static Uri GetOperationInfo(MethodInfo operation, Uri baseAddress, out string method, out IOperationBehavior webbehavior,//out WebInvokeAttribute webinvoke, out OperationContractAttribute operationcontract, out WebMessageFormat requestformat, out WebMessageFormat responseformat) { object[] customAttributes = operation.GetCustomAttributes(false); webbehavior = customAttributes.Single(a => a is WebInvokeAttribute || a is WebGetAttribute) as IOperationBehavior; operationcontract = customAttributes.Single(a => a is OperationContractAttribute) as OperationContractAttribute; if (webbehavior is WebInvokeAttribute) { requestformat = ((WebInvokeAttribute)webbehavior).RequestFormat; responseformat = ((WebInvokeAttribute)webbehavior).ResponseFormat; Uri relative = new Uri(((WebInvokeAttribute)webbehavior).UriTemplate, UriKind.Relative); Uri endpoint = new Uri(baseAddress, relative); method = ((WebInvokeAttribute)webbehavior).Method; return(endpoint); } else if (webbehavior is WebGetAttribute) { requestformat = ((WebGetAttribute)webbehavior).RequestFormat; responseformat = ((WebGetAttribute)webbehavior).ResponseFormat; Uri relative = new Uri(((WebGetAttribute)webbehavior).UriTemplate, UriKind.Relative); Uri endpoint = new Uri(baseAddress, relative); method = "GET"; return(endpoint); } else { throw new NotSupportedException(webbehavior.GetType().FullName + " is not supported."); } }
public WebHttpBehavior() { defaultOutgoingRequestFormat = WebMessageFormat.Xml; defaultOutgoingReplyFormat = WebMessageFormat.Xml; this.defaultBodyStyle = WebMessageBodyStyle.Bare; xmlSerializerManager = new UnwrappedTypesXmlSerializerManager(); }
static long Serialize(Stream stream, object instance, WebMessageFormat requestFormat, IEnumerable <Type> knownTypes = null) { dynamic serializer; //DataContractJsonSerializer or DataContractSerializer Type elementType = instance.GetType(); if (knownTypes == null) { knownTypes = new Type[] { elementType }; } switch (requestFormat) { case WebMessageFormat.Json: serializer = new DataContractJsonSerializer(elementType, knownTypes); break; case WebMessageFormat.Xml: serializer = new DataContractSerializer(elementType, knownTypes); break; default: serializer = new DataContractSerializer(elementType, knownTypes); break; } serializer.WriteObject(stream, instance); return(0); //return stream.Length; }
public WcfServiceHostFactory AddSecureRestfulEndPoint( string address, bool helpEnabled = false, bool automaticFormatSelectionEnabled = false, WebMessageBodyStyle defaultBodyStyle = WebMessageBodyStyle.Bare, WebMessageFormat defaultOutgoingRequestFormat = WebMessageFormat.Xml, WebMessageFormat defaultOutgoingResponseFormat = WebMessageFormat.Xml, bool crossDomainScriptAccessEnabled = false) { var endPointPrameters = new EndPointParameters { Address = address, Binding = new WebHttpBinding { CrossDomainScriptAccessEnabled = crossDomainScriptAccessEnabled, CloseTimeout = new TimeSpan(0, 15, 0), OpenTimeout = new TimeSpan(0, 15, 0), ReceiveTimeout = new TimeSpan(0, 15, 0), SendTimeout = new TimeSpan(0, 15, 0), AllowCookies = false, BypassProxyOnLocal = false, HostNameComparisonMode = HostNameComparisonMode.StrongWildcard, MaxBufferSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue, TransferMode = TransferMode.Buffered, UseDefaultWebProxy = true, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxDepth = 2000000, MaxStringContentLength = int.MaxValue, MaxArrayLength = int.MaxValue, MaxBytesPerRead = int.MaxValue, MaxNameTableCharCount = int.MaxValue }, Security = new WebHttpSecurity { Mode = WebHttpSecurityMode.Transport, Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.None } } } }; endPointPrameters.Behaviors .Add(new WebHttpBehavior { AutomaticFormatSelectionEnabled = true, DefaultOutgoingRequestFormat = WebMessageFormat.Json, DefaultOutgoingResponseFormat = WebMessageFormat.Json, DefaultBodyStyle = WebMessageBodyStyle.Bare, HelpEnabled = true }); _endPoints.Add(endPointPrameters); return(this); }
public MultiplexingDispatchMessageFormatter(Dictionary <WebMessageFormat, IDispatchMessageFormatter> formatters, WebMessageFormat defaultFormat) { if (formatters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatters"); } this.formatters = formatters; this.defaultFormat = defaultFormat; this.defaultContentTypes = new Dictionary <WebMessageFormat, string>(); Fx.Assert(this.formatters.ContainsKey(this.defaultFormat), "The default format should always be included in the dictionary of formatters."); }
public MultiplexingDispatchMessageFormatter(Dictionary<WebMessageFormat, IDispatchMessageFormatter> formatters, WebMessageFormat defaultFormat) { if (formatters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatters"); } this.formatters = formatters; this.defaultFormat = defaultFormat; this.defaultContentTypes = new Dictionary<WebMessageFormat, string>(); Fx.Assert(this.formatters.ContainsKey(this.defaultFormat), "The default format should always be included in the dictionary of formatters."); }
public WebHttpErrorHandler(WebMessageFormat format) { if (format == WebMessageFormat.Json) { this.format = WebContentFormat.Json; } else { this.format = WebContentFormat.Xml; } }
public static Stream ToMessageStream <T>(T obj, WebMessageFormat format, string callback) where T : new() { if ((object)obj == null) { throw new ArgumentNullException("obj"); } if (format == WebMessageFormat.Json) { return(MessageReader.ToJsonMessageStream <T>(obj, callback)); } return(MessageReader.ToXmlMessageStream <T>(obj)); }
void SetFormatAndContentType(WebMessageFormat format, string contentType) { OutgoingWebResponseContext outgoingResponse = WebOperationContext.Current.OutgoingResponse; outgoingResponse.Format = format; outgoingResponse.AutomatedFormatSelectionContentType = contentType; if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AutomaticFormatSelectedRequestBased, SR2.GetString(SR2.TraceCodeAutomaticFormatSelectedRequestBased, format.ToString(), contentType)); } }
private string ConvertWebMessageFormatToContentType(WebMessageFormat format) { switch (format) { case WebMessageFormat.Xml: return("application/xml"); case WebMessageFormat.Json: default: return("application/json"); } }
protected WebContentFormat ToContentFormat(WebMessageFormat src) { switch (src) { case WebMessageFormat.Xml: return(WebContentFormat.Xml); case WebMessageFormat.Json: return(WebContentFormat.Json); } throw new SystemException("INTERNAL ERROR: should not happen"); }
/// <summary> /// Initializes a new instance of the web service. /// </summary> protected SelfHostingService() { Type type = GetType(); m_endpoints = string.Empty; m_contractInterface = type.Namespace + ".I" + type.Name + ", " + type.AssemblyQualifiedName.ToNonNullString().Split(',')[1].Trim(); m_allowCrossDomainAccess = false; m_allowedDomainList = "*"; m_serviceEnabled = true; m_faultExceptionEnabled = true; m_defaultOutgoingRequestFormat = WebMessageFormat.Xml; m_defaultOutgoingResponseFormat = WebMessageFormat.Xml; }
public static Stream SerializeSystemBoolean(bool obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var root = new XElement(XName.Get("Boolean")); var xDocument = new XDocument(root); root.Add(XmlConvert.ToString(obj)); var stream = GetStream(xDocument); return stream; } else { return GetStream(obj.ToJsonString()); } }
protected WebContentFormat ToContentFormat(WebMessageFormat src, object result) { if (result is Stream) { return(WebContentFormat.Raw); } switch (src) { case WebMessageFormat.Xml: return(WebContentFormat.Xml); case WebMessageFormat.Json: return(WebContentFormat.Json); } throw new SystemException("INTERNAL ERROR: should not happen"); }
public static void CreateHttpWebRequest(Uri absoluteUri, object instance, Action <Stream> callback, string method = "POST", WebMessageFormat requestFormat = WebMessageFormat.Xml, WebMessageFormat responseFormat = WebMessageFormat.Xml, IEnumerable <Type> knownTypes = null ) { Stream postStream; HttpWebRequest request; HttpWebResponse response; #if SILVERLIGHT request = WebRequest.CreateHttp(absoluteUri); #else request = WebRequest.Create(absoluteUri) as HttpWebRequest; #endif request.Method = method; AsyncCallback responseCallback = (ar2) => { HttpWebRequest request2 = (HttpWebRequest)ar2.AsyncState; response = (HttpWebResponse)request2.EndGetResponse(ar2); Stream stream = response.GetResponseStream(); callback(stream); //stream.Position = 0;//NotSupportedException: Specified method is not supported. }; if (method == "POST" && instance != null) { request.ContentType = requestFormat == WebMessageFormat.Json ? "application/json" : "application/xml"; AsyncCallback requestCallback = (ar1) => { postStream = request.EndGetRequestStream(ar1); Serialize(postStream, instance, requestFormat, knownTypes: knownTypes); postStream.Close(); request.BeginGetResponse(responseCallback, request); //GetResponse }; request.BeginGetRequestStream(requestCallback, request); } else { request.ContentLength = 0; request.BeginGetResponse(responseCallback, request); } }
void SetFormatFromDefault(string operationName, string acceptHeader) { Fx.Assert(this.formatters.ContainsKey(operationName), "The calling method is responsible for ensuring that the 'operationName' key exists in the formatters dictionary."); WebMessageFormat format = this.formatters[operationName].DefaultFormat; if (!string.IsNullOrEmpty(acceptHeader)) { this.caches[operationName].AddOrUpdate(acceptHeader.ToUpperInvariant(), new FormatContentTypePair(format, null)); } WebOperationContext.Current.OutgoingResponse.Format = format; if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AutomaticFormatSelectedOperationDefault, SR2.GetString(SR2.TraceCodeAutomaticFormatSelectedOperationDefault, format.ToString())); } }
protected WebMessageFormat SetWebMessageFormat(string format) { WebOperationContext.Current.OutgoingResponse.Format = new WebMessageFormat?(); WebMessageFormat webMessageFormat = WebMessageFormat.Xml; if (!string.IsNullOrWhiteSpace(format) && format.ToLower() == "json") { this.ContentType = "application/json"; webMessageFormat = WebMessageFormat.Json; } else { this.ContentType = "application/xml"; } this.ContentType = "text/plain; " + this.ContentType; this.ContentType += "; charset=utf-8"; return(webMessageFormat); }
public override void WriteDetail(XmlWriter writer, WebMessageFormat format) { if (format == WebMessageFormat.Xml) { if (this.Detail != null) { string html = String.Format(CultureInfo.InvariantCulture, xhtmlFormat, this.StatusCode.ToString(), this.Detail); XElement element = XElement.Load(new StringReader(html)); element.WriteTo(writer); } } else { new DataContractJsonSerializer(typeof(JsonErrorData)).WriteObject(writer, new JsonErrorData() { Detail = this.Detail }); } }
static Uri GetOperationInfo(MethodInfo operation, Uri baseAddress, out string method, out WebInvokeAttribute webinvoke, out OperationContractAttribute operationcontract, out WebMessageFormat requestformat, out WebMessageFormat responseformat) { object[] customAttributes = operation.GetCustomAttributes(false); webinvoke = customAttributes.Single(a => a is WebInvokeAttribute) as WebInvokeAttribute; method = webinvoke.Method; operationcontract = customAttributes.Single(a => a is OperationContractAttribute) as OperationContractAttribute; requestformat = webinvoke.RequestFormat; responseformat = webinvoke.ResponseFormat; Uri relative = new Uri(webinvoke.UriTemplate, UriKind.Relative); Uri endpoint = new Uri(baseAddress, relative); return(endpoint); }
public static Stream SerializeSystemBooleanArray(bool[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var root = new XElement(XName.Get("BooleanArray")); var xDocument = new XDocument(root); foreach (var obj in objs) { var child = new XElement(XName.Get("Boolean")); child.Add(XmlConvert.ToString(obj)); } var stream = GetStream(xDocument); return stream; } else { return GetStream(objs.ToJsonString()); } }
public void JsonValueReturnContentTypeIsJsonWithAllDefaultResponseFormats() { WebHttpBinding binding = new WebHttpBinding(); WebMessageFormat[] defaultResponseFormats = new WebMessageFormat[] { WebMessageFormat.Json, WebMessageFormat.Xml }; foreach (WebMessageFormat format in defaultResponseFormats) { WebHttpBehavior3 behavior = new WebHttpBehavior3 { DefaultOutgoingResponseFormat = format }; Test( binding, behavior, "POST", WebHttpBehavior3Tests.Endpoint + "/EchoPost", WebHttpBehavior3Tests.FormUrlEncodedContentType, "a=1&b=2", HttpStatusCode.OK, WebHttpBehavior3Tests.ApplicationJsonContentTypeWithCharset, "{\"a\":\"1\",\"b\":\"2\"}"); Test( binding, behavior, "POST", WebHttpBehavior3Tests.Endpoint + "/EchoPostWithWebInvoke", WebHttpBehavior3Tests.FormUrlEncodedContentType, "a=1&b=2", HttpStatusCode.OK, WebHttpBehavior3Tests.ApplicationJsonContentTypeWithCharset, "{\"a\":\"1\",\"b\":\"2\"}"); Test( binding, behavior, "GET", WebHttpBehavior3Tests.Endpoint + "/EchoGet?a=1&b=2", null, null, HttpStatusCode.OK, WebHttpBehavior3Tests.ApplicationJsonContentTypeWithCharset, "{\"a\":\"1\",\"b\":\"2\"}"); } }
public static object Deserialize(Type type, Stream stream, WebMessageFormat responseformat = WebMessageFormat.Json) { dynamic serializer; IEnumerable <Type> knownTypes = new Type[] { type, }; switch (responseformat) { case WebMessageFormat.Json: serializer = new DataContractJsonSerializer(type, knownTypes); break; case WebMessageFormat.Xml: serializer = new DataContractSerializer(type, knownTypes); break; default: serializer = new DataContractJsonSerializer(type, knownTypes); break; } return(serializer.ReadObject(stream)); }
private object Deserialize(Type type, Stream stream, WebMessageFormat responseformat = WebMessageFormat.Json) { dynamic serializer; _knownTypes.Add(type); switch (responseformat) { case WebMessageFormat.Json: serializer = new DataContractJsonSerializer(type, _knownTypes); break; case WebMessageFormat.Xml: serializer = new DataContractSerializer(type, _knownTypes); break; default: serializer = new DataContractJsonSerializer(type, _knownTypes); break; } return(serializer.ReadObject(stream)); }
public void ValuesTest() { bool anyBool1 = AnyInstance.AnyBool; bool anyBool2 = !AnyInstance.AnyBool; bool anyBool3 = AnyInstance.AnyBool; WebMessageBodyStyle anyBodyStyle = WebMessageBodyStyle.Bare; WebMessageFormat anyMessageFormat = WebMessageFormat.Xml; string configXml = CreateConfig(anyBool1, anyBodyStyle, anyMessageFormat, anyBool2, anyBool3); TestjQueryConfigurationSection configSection = TestjQueryConfigurationSection.GetWebHttpBehavior3Section(configXml); WebHttpElement3 element = configSection.WebHttpElement3; Assert.AreEqual(typeof(WebHttpBehavior3), element.BehaviorType); Assert.AreEqual(anyBool1, element.AutomaticFormatSelectionEnabled); Assert.AreEqual(anyBodyStyle, element.DefaultBodyStyle); Assert.AreEqual(anyMessageFormat, element.DefaultOutgoingResponseFormat); Assert.AreEqual(anyBool2, element.FaultExceptionEnabled); Assert.AreEqual(anyBool3, element.HelpEnabled); }
long Serialize(Stream stream, object instance, WebMessageFormat requestFormat) { dynamic serializer; //DataContractJsonSerializer or DataContractSerializer (XmlObjectSerializer d.n.e. in SL) Type elementType = instance.GetType(); this._knownTypes.Add(elementType); switch (requestFormat) { case WebMessageFormat.Json: serializer = new DataContractJsonSerializer(elementType, _knownTypes); break; case WebMessageFormat.Xml: serializer = new DataContractSerializer(elementType, _knownTypes); break; default: serializer = new DataContractSerializer(elementType, _knownTypes); break; } serializer.WriteObject(stream, instance); return(0); //return stream.Length; }
bool TrySetFormatFromAcceptHeader(string operationName, string acceptHeader, bool matchCharSet) { Fx.Assert(this.formatters.ContainsKey(operationName), "The calling method is responsible for ensuring that the 'operationName' key exists in the formatters dictionary."); IList <ContentType> acceptHeaderElements = WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements(); for (int i = 0; i < acceptHeaderElements.Count; i++) { string[] typeAndSubType = acceptHeaderElements[i].MediaType.Split('/'); string type = typeAndSubType[0].Trim().ToLowerInvariant(); string subType = typeAndSubType[1].Trim(); if ((subType[0] == '*' && subType.Length == 1) && ((type[0] == '*' && type.Length == 1) || wildcardMediaTypes.Contains(type))) { SetFormatFromDefault(operationName, acceptHeader); return(true); } foreach (MultiplexingFormatMapping mapping in mappings) { ContentType contentType; WebMessageFormat format = mapping.MessageFormat; if (this.formatters[operationName].SupportsMessageFormat(format) && mapping.CanFormatResponse(acceptHeaderElements[i], matchCharSet, out contentType)) { string contentTypeStr = contentType.ToString(); this.caches[operationName].AddOrUpdate(acceptHeader.ToUpperInvariant(), new FormatContentTypePair(format, contentTypeStr)); SetFormatAndContentType(format, contentTypeStr); return(true); } } } return(false); }
private void ProcessWebAttribute() { // Find all web attributess var webGetAttribute = InterfaceMethod.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName == WcfAttributeConstants.WebGetAttribute); var webInvokeAttribute = InterfaceMethod.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName == WcfAttributeConstants.WebInvokeAttribute); if (webGetAttribute == null) { if (webInvokeAttribute == null) { webMode = WebMode.None; } else { webMode = GetWebMode(InterfaceMethod, webInvokeAttribute); requestFormat = GetRequestFormat(InterfaceMethod, webInvokeAttribute); responseFormat = GetResponseFormat(InterfaceMethod, webInvokeAttribute); uriTemplate = GetUriTemplate(InterfaceMethod, webInvokeAttribute); } } else { if (webInvokeAttribute == null) { webMode = WebMode.Get; responseFormat = GetResponseFormat(InterfaceMethod, webGetAttribute); uriTemplate = GetUriTemplate(InterfaceMethod, webGetAttribute); } else { throw new NotSupportedException( string.Format("Both WebGet and WebInvoke attributes are specified on the same method '{0}'", InterfaceMethod.FullName)); } } }
internal override bool UseBareReplyFormatter(WebMessageBodyStyle style, OperationDescription operationDescription, WebMessageFormat responseFormat, out Type parameterType) { if (responseFormat == WebMessageFormat.Json) { parameterType = null; return false; } return base.UseBareReplyFormatter(style, operationDescription, responseFormat, out parameterType); }
public abstract void WriteDetail(XmlWriter writer, WebMessageFormat format);
public override void WriteDetail(XmlWriter writer, WebMessageFormat format) { if (this.Element != null) { this.Element.WriteTo(writer); } }
public ProductEndpointWebHttpBehavior() { this.defaultOutgoingRequestFormat = WebMessageFormat.Json; this.defaultOutgoingResponseFormat = WebMessageFormat.Json; }
public static short[] DeserializeSystemInt16Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var doc = GetXDocument(stream); return DeserializeSystemInt16Array(doc.Root); } else { var jsonArray = GetJSONArray(stream); return DeserializeSystemInt16Array(jsonArray); } }
private T Deserialize <T>(Stream stream, WebMessageFormat responseformat = WebMessageFormat.Json) { return((T)Deserialize(typeof(T), stream, responseformat)); }
private string ConvertWebMessageFormatToContentType(WebMessageFormat format) { switch (format) { case WebMessageFormat.Xml: return "application/xml"; case WebMessageFormat.Json: default: return "application/json"; } }
public static DateTime DeserializeSystemDateTime(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var doc = GetXDocument(stream); return DeserializeSystemDateTime(doc.Root); } else { var json = GetString(stream, true); return JsonConvert.ToDateTime(json); } }
Message SerializeReplyCore(MessageVersion messageVersion, object [] parameters, object result) { if (parameters == null) { throw new ArgumentNullException("parameters"); } CheckMessageVersion(messageVersion); MessageDescription md = GetMessageDescription(MessageDirection.Output); // FIXME: use them. // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> (); // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null); // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> (); // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ()); WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat; string mediaType = null; XmlObjectSerializer serializer = null; // FIXME: serialize ref/out parameters as well. string name = null, ns = null; switch (msgfmt) { case WebMessageFormat.Xml: serializer = GetSerializer(WebContentFormat.Xml); mediaType = "application/xml"; name = IsResponseBodyWrapped ? md.Body.WrapperName : null; ns = IsResponseBodyWrapped ? md.Body.WrapperNamespace : null; break; case WebMessageFormat.Json: serializer = GetSerializer(WebContentFormat.Json); mediaType = "application/json"; name = IsResponseBodyWrapped ? (BodyName ?? md.Body.ReturnValue.Name) : null; ns = String.Empty; break; } bool json = msgfmt == WebMessageFormat.Json; Message ret = Message.CreateMessage(MessageVersion.None, null, new WrappedBodyWriter(result, serializer, name, ns, json)); // Message properties var hp = new HttpResponseMessageProperty(); // FIXME: get encoding from somewhere hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8"; // apply user-customized HTTP results via WebOperationContext. WebOperationContext.Current.OutgoingResponse.Apply(hp); // FIXME: fill some properties if required. ret.Properties.Add(HttpResponseMessageProperty.Name, hp); var wp = new WebBodyFormatMessageProperty(ToContentFormat(msgfmt)); ret.Properties.Add(WebBodyFormatMessageProperty.Name, wp); return(ret); }
//private IEnumerable<IDispatchMessageInspector> _messageInspectors { get; set; } public ProductEndpointWebHttpBehavior() { //_messageInspectors = new List<IDispatchMessageInspector>(); this.defaultOutgoingRequestFormat = WebMessageFormat.Json; this.defaultOutgoingResponseFormat = WebMessageFormat.Json; }
public static short DeserializeSystemInt16(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var doc = GetXDocument(stream); return DeserializeSystemInt16(doc.Root); } else { var json = GetString(stream); return short.Parse(json); } }
internal static bool IsDefined(WebMessageFormat format) { return (format == WebMessageFormat.Xml || format == WebMessageFormat.Json); }
public static Stream WebInvoke(Uri uri, Verb verb, Stream input, WebMessageFormat requestFormat, bool hasOutput) { var request = WebRequest.Create(uri); switch (verb) { case Verb.Get: request.Method = "GET"; break; case Verb.Post: request.Method = "POST"; break; case Verb.Put: request.Method = "PUT"; break; case Verb.Delete: request.Method = "DELETE"; break; default: throw new NotSupportedException(); } if (input != null) { input.Seek(0L, SeekOrigin.Begin); switch (requestFormat) { case WebMessageFormat.Xml: request.ContentType = "application/xml"; break; case WebMessageFormat.Json: request.ContentType = "application/json"; break; } request.ContentLength = input.Length; using (var requestStream = request.GetRequestStream()) { var bytes = new byte[1024]; var read = 1; while (read > 0) { read = input.Read(bytes, 0, bytes.Length); requestStream.Write(bytes, 0, read); } } } try { using (var response = request.GetResponse()) { if (!hasOutput) { return(null); } var length = (int)response.ContentLength; var copy = (length > 0) ? new MemoryStream(length) : new MemoryStream(); response.GetResponseStream().CopyTo(copy); copy.Seek(0L, SeekOrigin.Begin); return(copy); } } catch (WebException ex) { var message = string.Format("The remote server returned an unexpected response: {0}", ex.Message); throw new CommunicationException(message, ex); } }
public static Stream WebInvoke(Uri uri, Verb verb, Stream input, WebMessageFormat requestFormat, bool hasOutput) { var request = WebRequest.Create(uri); switch (verb) { case Verb.Get: request.Method = "GET"; break; case Verb.Post: request.Method = "POST"; break; case Verb.Put: request.Method = "PUT"; break; case Verb.Delete: request.Method = "DELETE"; break; default: throw new NotSupportedException(); } if (input != null) { input.Seek(0L, SeekOrigin.Begin); switch (requestFormat) { case WebMessageFormat.Xml: request.ContentType = "application/xml"; break; case WebMessageFormat.Json: request.ContentType = "application/json"; break; } request.ContentLength = input.Length; using (var requestStream = request.GetRequestStream()) { var bytes = new byte[1024]; var read = 1; while (read > 0) { read = input.Read(bytes, 0, bytes.Length); requestStream.Write(bytes, 0, read); } } } try { using (var response = request.GetResponse()) { if (!hasOutput) return null; var length = (int) response.ContentLength; var copy = (length > 0) ? new MemoryStream(length) : new MemoryStream(); response.GetResponseStream().CopyTo(copy); copy.Seek(0L, SeekOrigin.Begin); return copy; } } catch (WebException ex) { var message = string.Format("The remote server returned an unexpected response: {0}", ex.Message); throw new CommunicationException(message, ex); } }
private static WebBodyFormatMessageProperty GetBodyFormat(WebMessageFormat webMessageFormat) { return new WebBodyFormatMessageProperty((WebContentFormat) Enum.Parse(typeof(WebContentFormat), webMessageFormat.ToString())); }
public WebHttp3Values(bool automaticFormatSelectionEnabledValue, WebMessageBodyStyle defaultBodyStyleValue, WebMessageFormat defaultOutgoingResponseFormatValue, bool faultExceptionEnabledValue, bool helpEnabledValue) { this.AutomaticFormatSelectionEnabledValue = automaticFormatSelectionEnabledValue; this.DefaultBodyStyleValue = defaultBodyStyleValue; this.DefaultOutgoingResponseFormatValue = defaultOutgoingResponseFormatValue; this.FaultExceptionEnabledValue = faultExceptionEnabledValue; this.HelpEnabledValue = helpEnabledValue; }
Message SerializeReplyCore(MessageVersion messageVersion, object [] parameters, object result) { // parameters could be null. // result could be null. For Raw output, it becomes no output. CheckMessageVersion(messageVersion); MessageDescription md = GetMessageDescription(MessageDirection.Output); // FIXME: use them. // var dcob = Operation.Behaviors.Find<DataContractSerializerOperationBehavior> (); // XmlObjectSerializer xos = dcob.CreateSerializer (result.GetType (), md.Body.WrapperName, md.Body.WrapperNamespace, null); // var xsob = Operation.Behaviors.Find<XmlSerializerOperationBehavior> (); // XmlSerializer [] serializers = XmlSerializer.FromMappings (xsob.GetXmlMappings ().ToArray ()); WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat; XmlObjectSerializer serializer = null; // FIXME: serialize ref/out parameters as well. string name = null, ns = null; switch (msgfmt) { case WebMessageFormat.Xml: serializer = GetSerializer(WebContentFormat.Xml, IsResponseBodyWrapped, md.Body.ReturnValue); name = IsResponseBodyWrapped ? md.Body.WrapperName : null; ns = IsResponseBodyWrapped ? md.Body.WrapperNamespace : null; break; case WebMessageFormat.Json: serializer = GetSerializer(WebContentFormat.Json, IsResponseBodyWrapped, md.Body.ReturnValue); name = IsResponseBodyWrapped ? (BodyName ?? md.Body.ReturnValue.Name) : null; ns = String.Empty; break; } var contentFormat = ToContentFormat(msgfmt, result); string mediaType = GetMediaTypeString(contentFormat); Message ret = contentFormat == WebContentFormat.Raw ? new RawMessage((Stream)result) : Message.CreateMessage(MessageVersion.None, null, new WrappedBodyWriter(result, serializer, name, ns, contentFormat)); // Message properties var hp = new HttpResponseMessageProperty(); // FIXME: get encoding from somewhere hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8"; // apply user-customized HTTP results via WebOperationContext. if (WebOperationContext.Current != null) // this formatter must be available outside ServiceHost. { WebOperationContext.Current.OutgoingResponse.Apply(hp); } // FIXME: fill some properties if required. ret.Properties.Add(HttpResponseMessageProperty.Name, hp); var wp = new WebBodyFormatMessageProperty(contentFormat); ret.Properties.Add(WebBodyFormatMessageProperty.Name, wp); return(ret); }
private static Message CreateMessage(RestErrorMessage restErrorMessage, MessageVersion version, WebMessageFormat webMessageFormat) { if (webMessageFormat == WebMessageFormat.Json) { return Message.CreateMessage(version, null, restErrorMessage, new DataContractJsonSerializer(restErrorMessage.GetType())); } if (webMessageFormat == WebMessageFormat.Xml) { return Message.CreateMessage(version, null, restErrorMessage); } return null; }
internal virtual bool UseBareReplyFormatter(WebMessageBodyStyle style, OperationDescription operationDescription, WebMessageFormat responseFormat, out Type parameterType) { parameterType = null; return IsBareResponse(style) && TryGetNonMessageParameterType(operationDescription.Messages[1], operationDescription, false, out parameterType); }
public static bool DeserializeSystemBoolean(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var doc = GetXDocument(stream); return DeserializeSystemBoolean(doc.Root); } else { var json = GetString(stream); var tokenizer = new JSONTokener(json); return bool.Parse(tokenizer.NextValue().ToString()); } }
public static char DeserializeSystemChar(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var doc = GetXDocument(stream); return DeserializeSystemChar(doc.Root); } else { var json = GetString(stream, true); return char.Parse(json); } }
public bool SupportsMessageFormat(WebMessageFormat format) { return this.formatters.ContainsKey(format); }
protected WebContentFormat ToContentFormat (WebMessageFormat src, object result) { if (result is Stream) return WebContentFormat.Raw; switch (src) { case WebMessageFormat.Xml: return WebContentFormat.Xml; case WebMessageFormat.Json: return WebContentFormat.Json; } throw new SystemException ("INTERNAL ERROR: should not happen"); }
public static Guid DeserializeSystemGuid(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat) { if (IsXml(serializationFormat, webMessageFormat)) { var doc = GetXDocument(stream); return DeserializeSystemGuid(doc.Root); } else { var json = GetString(stream, true); return new Guid(json); } }
public virtual Message SerializeRequest(MessageVersion messageVersion, object [] parameters) { if (parameters == null) { throw new ArgumentNullException("parameters"); } CheckMessageVersion(messageVersion); var c = new Dictionary <string, string> (); MessageDescription md = GetMessageDescription(MessageDirection.Input); Message ret; Uri to; object msgpart = null; for (int i = 0; i < parameters.Length; i++) { var p = md.Body.Parts [i]; string name = p.Name.ToUpper(CultureInfo.InvariantCulture); if (UriTemplate.PathSegmentVariableNames.Contains(name) || UriTemplate.QueryValueVariableNames.Contains(name)) { c.Add(name, parameters [i] != null ? Converter.ConvertValueToString(parameters [i], parameters [i].GetType()) : null); } else { // FIXME: bind as a message part if (msgpart == null) { msgpart = parameters [i]; } else { throw new NotImplementedException(String.Format("More than one parameters including {0} that are not contained in the URI template {1} was found.", p.Name, UriTemplate)); } } } ret = Message.CreateMessage(messageVersion, (string)null, msgpart); to = UriTemplate.BindByName(Endpoint.Address.Uri, c); ret.Headers.To = to; var hp = new HttpRequestMessageProperty(); hp.Method = Info.Method; WebMessageFormat msgfmt = Info.IsResponseFormatSetExplicitly ? Info.ResponseFormat : Behavior.DefaultOutgoingResponseFormat; var contentFormat = ToContentFormat(msgfmt, msgpart); string mediaType = GetMediaTypeString(contentFormat); // FIXME: get encoding from somewhere hp.Headers ["Content-Type"] = mediaType + "; charset=utf-8"; #if !NET_2_1 if (WebOperationContext.Current != null) { WebOperationContext.Current.OutgoingRequest.Apply(hp); } #endif // FIXME: set hp.SuppressEntityBody for some cases. ret.Properties.Add(HttpRequestMessageProperty.Name, hp); var wp = new WebBodyFormatMessageProperty(ToContentFormat(Info.IsRequestFormatSetExplicitly ? Info.RequestFormat : Behavior.DefaultOutgoingRequestFormat, null)); ret.Properties.Add(WebBodyFormatMessageProperty.Name, wp); return(ret); }
public override void WriteDetail(XmlWriter writer, WebMessageFormat format) { if (this.Detail != null) { this.SerializerFactory(format).WriteObject(writer, this.Detail); } }
internal protected virtual void WriteDetail(XmlWriter writer, WebMessageFormat format) { this.detailWriter.WriteDetail(writer, format); }