Ejemplo n.º 1
0
        /// <summary>
        /// Writes Protocol in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        internal void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names)
        {
            writer.WriteStartObject();

            JsonHelper.writeIfNotNullOrEmpty(writer, "protocol", this.Name);
            JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.Namespace);
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            writer.WritePropertyName("types");
            writer.WriteStartArray();

            foreach (Schema type in this.Types)
            {
                type.WriteJson(writer, names, this.Namespace);
            }

            writer.WriteEndArray();

            writer.WritePropertyName("messages");
            writer.WriteStartObject();

            foreach (KeyValuePair <string, Message> message in this.Messages)
            {
                writer.WritePropertyName(message.Key);
                message.Value.writeJson(writer, names, this.Namespace);
            }

            writer.WriteEndObject();
            writer.WriteEndObject();
        }
Ejemplo n.º 2
0
        public static string ToJSON(ContractValue contract, object value)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                var datacontract = ServicesFactory.GetDataContract(contract.Type);

                if (datacontract != null)
                {
                    foreach (var p in datacontract.Properties)
                    {
                        var v = p.Property.GetValue(value, new object[0]);

                        writer.WritePropertyName(p.Name);
                        writer.WriteValue(ValueConverter.ToString(p, v));
                    }
                }
                else
                {
                    writer.WritePropertyName("result");
                    writer.WriteValue(ValueConverter.ToString(contract, value));
                }
                writer.WriteEndObject();
            }
            return(sb.ToString());
        }
Ejemplo n.º 3
0
        public override void BuildString(Newtonsoft.Json.JsonTextWriter writer)
        {
            if (this._namevalues.Count > 0)
            {
                foreach (var kv in this._namevalues)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName(Condition);

                    writer.WriteStartObject();

                    writer.WritePropertyName(kv.Key);

                    writer.WriteStartObject();
                    foreach (var kv2 in (Dictionary <string, object>)kv.Value)
                    {
                        writer.WritePropertyName(kv2.Key);
                        writer.WriteValue(kv2.Value);
                    }
                    writer.WriteEndObject();
                    writer.WriteEndObject();

                    writer.WriteEndObject();
                }
            }
            else
            {
            }
        }
Ejemplo n.º 4
0
        } // WriteAssociativeArray

        private static void WriteComplexArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr, RenderType_t renderType)
        {
            //jsonWriter.WriteStartObject();
            jsonWriter.WriteStartArray();

            for (int i = 0; i <= dr.FieldCount - 1; i++)
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue(dr.GetName(i));

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

                if (renderType.HasFlag(RenderType_t.WithDetail))
                {
                    jsonWriter.WritePropertyName("fieldType");
                    //jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                    jsonWriter.WriteValue(GetTypeName(dr.GetFieldType(i), renderType));
                }

                jsonWriter.WriteEndObject();
            }

            // jsonWriter.WriteEndObject();
            jsonWriter.WriteEndArray();
        } // WriteAssociativeArray
Ejemplo n.º 5
0
        /// <summary>
        /// Writes the messages section of a protocol definition
        /// </summary>
        /// <param name="writer">writer</param>
        /// <param name="names">list of names written</param>
        /// <param name="encspace">enclosing namespace</param>
        internal void writeJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            writer.WriteStartObject();
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            if (null != this.Request)
                this.Request.WriteJsonFields(writer, names, null);

            if (null != this.Response)
            {
                writer.WritePropertyName("response");
                Response.WriteJson(writer, names, encspace);
            }

            if (null != this.Error)
            {
                writer.WritePropertyName("errors");
                this.Error.WriteJson(writer, names, encspace);
            }

            if (null != Oneway)
            {
                writer.WritePropertyName("one-way");
                writer.WriteValue(Oneway);
            }

            writer.WriteEndObject();
        }
        } // End Sub WriteAssociativeArray

        private static void WriteAssociativeArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr, bool dataType)
        {
            // JSON:
            //{
            //     "column_1":{ "index":0,"fieldType":"int"}
            //    ,"column_2":{ "index":1,"fieldType":"int"}
            //}

            jsonWriter.WriteStartObject();

            for (int i = 0; i < dr.FieldCount; ++i)
            {
                jsonWriter.WritePropertyName(dr.GetName(i));
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

#if false
                jsonWriter.WritePropertyName("columnName");
                jsonWriter.WriteValue(dr.GetName(i));
#endif

                if (dataType)
                {
                    jsonWriter.WritePropertyName("fieldType");
                    jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                } // End if (dataType)

                jsonWriter.WriteEndObject();
            } // Next i

            jsonWriter.WriteEndObject();
        } // End Sub WriteAssociativeArray
Ejemplo n.º 7
0
        public override void BuildString(Newtonsoft.Json.JsonTextWriter writer)
        {
            if (_namevalues.Count > 0)
            {
                foreach (var kv in _namevalues)
                {
                    var list = (List <object>)kv.Value;

                    if (list.Count > 1)
                    {
                        //writer.WriteStartObject();
                        //writer.WritePropertyName(this.Condition+"s");
                        //writer.WriteStartObject();
                        //writer.WritePropertyName(kv.Key);
                        //writer.WriteStartArray();
                        //foreach(var it in list)
                        //{
                        //    writer.WriteValue(it);
                        //}
                        //writer.WriteEndArray();

                        foreach (var it in list)
                        {
                            writer.WriteStartObject();
                            writer.WritePropertyName(this.Condition);
                            writer.WriteStartObject();
                            writer.WritePropertyName(kv.Key);
                            writer.WriteValue(it);
                            writer.WriteEndObject();
                            writer.WriteEndObject();
                        }
                    }
                    else
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName(this.Condition);
                        writer.WriteStartObject();
                        writer.WritePropertyName(kv.Key);
                        writer.WriteValue(list[0]);
                        writer.WriteEndObject();
                        writer.WriteEndObject();
                    }
                }
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName(Condition);
                writer.WriteStartObject();
                writer.WriteEndObject();
                writer.WriteEndObject();
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Writes logical schema in JSON format
 /// </summary>
 /// <param name="writer">JSON writer</param>
 /// <param name="names">list of named schemas already written</param>
 /// <param name="encspace">enclosing namespace of the schema</param>
 protected internal override void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("type");
     BaseSchema.WriteJson(writer, names, encspace);
     writer.WritePropertyName("logicalType");
     writer.WriteValue(LogicalTypeName);
     if (null != Props)
     {
         Props.WriteJson(writer);
     }
     writer.WriteEndObject();
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 部分更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="doc"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public BulkOpBuilder Update <T>(ESDocument <T> doc, params Expression <Func <T, object> >[] predicate)
        {
            if (doc != null)
            {
                sb.AppendFormat("{{\"{0}\":{{ \"_index\":\"{1}\",\"_type\":\"{2}\",\"_id\":\"{3}\",\"_retry_on_conflict\":3}}}}\n", OpTypes.update, doc.IndexName, doc.DocumentType, doc.DocumentID);
                if (predicate == null || predicate.Length == 0)
                {
                    sb.AppendFormat("{{\"doc\":{0}}}\n", doc.ToString());
                }
                else
                {
                    sb.Append("{{");

                    string membername = string.Empty;
                    using (Newtonsoft.Json.JsonTextWriter jw = new Newtonsoft.Json.JsonTextWriter(new StringWriter(sb)))
                    {
                        foreach (var selecter in predicate)
                        {
                            jw.WritePropertyName(JsonHelper.GetJsonTag(selecter, out membername));
                            var val = doc.Document.Eval(membername);

                            jw.WriteValue(val);
                        }
                    }

                    sb.Append("}}\n");
                }
            }
            return(this);
        }
Ejemplo n.º 10
0
        private static string GetExpectedString(bool prettyPrint, bool isUtf8, int[] data)
        {
            MemoryStream ms           = new MemoryStream();
            StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true);

            StringBuilder sb           = new StringBuilder();
            StringWriter  stringWriter = new StringWriter(sb);

            TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter;

            var json = new Newtonsoft.Json.JsonTextWriter(writer)
            {
                Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None
            };

            json.WriteStartObject();
            json.WritePropertyName("age");
            json.WriteValue(42);
            json.WritePropertyName("first");
            json.WriteValue("John");
            json.WritePropertyName("last");
            json.WriteValue("Smith");
            json.WritePropertyName("phoneNumbers");
            json.WriteStartArray();
            json.WriteValue("425-000-1212");
            json.WriteValue("425-000-1213");
            json.WriteEnd();
            json.WritePropertyName("address");
            json.WriteStartObject();
            json.WritePropertyName("street");
            json.WriteValue("1 Microsoft Way");
            json.WritePropertyName("city");
            json.WriteValue("Redmond");
            json.WritePropertyName("zip");
            json.WriteValue(98052);
            json.WriteEnd();

            // Add a large array of values
            json.WritePropertyName("ExtraArray");
            json.WriteStartArray();
            for (var i = 0; i < ExtraArraySize; i++)
            {
                json.WriteValue(data[i]);
            }
            json.WriteEnd();

            json.WriteEnd();

            json.Flush();

            return(isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString());
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Writes enum schema in JSON format
 /// </summary>
 /// <param name="writer">JSON writer</param>
 /// <param name="names">list of named schema already written</param>
 /// <param name="encspace">enclosing namespace of the enum schema</param>
 protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer,
                                                  SchemaNames names, string encspace)
 {
     base.WriteJsonFields(writer, names, encspace);
     writer.WritePropertyName("symbols");
     writer.WriteStartArray();
     foreach (string s in this.Symbols)
     {
         writer.WriteValue(s);
     }
     writer.WriteEndArray();
     if (null != Default)
     {
         writer.WritePropertyName("default");
         writer.WriteValue(Default);
     }
 }
Ejemplo n.º 12
0
 public static void Serialize(Newtonsoft.Json.JsonTextWriter Writer, TimingDebugger TimingDebuggerObj)
 {
     Writer.WritePropertyName("TimingGroup");
     Writer.WriteStartArray();
     foreach (var t in TimingDebuggerObj)
     {
         var timing = t.Where(tt => tt.Name == t.Name).First();
         Writer.WriteStartObject();
         Writer.WritePropertyName("Name");
         Writer.WriteValue(t.Name);
         Writer.WritePropertyName("ExecutionTime");
         Writer.WriteValue(timing.ExecutionTime);
         Timing.Serialize(Writer, t);
         Writer.WriteEndObject();
     }
     Writer.WriteEndArray();
 }
Ejemplo n.º 13
0
        private static void WriterNewtonsoftHelloWorld(bool formatted, TextWriter writer)
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
            {
                json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("message");
                json.WriteValue("Hello, World!");
                json.WriteEnd();
            }
        }
Ejemplo n.º 14
0
        public System.ServiceModel.Channels.Message OrleanStats()
        {
            if (Orleans.GrainClient.IsInitialized == false)
                return WebOperationContext.Current.CreateTextResponse("Error: Client not initialised", "text/plain", Encoding.UTF8);

            IManagementGrain systemManagement = GrainClient.GrainFactory.GetGrain<IManagementGrain>(RuntimeInterfaceConstants.SYSTEM_MANAGEMENT_ID);

            if (systemManagement == null)
                return WebOperationContext.Current.CreateTextResponse("Error: System management not found", "text/plain", Encoding.UTF8);

            var stats = systemManagement.GetSimpleGrainStatistics().Result;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);
            writer.Formatting = Newtonsoft.Json.Formatting.Indented;

            writer.WriteStartObject();
            writer.WritePropertyName("stats");
            writer.WriteStartArray();

            foreach (var s in stats)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("activations");
                writer.WriteValue(s.ActivationCount);
                writer.WritePropertyName("address");
                writer.WriteValue(s.SiloAddress.ToString());
                writer.WritePropertyName("type");
                writer.WriteValue(s.GrainType);
                writer.WriteEndObject();

            }

            writer.WriteEndArray();
            writer.WriteEndObject();

            string ret = sb.ToString();
            return WebOperationContext.Current.CreateTextResponse(ret, "text/plain", Encoding.UTF8);
        }
        } // End Sub WriteAssociativeArray

        private static void WriteArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr)
        {
            jsonWriter.WriteStartArray();

            for (int i = 0; i < dr.FieldCount; ++i)
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

                jsonWriter.WritePropertyName("columnName");
                jsonWriter.WriteValue(dr.GetName(i));

                jsonWriter.WritePropertyName("fieldType");
                jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));

                jsonWriter.WriteEndObject();
            } // Next i

            jsonWriter.WriteEndArray();
        } // End Sub WriteArray
Ejemplo n.º 16
0
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = endpoint.NewtonsoftSettings().JsonSerializer;

            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        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();
                    }
                }
            }
            if (traceSource.Switch.ShouldTrace(TraceEventType.Information))
            {
                traceSource.TraceEvent(TraceEventType.Information, 1004, System.Text.Encoding.UTF8.GetString(body));
            }

            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);
        }
Ejemplo n.º 17
0
        //[Benchmark]
        public void NewtonsoftEscapingRequired()
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter()))
            {
                json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                for (int i = 0; i < 100; i++)
                {
                    json.WritePropertyName("fir\nst");
                    json.WriteValue("Joh\nn");
                }
                json.WriteEndObject();
            }
        }
Ejemplo n.º 18
0
        //[Benchmark]
        public void NewtonsoftNullUnescaped()
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter()))
            {
                json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                for (int i = 0; i < 100; i++)
                {
                    json.WritePropertyName("first", escape: false);
                    json.WriteValue((object)null);
                }
                json.WriteEndObject();
            }
        }
Ejemplo n.º 19
0
        //[Benchmark]
        public void NewtonsoftDateTimeUnescapedOverhead()
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter()))
            {
                json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                for (int i = 0; i < 100; i++)
                {
                    json.WritePropertyName("first", escape: true);
                    json.WriteValue(MyDate);
                }
                json.WriteEndObject();
            }
        }
Ejemplo n.º 20
0
        //[Benchmark]
        public void NewtonsoftEscapeUnnecessarily()
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter()))
            {
                json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                for (int i = 0; i < 100; i++)
                {
                    json.WritePropertyName("first", escape: true);
                    json.WriteValue("John");
                }
                json.WriteEndObject();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Writes the records schema in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        /// <param name="encspace">enclosing namespace of the record schema</param>
        protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            base.WriteJsonFields(writer, names, encspace);

            // we allow reading for empty fields, so writing of records with empty fields are allowed as well
            if (request)
            {
                writer.WritePropertyName("request");
            }
            else
            {
                writer.WritePropertyName("fields");
            }
            writer.WriteStartArray();

            if (null != this.Fields && this.Fields.Count > 0)
            {
                foreach (Field field in this)
                {
                    field.writeJson(writer, names, this.Namespace); // use the namespace of the record for the fields
                }
            }
            writer.WriteEndArray();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Writes named schema in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        /// <param name="encspace">enclosing namespace of the named schema</param>
        protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            this.SchemaName.WriteJson(writer, names, encspace);

            if (null != aliases)
            {
                writer.WritePropertyName("aliases");
                writer.WriteStartArray();
                foreach (SchemaName name in aliases)
                {
                    string fullname = (null != name.Space) ? name.Space + "." + name.Name : name.Name;
                    writer.WriteValue(fullname);
                }
                writer.WriteEndArray();
            }
        }
Ejemplo n.º 23
0
        private static void WriterNewtonsoftBasic(bool formatted, StreamWriter writer)
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
            {
                json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("age");
                json.WriteValue(42);
                json.WritePropertyName("first");
                json.WriteValue("John");
                json.WritePropertyName("last");
                json.WriteValue("Smith");
                json.WritePropertyName("phoneNumbers");
                json.WriteStartArray();
                json.WriteValue("425-000-1212");
                json.WriteValue("425-000-1213");
                json.WriteEnd();
                json.WritePropertyName("address");
                json.WriteStartObject();
                json.WritePropertyName("street");
                json.WriteValue("1 Microsoft Way");
                json.WritePropertyName("city");
                json.WriteValue("Redmond");
                json.WritePropertyName("zip");
                json.WriteValue(98052);
                json.WriteEnd();

                // Add a large array of values
                json.WritePropertyName("ExtraArray");
                json.WriteStartArray();
                for (var i = 0; i < ExtraArraySize; i++)
                {
                    json.WriteValue(i);
                }
                json.WriteEnd();

                json.WriteEnd();
            }
        }
Ejemplo n.º 24
0
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            byte[] body;
            var    serializer = NewtonsoftJsonSettings.GetSerializer();

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        writer.Formatting = NewtonsoftJsonSettings.GetFormatting();

                        if (parameters.Length == 1)
                        {
                            // Single parameter, assuming bare
                            serializer.Serialize(sw, parameters[0]);
                        }
                        else
                        {
                            writer.WriteStartObject();
                            foreach (MessagePartDescription t in this.m_operation.Messages[0].Body.Parts)
                            {
                                writer.WritePropertyName(t.Name);
                                serializer.Serialize(writer, parameters[0]);
                            }

                            writer.WriteEndObject();
                        }

                        writer.Flush();
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            Message requestMessage = Message.CreateMessage(messageVersion, m_operation.Messages[0].Action, new RawBodyWriter(body));

            requestMessage.Headers.To = m_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);
        }
Ejemplo n.º 25
0
        private static void WriterNewtonsoftBasic(bool formatted, TextWriter writer, ReadOnlySpan <int> data)
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
            {
                json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("age");
                json.WriteValue(42);
                json.WritePropertyName("first");
                json.WriteValue("John");
                json.WritePropertyName("last");
                json.WriteValue("Smith");
                json.WritePropertyName("phoneNumbers");
                json.WriteStartArray();
                json.WriteValue("425-000-1212");
                json.WriteValue("425-000-1213");
                json.WriteEnd();
                json.WritePropertyName("address");
                json.WriteStartObject();
                json.WritePropertyName("street");
                json.WriteValue("1 Microsoft Way");
                json.WritePropertyName("city");
                json.WriteValue("Redmond");
                json.WritePropertyName("zip");
                json.WriteValue(98052);
                json.WriteEnd();

                json.WritePropertyName("ExtraArray");
                json.WriteStartArray();
                for (var i = 0; i < data.Length; i++)
                {
                    json.WriteValue(data[i]);
                }
                json.WriteEnd();

                json.WriteEnd();
            }
        }
Ejemplo n.º 26
0
        //[Benchmark]
        public void WriteArrayNewtonsoft()
        {
            using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter()))
            {
                json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;

                json.WriteStartObject();
                json.WritePropertyName("message");
                json.WriteStartArray();
                for (var i = 0; i < _longs.Length; i++)
                {
                    json.WriteValue(_longs[i]);
                }
                json.WriteEnd();
                json.WriteEnd();
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 返回结果的存储过程
        /// </summary>
        /// <param name="strSql">任何SQL语句</param>
        /// <param name="parameters">参数值</param>
        /// <returns></returns>
        public override string ExecuteJson(string strSql, params DbParameter[] parameters)
        {
            try
            {
                DbCommand cmd = BuilderQueryCommand(strSql, parameters);

                System.IO.StringWriter     sw     = null;
                Newtonsoft.Json.JsonWriter writer = null;

                sw     = new System.IO.StringWriter();
                writer = new Newtonsoft.Json.JsonTextWriter(sw);

                writer.WriteStartArray();
                using (DbDataReader dr = cmd.ExecuteReader())
                {
                    do
                    {
                        while (dr.Read())
                        {
                            writer.WriteStartObject();
                            for (int i = 0; i < dr.FieldCount; i++)
                            {
                                writer.WritePropertyName(dr.GetName(i));
                                writer.WriteValue(Convert.ToString(dr[i]));
                            }
                            writer.WriteEndObject();
                        }
                    }while (dr.NextResult());
                }

                writer.WriteEndArray();
                writer.Flush();
                return(sw.GetStringBuilder().ToString());
            }
            catch (DbException ex)
            {
                throw ex;
            }
            catch
            {
                throw;
            }
        }
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        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[0]);
                            }

                            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;
        }
Ejemplo n.º 29
0
        public string ToJson()
        {
            System.IO.StringWriter         sw     = new System.IO.StringWriter();
            Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            // {
            writer.WriteStartObject();

            // "query" : ""
            writer.WritePropertyName("query");
            writer.WriteValue(query);

            // "name" : ""
            writer.WritePropertyName("name");
            writer.WriteValue(name);

            // "latitude" : ""
            writer.WritePropertyName("latitude");
            writer.WriteValue(latitude);

            // "longitude" : ""
            writer.WritePropertyName("longitude");
            writer.WriteValue(longitude);

            // "tz_long" : ""
            writer.WritePropertyName("tz_long");
            writer.WriteValue(tz_long);

            // "locationType" : ""
            writer.WritePropertyName("locationType");
            writer.WriteValue((int)locationType);

            // "source" : ""
            writer.WritePropertyName("source");
            writer.WriteValue(source);

            // }
            writer.WriteEndObject();

            return(sw.ToString());
        }
Ejemplo n.º 30
0
        private static string GetHelloWorldExpectedString(bool prettyPrint, bool isUtf8)
        {
            MemoryStream ms           = new MemoryStream();
            StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true);

            StringBuilder sb           = new StringBuilder();
            StringWriter  stringWriter = new StringWriter(sb);

            TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter;

            var json = new Newtonsoft.Json.JsonTextWriter(writer)
            {
                Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None
            };

            json.WriteStartObject();
            json.WritePropertyName("message");
            json.WriteValue("Hello, World!");
            json.WriteEnd();

            json.Flush();

            return(isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString());
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Writes the fixed schema class in JSON format
 /// </summary>
 /// <param name="writer">JSON writer</param>
 /// <param name="names">list of named schema already written</param>
 /// <param name="encspace">enclosing namespace for the fixed schema</param>
 protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
 {
     base.WriteJsonFields(writer, names, encspace);
     writer.WritePropertyName("size");
     writer.WriteValue(this.Size);
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Convert the sql results to UtilityResponce
        /// </summary>
        /// <param name="sqlReadResults">the source</param>
        /// <param name="result">the target.</param>
        public static void ConvertReadResultsToResponce(List <SqlReadResult> sqlReadResults, UtilityResponce result)
        {
            int kind          = 0;
            var stringBuilder = new System.Text.StringBuilder();

            if (sqlReadResults.Count > 0)
            {
                var sqlReadResult = sqlReadResults[0];
                if ((sqlReadResult.FieldCount == 1) &&
                    (sqlReadResult.Rows.Count > 0) &&
                    ((string.Equals(sqlReadResult.FieldNames[0], "kind", StringComparison.OrdinalIgnoreCase)) ||
                     (string.Equals(sqlReadResult.FieldNames[0], "mimetype", StringComparison.OrdinalIgnoreCase))))
                {
                    var cell00 = sqlReadResult.Rows[0][0] as string;
                    if ((string.Equals(cell00, "text", StringComparison.OrdinalIgnoreCase)) ||
                        (string.Equals(cell00, Consts.MimeTypeText, StringComparison.OrdinalIgnoreCase)) ||
                        (string.Equals(cell00, Consts.MimeTypeJavascript, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeText;
                        kind        = 1;
                        sqlReadResults.RemoveAt(0);
                    }
                    else if ((string.Equals(cell00, Consts.MimeTypeHTML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(cell00, "html", StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeHTML;
                        kind        = 2;
                        sqlReadResults.RemoveAt(0);
                    }
                    else if ((string.Equals(cell00, "json", StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(cell00, Consts.MimeTypeJSON, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeJSON;
                        kind        = 3;
                        sqlReadResults.RemoveAt(0);
                    }
                    else if ((string.Equals(cell00, Consts.MimeTypeXML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(cell00, Consts.MimeTypeTextXML, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = cell00;
                        kind        = 4;
                        sqlReadResults.RemoveAt(0);
                    }
                    else
                    {
                        result.Kind = cell00;
                        kind        = 1;
                    }
                }
                else if (sqlReadResult.FieldCount >= 1)
                {
                    var fieldName0 = sqlReadResult.FieldNames[0] as string;
                    if ((string.Equals(fieldName0, "text", StringComparison.OrdinalIgnoreCase)) ||
                        (string.Equals(fieldName0, Consts.MimeTypeText, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeText;
                        kind        = 1;
                    }
                    else if ((string.Equals(fieldName0, Consts.MimeTypeHTML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(fieldName0, "html", StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeHTML;
                        kind        = 2;
                    }
                    else if ((string.Equals(fieldName0, "json", StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(fieldName0, Consts.MimeTypeJSON, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = Consts.MimeTypeJSON;
                        kind        = 3;
                    }
                    else if ((string.Equals(fieldName0, Consts.MimeTypeXML, StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(fieldName0, Consts.MimeTypeTextXML, StringComparison.OrdinalIgnoreCase)))
                    {
                        result.Kind = fieldName0;
                        kind        = 4;
                    }
                    else
                    {
                        result.Kind = "application/json";
                        kind        = 3;
                    }
                }
            }
            if (kind == 1)
            {
                foreach (var sqlReadResult in sqlReadResults)
                {
                    foreach (var row in sqlReadResult.Rows)
                    {
                        for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                        {
                            var value = row[fieldIndex];
                            if (value == null)
                            {
                                continue;
                            }
                            stringBuilder.Append(value);
                        }
                    }
                }
            }
            else if (kind == 2)
            {
                foreach (var sqlReadResult in sqlReadResults)
                {
                    foreach (var row in sqlReadResult.Rows)
                    {
                        for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                        {
                            var value = row[fieldIndex];
                            if (value == null)
                            {
                                continue;
                            }
                            stringBuilder.Append(value);
                        }
                    }
                }
            }
            else if (kind == 3)
            {
                using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder)) {
                    using (Newtonsoft.Json.JsonTextWriter jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)) {
                        jsonTextWriter.WriteStartArray();
                        foreach (var sqlReadResult in sqlReadResults)
                        {
                            jsonTextWriter.WriteStartArray();
                            foreach (var row in sqlReadResult.Rows)
                            {
                                jsonTextWriter.WriteStartObject();
                                for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                                {
                                    var fieldName = sqlReadResult.FieldNames[fieldIndex];
                                    var value     = row[fieldIndex];
                                    jsonTextWriter.WritePropertyName(fieldName);
                                    jsonTextWriter.WriteValue(value);
                                }
                                jsonTextWriter.WriteEndObject();
                            }
                            jsonTextWriter.WriteEndArray();
                            if ((sqlReadResult.MeassureMessage.Count > 0) && (sqlReadResult.MeassureError.Count > 0))
                            {
                                if (sqlReadResult.MeassureMessage.Count > 0)
                                {
                                    jsonTextWriter.WriteStartArray();
                                    foreach (var meassureMessage in sqlReadResult.MeassureMessage)
                                    {
                                        jsonTextWriter.WriteStartObject();
                                        jsonTextWriter.WritePropertyName("MeassureMessage");
                                        jsonTextWriter.WriteValue(meassureMessage);
                                        jsonTextWriter.WriteEndObject();
                                    }
                                    jsonTextWriter.WriteEndArray();
                                }
                                if (sqlReadResult.MeassureError.Count > 0)
                                {
                                    jsonTextWriter.WriteStartArray();
                                    foreach (var meassureError in sqlReadResult.MeassureError)
                                    {
                                        jsonTextWriter.WriteStartObject();
                                        jsonTextWriter.WritePropertyName("MeassureError");
                                        jsonTextWriter.WriteValue(meassureError);
                                        jsonTextWriter.WriteEndObject();
                                    }
                                    jsonTextWriter.WriteEndArray();
                                }
                            }
                        }
                        jsonTextWriter.WriteEndArray();
                    }
                }
            }
            else if (kind == 4)
            {
                using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder)) {
                    using (var xmlWriter = new System.Xml.XmlTextWriter(stringWriter)) {
                        xmlWriter.Formatting = System.Xml.Formatting.None;
                        xmlWriter.WriteStartDocument();
                        xmlWriter.WriteStartElement("data");
                        foreach (var sqlReadResult in sqlReadResults)
                        {
                            xmlWriter.WriteStartElement("result");
                            foreach (var row in sqlReadResult.Rows)
                            {
                                xmlWriter.WriteStartElement("row");
                                for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                                {
                                    var fieldName = sqlReadResult.FieldNames[fieldIndex];
                                    var value     = row[fieldIndex];
                                    xmlWriter.WriteStartElement(fieldName);
                                    if (value == null)
                                    {
                                        // ignore
                                    }
                                    else if (value == DBNull.Value)
                                    {
                                        // ignore
                                    }
                                    else if (value is string)
                                    {
                                        xmlWriter.WriteValue((string)value);
                                    }
                                    else if (value is bool)
                                    {
                                        xmlWriter.WriteValue((bool)value);
                                    }
                                    else if (value is DateTime)
                                    {
                                        xmlWriter.WriteValue((DateTime)value);
                                    }
                                    else if (value is decimal)
                                    {
                                        xmlWriter.WriteValue((decimal)value);
                                    }
                                    else if (value is float)
                                    {
                                        xmlWriter.WriteValue((float)value);
                                    }
                                    else if (value is double)
                                    {
                                        xmlWriter.WriteValue((double)value);
                                    }
                                    else if (value is int)
                                    {
                                        xmlWriter.WriteValue((int)value);
                                    }
                                    else if (value is long)
                                    {
                                        xmlWriter.WriteValue((long)value);
                                    }
                                    else
                                    {
                                        xmlWriter.WriteElementString(fieldName, value.ToString());
                                    }
                                    xmlWriter.WriteEndElement(/*fieldName*/);
                                }
                                xmlWriter.WriteEndElement(/*row*/);
                            }
                            xmlWriter.WriteEndElement(/*result*/);
                        }
                        xmlWriter.WriteEndElement(/*data*/);
                        xmlWriter.WriteEndDocument();
                    }
                    using (Newtonsoft.Json.JsonTextWriter jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)) {
                        jsonTextWriter.WriteStartArray();
                        foreach (var sqlReadResult in sqlReadResults)
                        {
                            jsonTextWriter.WriteStartArray();
                            foreach (var row in sqlReadResult.Rows)
                            {
                                jsonTextWriter.WriteStartObject();
                                for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++)
                                {
                                    var fieldName = sqlReadResult.FieldNames[fieldIndex];
                                    var value     = row[fieldIndex];
                                    jsonTextWriter.WritePropertyName(fieldName);
                                    jsonTextWriter.WriteValue(value);
                                }
                                jsonTextWriter.WriteEndObject();
                            }
                            jsonTextWriter.WriteEndArray();
                        }
                        jsonTextWriter.WriteEndArray();
                    }
                }
            }
            result.Value = stringBuilder.ToString();
        }