Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using Onyx.Payments.Models;
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Net;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Json;
- using System.ServiceModel;
- using System.ServiceModel.Channels;
- using System.ServiceModel.Description;
- using System.ServiceModel.Dispatcher;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Xml;
- using System.Linq;
- using System.Collections.Generic;
- namespace JsonNetMessageFormatter
- {
- class NewtonsoftJsonClientFormatter : IClientMessageFormatter
- {
- OperationDescription operation;
- Uri operationUri;
- public NewtonsoftJsonClientFormatter(OperationDescription operation, ServiceEndpoint endpoint, JsonSerializerSettings settings)
- {
- this.JsonSettings = settings;
- this.operation = operation;
- string endpointAddress = endpoint.Address.Uri.ToString();
- if (!endpointAddress.EndsWith("/"))
- {
- endpointAddress = endpointAddress + "/";
- }
- WebInvokeAttribute wia = operation.Behaviors.Find<WebInvokeAttribute>();
- if (wia != null && !String.IsNullOrEmpty(wia.UriTemplate))
- {
- this.operationUri = new Uri(endpointAddress + wia.UriTemplate);
- }
- else
- {
- this.operationUri = new Uri(endpointAddress + operation.Name);
- }
- }
- public object DeserializeReply(Message message, object[] parameters)
- {
- object bodyFormatProperty;
- if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
- ((bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Json))
- {
- throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
- }
- Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
- this.SetupSerializer(serializer);
- serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
- XmlDictionaryReader reader = buffer.CreateMessage().GetReaderAtBodyContents();
- XmlDocument request = new XmlDocument();
- request.LoadXml(reader.ReadOuterXml());
- string jsonText = String.Empty;// JsonConvert.SerializeXmlNode(request.DocumentElement);
- var sbuilder = new StringBuilder();
- using (var swriter = new StringWriter(sbuilder))
- {
- using (var jwriter = new JsonTextWriter(swriter))
- {
- serializer.Serialize(jwriter, request.DocumentElement);
- jwriter.Flush();
- jwriter.Close();
- jsonText = sbuilder.ToString();
- }
- }
- Newtonsoft.Json.Linq.JObject jobject = null;
- using (var sreader = new StringReader(jsonText))
- {
- using (var jreader = new JsonTextReader(sreader))
- {
- serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- jobject = serializer.Deserialize<Newtonsoft.Json.Linq.JObject>(jreader);
- }
- }
- //var jobject = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(jsonText);
- StringBuilder sb = new StringBuilder();
- using (StringWriter sw = new StringWriter(sb))
- {
- using (JsonWriter jsonWriter = new JsonTextWriter(sw))
- {
- this.SetupWriter(jsonWriter);
- jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Local;
- // var cobject = ToObject(jobject);
- //Dictionary<string, object> list = cobject as Dictionary<string, object>;
- WriteDetails(jobject, jsonWriter);
- jsonWriter.Flush();
- jsonWriter.Close();
- }
- }
- jsonText = sb.ToString();
- if (operation.Messages.Count > 1 && operation.Messages[1].Body != null && operation.Messages[1].Body.ReturnValue != null && operation.Messages[1].Body.ReturnValue.Type != null)
- {
- using (var sreader = new StringReader(jsonText))
- {
- using (var jreader = new JsonTextReader(sreader))
- {
- serializer.DateTimeZoneHandling = DateTimeZoneHandling.Local;
- var deserializedObjectFromType = serializer.Deserialize(jreader, operation.Messages[1].Body.ReturnValue.Type.UnderlyingSystemType);
- return deserializedObjectFromType;
- }
- }
- }
- else
- {
- using (var sreader = new StringReader(jsonText))
- {
- using (var jreader = new JsonTextReader(sreader))
- {
- serializer.DateTimeZoneHandling = DateTimeZoneHandling.Local;
- var deserializedObject = serializer.Deserialize(jreader);
- return deserializedObject;
- }
- }
- }
- }
- private static Dictionary<string, object> ToArrayObject(JToken token)
- {
- Dictionary<string, object> citem = new Dictionary<string, object>();
- Dictionary<string, object> dict = new Dictionary<string, object>();
- var tlist = token.Values().ToList();
- int citemIndex = 0;
- int dictIndex = 0;
- while (tlist.FindIndex(cc => cc as JProperty != null && (cc as JProperty).Name == "@type" && (cc as JProperty).Value.ToString() == "object") > -1)
- {
- citem = new Dictionary<string, object>();
- var cindex = tlist.FindIndex(cc => cc as JProperty != null && (cc as JProperty).Name == "@type" && (cc as JProperty).Value.ToString() == "object");
- var nindex = tlist.FindIndex(cindex + 1, cc => cc as JProperty != null && (cc as JProperty).Name == "@type" && (cc as JProperty).Value.ToString() == "object");
- if (nindex < 0)
- {
- nindex = tlist.Count();
- }
- citemIndex = 0;
- for (int x = cindex + 1; x < nindex; x++)
- {
- var ctype = tlist[x] as JProperty;
- var currentItem = ctype.Values().Where(cc => cc as JProperty != null && (cc as JProperty).Name == "@type").Select(cc => cc as JProperty).FirstOrDefault();
- //citem.Add(tlist[x]);
- if (currentItem != null && currentItem.Value.ToString() == "array")
- {
- citem.Add(String.Format("Item{0}", citemIndex), ToArrayObject(tlist[x]));
- }
- else if (ctype != null)
- {
- var val = ctype.Values().Where(cc => cc as JProperty != null && (cc as JProperty).Name != "@type").Select(cc => cc as JProperty).FirstOrDefault();
- citem.Add(ctype.Name, val.Value);
- }
- citemIndex += 1;
- }
- tlist.RemoveRange(cindex, nindex);
- dict.Add(String.Format("Item{0}", dictIndex), citem);
- dictIndex += 1;
- }
- if (dict != null && dict.Count != 0)
- {
- return dict;
- }
- else
- {
- dict = new Dictionary<string, object>();
- dictIndex = 0;
- foreach (var value in tlist)
- {
- dict.Add(String.Format("Item{0}", dictIndex), ToObject(value));
- dictIndex += 1;
- }
- return dict;
- }
- }
- private static object ToObject(JToken token)
- {
- if (token.Type == JTokenType.Object)
- {
- Dictionary<string, object> dict = new Dictionary<string, object>();
- foreach (JProperty prop in ((JObject)token).Properties())
- {
- dict.Add(prop.Name, ToObject(prop.Value));
- }
- return dict;
- }
- else if (token.Type == JTokenType.Array)
- {
- return ToArrayObject(token);
- }
- else if (token.Type == JTokenType.Property)
- {
- Dictionary<string, object> dict = new Dictionary<string, object>();
- var obj = (((JProperty)token).Value as JObject);
- if (obj != null)
- {
- var result = ToObject(obj);
- return result;
- }
- else
- {
- return ((JProperty)token).Value.ToString();
- }
- }
- else
- {
- return ((JValue)token).Value;
- }
- }
- public String GetItemType(Dictionary<string, object> dict)
- {
- if (dict.ContainsKey("@type"))
- {
- return dict["@type"].ToString();
- }
- return "";
- }
- public class ItemInfo
- {
- public String Name { get; set; }
- public String Type { get; set; }
- public List<JToken> Values { get; set; }
- public JToken Value { get; set; }
- }
- public String GetPropertyInfo(JToken node)
- {
- return string.Empty;
- }
- public ItemInfo GetItemInfo(JToken node)
- {
- var answer = new ItemInfo();
- JProperty jproperty = node as JProperty;
- IEnumerable<JToken> nodes = null;
- var jObject = node as JObject;
- Boolean parse = true;
- if (jproperty == null)
- {
- var typenode = node.Where(cn => (cn as JProperty) != null && (cn as JProperty).Name == "@type").Select(cn => cn as JProperty).FirstOrDefault();
- if (node.FirstOrDefault(cn => (cn as JProperty) != null && (cn as JProperty).Name == "@type") != null)
- {
- answer.Type = typenode.Value.ToString();
- answer.Values = node.Where(cn => (cn as JProperty) != null && (cn as JProperty).Name != "@type").Select(cn => cn as JToken).ToList();
- parse = false;
- }
- else
- {
- var fnode = node.First as JProperty;
- if (fnode != null)
- {
- answer.Name = fnode.Name;
- }
- var cnodes = node.Values().Where(cn => cn as JToken != null).Select(ccn => ccn as JToken);
- nodes = cnodes.Values();
- }
- }
- else
- {
- var cnodes = jproperty.Values().ToList();
- answer.Name = jproperty.Name;
- nodes = cnodes.Where(cn => cn as JProperty != null).Select(cn => cn as JProperty);
- }
- if (parse)
- {
- var typeProperty = nodes.Where(cn => cn as JProperty != null && (cn as JProperty).Name == "@type").Select(ccn => (ccn as JProperty)).FirstOrDefault();
- var values = nodes.Where(cn => cn as JProperty != null && (cn as JProperty).Name != "@type").Select(ccn => (ccn as JToken)).ToList();
- if (typeProperty != null)
- {
- answer.Type = typeProperty.Value.ToString();
- }
- else
- {
- answer.Type = String.Empty;
- }
- answer.Values = values;
- }
- if (answer.Type != "object" && answer.Type != "array" && answer.Type != "null" && answer.Values != null && answer.Values.Count != 0)
- {
- answer.Value = answer.Values[0];
- if (answer.Value as JProperty != null)
- {
- answer.Value = (answer.Value as JProperty).Value;
- }
- }
- if (answer.Type == "array")
- {
- jproperty = answer.Values[0] as JProperty;
- answer.Values = jproperty.Values().ToList();
- }
- return answer;
- }
- public void WriteDetails(JObject node, JsonWriter jsonWriter)
- {
- var info = GetItemInfo(node);
- info.Name = String.Empty;
- switch (info.Type)
- {
- case "array":
- WriteArray(info, jsonWriter);
- break;
- case "object":
- WriteObject(info, jsonWriter);
- break;
- default:
- jsonWriter.WriteStartObject();
- WritePropertyValue(info.Name, info.Value, jsonWriter);
- jsonWriter.WriteEndObject();
- break;
- }
- }
- public void WriteArray(ItemInfo info, JsonWriter jsonWriter)
- {
- if (!String.IsNullOrEmpty(info.Name))
- {
- jsonWriter.WritePropertyName(info.Name);
- }
- jsonWriter.WriteStartArray();
- foreach (var item in info.Values)
- {
- var cinfo = GetItemInfo(item);
- switch (cinfo.Type)
- {
- case "object":
- WriteObject(cinfo, jsonWriter);
- break;
- case "array":
- WriteArray(cinfo, jsonWriter);
- break;
- default:
- jsonWriter.WriteStartObject();
- WritePropertyValue(cinfo.Name, cinfo.Value, jsonWriter);
- jsonWriter.WriteEndObject();
- break;
- }
- }
- jsonWriter.WriteEndArray();
- }
- public void WriteObject(ItemInfo info, JsonWriter jsonWriter)
- {
- ItemInfo cinfo = null;
- if (!String.IsNullOrEmpty(info.Name))
- {
- jsonWriter.WritePropertyName(info.Name);
- }
- jsonWriter.WriteStartObject();
- foreach (var item in info.Values)
- {
- cinfo = GetItemInfo(item);
- switch (cinfo.Type)
- {
- case "object":
- WriteObject(cinfo, jsonWriter);
- break;
- case "array":
- WriteArray(cinfo, jsonWriter);
- break;
- default:
- WritePropertyValue(cinfo.Name, cinfo.Value, jsonWriter);
- break;
- }
- //jsonWriter.WritePropertyName(item.);
- //jsonWriter.WriteValue(item.Value);
- }
- jsonWriter.WriteEndObject();
- }
- public void WritePropertyValue(String propertyName, Object value, JsonWriter jsonWriter)
- {
- jsonWriter.WritePropertyName(propertyName);
- if (value == null || (value != null && !String.IsNullOrEmpty(value.ToString())))
- {
- jsonWriter.WriteValue(value);
- }
- else
- {
- jsonWriter.WriteNull();
- }
- }
- private JsonSerializerSettings _JsonSettings;
- JsonSerializerSettings JsonSettings
- {
- get
- {
- var s = this._JsonSettings;
- if (s == null)
- {
- return JsonConvert.DefaultSettings();
- }
- return s;
- }
- set
- {
- this._JsonSettings = value;
- }
- }
- public void SetupSerializer(JsonSerializer serializer)
- {
- var settings = this.JsonSettings;
- if (settings != null)
- {
- settings.Converters.ToList().ForEach(ci => serializer.Converters.Add(ci));
- serializer.Formatting = settings.Formatting;
- serializer.DateTimeZoneHandling = settings.DateTimeZoneHandling;
- serializer.DateFormatString = settings.DateFormatString;
- serializer.DateFormatHandling = settings.DateFormatHandling;
- serializer.FloatFormatHandling = settings.FloatFormatHandling;
- serializer.FloatParseHandling = settings.FloatParseHandling;
- serializer.StringEscapeHandling = settings.StringEscapeHandling;
- serializer.Culture = settings.Culture;
- serializer.CheckAdditionalContent = settings.CheckAdditionalContent;
- serializer.ConstructorHandling = settings.ConstructorHandling;
- serializer.Context = settings.Context;
- serializer.ContractResolver = settings.ContractResolver;
- serializer.DefaultValueHandling = settings.DefaultValueHandling;
- serializer.MaxDepth = settings.MaxDepth;
- serializer.MissingMemberHandling = settings.MissingMemberHandling;
- serializer.NullValueHandling = settings.NullValueHandling;
- serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
- serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
- serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
- if (settings.ReferenceResolver != null)
- {
- serializer.ReferenceResolver = settings.ReferenceResolver;
- }
- serializer.StringEscapeHandling = settings.StringEscapeHandling;
- serializer.TraceWriter = settings.TraceWriter;
- serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat;
- serializer.TypeNameHandling = settings.TypeNameHandling;
- }
- }
- public void SetupWriter(JsonWriter writer)
- {
- var settings = this.JsonSettings;
- if (settings != null)
- {
- writer.Formatting = settings.Formatting;
- writer.DateTimeZoneHandling = settings.DateTimeZoneHandling;
- writer.DateFormatString = settings.DateFormatString;
- writer.DateFormatHandling = settings.DateFormatHandling;
- writer.FloatFormatHandling = settings.FloatFormatHandling;
- writer.StringEscapeHandling = settings.StringEscapeHandling;
- writer.Culture = settings.Culture;
- writer.StringEscapeHandling = settings.StringEscapeHandling;
- }
- }
- public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
- {
- byte[] body;
- Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
- #region mysettings
- this.SetupSerializer(serializer);
- //serializer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- #endregion
- using (MemoryStream ms = new MemoryStream())
- {
- using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
- {
- using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
- {
- #region mysettings
- SetupWriter(writer);
- writer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
- #endregion
- //writer.Formatting = Newtonsoft.Json.Formatting.Indented;
- if (parameters.Length == 1)
- {
- // Single parameter, assuming bare
- serializer.Serialize(sw, parameters[0]);
- }
- else
- {
- writer.WriteStartObject();
- for (int i = 0; i < this.operation.Messages[0].Body.Parts.Count; i++)
- {
- writer.WritePropertyName(this.operation.Messages[0].Body.Parts[i].Name);
- serializer.Serialize(writer, parameters[i]);
- }
- writer.WriteEndObject();
- }
- writer.Flush();
- sw.Flush();
- body = ms.ToArray();
- }
- }
- }
- Message requestMessage = Message.CreateMessage(messageVersion, operation.Messages[0].Action, new RawBodyWriter(body));
- requestMessage.Headers.To = operationUri;
- requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
- HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();
- reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";
- requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp);
- return requestMessage;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement