WriteStartArray() public method

Writes the beginning of a JSON array.
public WriteStartArray ( ) : void
return void
Ejemplo n.º 1
1
        private static string toJSON(SqlDataReader rdr)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            JsonWriter jsonWriter = new JsonTextWriter(sw);
            jsonWriter.WriteStartArray();
            while (rdr.Read())
            {
                int fieldcount = rdr.FieldCount; // count how many columns are in the row
                object[] values = new object[fieldcount]; // storage for column values
                rdr.GetValues(values); // extract the values in each column
                jsonWriter.WriteStartObject();
                for (int index = 0; index < fieldcount; index++)
                {

                    string colName = rdr.GetName(index);
                    object value = values[index];
                    jsonWriter.WritePropertyName(colName);

                    if (value == DBNull.Value)
                        value = "";
                    else if (colName.Contains("date") && !colName.Contains("by"))
                        value = String.Format("{0:MM/dd/yyyy HH:mm tt}", value);

                    jsonWriter.WriteValue(value);
                }
                jsonWriter.WriteEndObject();
            }
            jsonWriter.WriteEndArray();

            return sb.ToString();
        }
Ejemplo n.º 2
0
 //-----------------------------------------------------------------------------------------------------
 public void Join(UserManager.UserClass _user)
 {
     if (_user.Is_Bot != 1)
     {
         _user.sep.Send("[" + (int)ServerOpcode.enter_room + "]");
         StringBuilder sb = new StringBuilder();
         StringWriter sw = new StringWriter(sb);
         using (JsonWriter writer = new JsonTextWriter(sw))
         {
             writer.Formatting = Formatting.None;
             writer.WriteStartArray();
             writer.WriteValue((int)ServerOpcode.room_state);
             writer.WriteStartArray();
             writer.WriteValue(_channel_id);
             writer.WriteValue(_channel_name);
             writer.WriteValue(_channel_password);
             writer.WriteValue(_channel_maxplayers);
             writer.WriteValue(_channel_gamemode);
             writer.WriteValue(_channel_map);
             writer.WriteValue(_channel_avatar_on);
             writer.WriteValue(_channel_max_wind);
             writer.WriteValue(_channel_gp_rate);
             writer.WriteValue(_unk1);
             writer.WriteValue(_unk2);
             writer.WriteValue(_unk3);
             writer.WriteValue(_unk4);
             writer.WriteEndArray();
             writer.WriteEndArray();
         }
         _user.sep.Send(sb.ToString());
     }
     _user.channel = _channel_id;
     RoomPlayer(_user);
 }
        public static void WriteAsJson([NotNull] this LayoutBuilder layoutBuilder, [NotNull] TextWriter writer)
        {
            var output = new JsonTextWriter(writer)
            {
                Formatting = Formatting.Indented
            };

            output.WriteStartObject("Layout");
            output.WriteStartArray("Devices");

            foreach (var deviceBuilder in layoutBuilder.Devices)
            {
                output.WriteStartObject();
                output.WritePropertyStringIf("Name", deviceBuilder.DeviceName);
                output.WritePropertyStringIf("Layout", deviceBuilder.LayoutItemPath);

                output.WriteStartArray("Renderings");

                foreach (var renderingBuilder in deviceBuilder.Renderings.Where(r => r.ParentRendering == null))
                {
                    WriteAsJson(output, deviceBuilder, renderingBuilder);
                }

                output.WriteEndArray();
                output.WriteEndObject();
            }

            output.WriteEndArray();
            output.WriteEndObject();
        }
Ejemplo n.º 4
0
        public static void WriteTo(this Item item, JsonTextWriter writer)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(item.Format));
            writer.WriteValue(Enum.GetName(typeof(SecsFormat), item.Format));
            if (item.Format == SecsFormat.List)
            {
                writer.WritePropertyName(nameof(item.Items));
                writer.WriteStartArray();
                foreach (var subitem in item.Items)
                    subitem.WriteTo(writer);
                writer.WriteEndArray();
            }
            else
            {
                writer.WritePropertyName(nameof(item.Values));

                if (item.Format == SecsFormat.ASCII || item.Format == SecsFormat.JIS8)
                {
                    writer.WriteValue(item.GetValue<string>());
                }
                else
                {
                    writer.WriteStartArray();
                    foreach (var value in item.Values)
                        writer.WriteValue(value);
                    writer.WriteEndArray();
                }
            }
            writer.WriteEndObject();
        }
Ejemplo n.º 5
0
        public override bool Execute()
        {
            if (Items.Length == 0)
                throw new ArgumentException("The provided items contained zero entries.");

            if (!Directory.Exists(Path.GetDirectoryName(JsonFileName)))
                Directory.CreateDirectory(Path.GetDirectoryName(JsonFileName));

            JsonSerializer jsonSerializer = new JsonSerializer();
            using (StreamWriter streamWriter = new StreamWriter(JsonFileName))
            {
                using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                {
                    jsonWriter.Formatting = Formatting.Indented;

                    if (Items.Length > 1)
                        jsonWriter.WriteStartArray();

                    foreach (ITaskItem item in Items)
                    {
                        var customMd = item.CloneCustomMetadata();
                        jsonWriter.WriteStartObject();
                        foreach (var key in customMd.Keys)
                        {
                            var mdString = key.ToString();
                            var mdValue = customMd[key].ToString();

                            jsonWriter.WritePropertyName(mdString);

                            // if the value is surrounded in square brackets it's meant to be an array.
                            // split the value into its respective chunks and write it into a JSON array.
                            if (mdValue.Length > 0 && mdValue[0] == '[' && mdValue[mdValue.Length - 1] == ']')
                            {
                                mdValue = mdValue.Substring(1, mdValue.Length - 2);
                                jsonWriter.WriteStartArray();

                                var parts = mdValue.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var part in parts)
                                    jsonWriter.WriteValue(part);

                                jsonWriter.WriteEndArray();
                            }
                            else
                            {
                                jsonWriter.WriteValue(mdValue);
                            }
                        }

                        jsonWriter.WriteEndObject();
                    }

                    if (Items.Length > 1)
                        jsonWriter.WriteEndArray();

                    Log.LogMessage(MessageImportance.High, "Writing {0}.", JsonFileName);
                }
            }

            return true;
        }
Ejemplo n.º 6
0
    public void ValueFormatting()
    {
      StringBuilder sb = new StringBuilder();
      StringWriter sw = new StringWriter(sb);

      using (JsonWriter jsonWriter = new JsonTextWriter(sw))
      {
        jsonWriter.WriteStartArray();
        jsonWriter.WriteValue('@');
        jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
        jsonWriter.WriteValue(true);
        jsonWriter.WriteValue(10);
        jsonWriter.WriteValue(10.99);
        jsonWriter.WriteValue(0.99);
        jsonWriter.WriteValue(0.000000000000000001d);
        jsonWriter.WriteValue(0.000000000000000001m);
        jsonWriter.WriteValue((string)null);
        jsonWriter.WriteValue((object)null);
        jsonWriter.WriteValue("This is a string.");
        jsonWriter.WriteNull();
        jsonWriter.WriteUndefined();
        jsonWriter.WriteEndArray();
      }

      string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]";
      string result = sb.ToString();

      Console.WriteLine("ValueFormatting");
      Console.WriteLine(result);

      Assert.AreEqual(expected, result);
    }
Ejemplo n.º 7
0
        /// <summary>
        /// 数据集(DataSet)转DataJSON  一般用于显示查询结果。
        /// </summary>
        public static String dataTableToDataJson(DataTable dt,int pCount)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.Indented;
                jsonWriter.WriteStartArray();

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    jsonWriter.WriteStartObject();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        jsonWriter.WritePropertyName(dc.ColumnName);
                        jsonWriter.WriteValue(dt.Rows[i][dc.ColumnName]);
                    }
                    jsonWriter.WriteEndObject();
                }
                jsonWriter.WriteEndArray();

            }
            string hand = "{\"totalProperty\": " + pCount.ToString() + " , \"root\": ";
            return Convert.ToString(hand + sb + "}");
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Convert parameter list to json object
        /// </summary>
        public static string parameterFieldMapJson(parameters parms, string ProjectID, string QueryID)
        {
            StringWriter sw = new StringWriter();
            JsonTextWriter json = new JsonTextWriter(sw);

            json.WriteStartObject();
            json.WritePropertyName("results");
            json.WriteStartArray();
            json.WriteStartObject();
            // ProjectID and QueryID
            json.WritePropertyName("ProjectID");
            json.WriteValue(ProjectID);
            json.WritePropertyName("QueryID");
            json.WriteValue(QueryID);

            json.WritePropertyName("parameters");
            json.WriteRawValue(JsonConvert.SerializeObject(parms));

            json.WriteEndObject();
            json.WriteEndArray();
            json.WriteEndObject();

            json.Flush();
            sw.Flush();

            return sw.ToString();
        }
Ejemplo n.º 9
0
 public void ProcessRequest(HttpContext context)
 {
     string reVal = string.Empty;
     context.Response.ContentType = "text/plain";
     IEnumerable<ADM_USER> list = from m in etMgr.ADM_USER.OfType<ADM_USER>()
                                  select m;
     StringBuilder sb = new StringBuilder();
     StringWriter sw = new StringWriter(sb);
     using (JsonWriter jsonWriter = new JsonTextWriter(sw))
     {
         jsonWriter.Formatting = Formatting.Indented;
         jsonWriter.WriteStartArray();
         foreach (ADM_USER m in list)
         {
             jsonWriter.WriteStartObject();
             jsonWriter.WritePropertyName("name");
             jsonWriter.WriteValue(string.IsNullOrEmpty(m.REAL_NAME) ? m.USERNAME : m.REAL_NAME);
             jsonWriter.WritePropertyName("id");
             jsonWriter.WriteValue(m.USER_ID);
             jsonWriter.WriteEndObject();
         }
         jsonWriter.WriteEnd();
     }
     reVal = sb.ToString();
     context.Response.Write(reVal);
 }
Ejemplo n.º 10
0
        public void Invoke(Session _Session, IncomingPacket _Packet)
        {
            string _ctmp = _Packet.GetString();

            string msj_f = HttpUtility.HtmlEncode(_ctmp.Replace("\\\"", "\""));

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;
                writer.WriteStartArray();
                writer.WriteValue((int)ServerOpcode.chat);
                writer.WriteValue(msj_f);
                writer.WriteValue(_Session.User.Name);

                if (_Session.User.rank >= 24)
                    writer.WriteValue(ChatType.CHAT_TYPE_GM); //type
                else
                    writer.WriteValue(0); //type

                if (_Session.User.guild > 0)
                    writer.WriteValue(_Session.User.guild_name);

                writer.WriteEndArray();
            }

            _Session.Broadcast(sb.ToString());
        }
Ejemplo n.º 11
0
        private string GetICJson(List<BusinessPartner> list)
        {
            StringWriter sw = new StringWriter();
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;

                writer.WriteStartArray();

                foreach (var bp in list)
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("id");
                    writer.WriteValue(bp.Id);

                    writer.WritePropertyName("name");
                    writer.WriteValue(bp.ShortName);

                    writer.WriteEndObject();
                }

                writer.WriteEndArray();

                writer.Flush();
                sw.Close();
            }
            return sw.GetStringBuilder().ToString();
        }
Ejemplo n.º 12
0
			public override void Execute(object parameter)
			{
				var saveFile = new SaveFileDialog
				{
					DefaultExt = ".raven.dump",
					Filter = "Raven Dumps|*.raven.dump"
				};
				var dialogResult = saveFile.ShowDialog() ?? false;

				if (!dialogResult)
					return;

				stream = saveFile.OpenFile();
				gZipStream = new GZipStream(stream, CompressionMode.Compress);
				streamWriter = new StreamWriter(gZipStream);
				jsonWriter = new JsonTextWriter(streamWriter)
				{
					Formatting = Formatting.Indented
				};

				output(string.Format("Exporting to {0}", saveFile.SafeFileName));

				output("Begin reading indexes");

				jsonWriter.WriteStartObject();
				jsonWriter.WritePropertyName("Indexes");
				jsonWriter.WriteStartArray();

				ReadIndexes(0).Catch(exception => Infrastructure.Execute.OnTheUI(() => Finish(exception)));
			}
Ejemplo n.º 13
0
        public static string Msj(string _msjx, UserManager.UserClass _user)
        {
            string msj_f = HttpUtility.HtmlEncode(_msjx.Replace("\\\"", "\""));
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;
                writer.WriteStartArray();
                writer.WriteValue((int)ServerOpcode.chat);
                writer.WriteValue(_msjx);
                writer.WriteValue(_user.Name);

                if(_user.rank >= 24)
                    writer.WriteValue(ChatType.CHAT_TYPE_GM); //type
                else
                    writer.WriteValue(0); //type

                if (_user.guild > 0)
                    writer.WriteValue(_user.guild_name);

                writer.WriteEndArray();
            }

            return sb.ToString();
        }
Ejemplo n.º 14
0
        public override string Serialize(Node node, Type typeAttr)
        {
            XpcaProxy proxy = new XpcaProxy(node);
            StringWriter sw = new StringWriter();

            using(JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Newtonsoft.Json.Formatting.None;
                jsonWriter.WriteStartObject();

                foreach (KeyValuePair<string, PropertyInfo> property in proxy.GetPropertiesFor(typeAttr)) {
                    object value = proxy[property.Key];

                    if (value != null) {
                        jsonWriter.WritePropertyName(property.Key);
                        if(value is IEnumerable<object>) {
                            jsonWriter.WriteStartArray();

                            foreach (object obj in (value as IEnumerable<object>)) {
                                JsonWriteValue(jsonWriter, obj);
                            }

                            jsonWriter.WriteEndArray();
                        }
                        else {
                            JsonWriteValue(jsonWriter, value);
                        }
                    }
                }
                jsonWriter.WriteEndObject();
            }

            return sw.ToString();
        }
Ejemplo n.º 15
0
        public String ToJSONRepresentation()
        {
            StringBuilder sb = new StringBuilder();
            JsonWriter jw = new JsonTextWriter(new StringWriter(sb));

            jw.Formatting = Formatting.Indented;
            jw.WriteStartObject();
            jw.WritePropertyName(this._description);
            jw.WriteStartArray();

            foreach(MailStructure mail in this._mailStructures)
            {
                jw.WriteStartObject();
                jw.WritePropertyName("Id");
                jw.WriteValue(mail.Id);
                jw.WritePropertyName("Uuid");
                jw.WriteValue(mail.Uuid);
                jw.WritePropertyName("MailDate");
                jw.WriteValue(mail.MailDate);
                jw.WritePropertyName("From");
                jw.WriteValue(mail.From);
                jw.WritePropertyName("Subject");
                jw.WriteValue(mail.Subject);
                jw.WritePropertyName("Body");
                jw.WriteValue(mail.Body);
                jw.WritePropertyName("AttachmentExist");
                jw.WriteValue((mail.AttachmentExist ? "1" : "0"));
                jw.WritePropertyName("AttachmentFiles");
                jw.WriteValue(mail.AttachmentFiles);
                jw.WriteEndObject();
            }
            jw.WriteEndArray();
            jw.WriteEndObject();
            return sb.ToString();
        }
Ejemplo n.º 16
0
            public static void getFieldJsonStringArray(JsonTextWriter json, List<field> Fields)
            {
                json.WriteStartArray();

                foreach (field field in Fields)
                {

                    json.WriteStartObject();

                    json.WritePropertyName("field");
                    json.WriteValue(field.name.Trim());

                    json.WritePropertyName(TrimValue(field.name));
                    json.WriteValue(TrimValue(field.display));

                    json.WritePropertyName("type");
                    json.WriteValue(field.type.ToString());

                    json.WritePropertyName("display");
                    json.WriteValue(TrimValue(field.display));

                    json.WritePropertyName("ForView");
                    json.WriteValue(field.ForView);

                    json.WritePropertyName("ForUpdate");
                    json.WriteValue(field.ForUpdate);

                    json.WriteEndObject();
                }

                json.WriteEndArray();
            }
Ejemplo n.º 17
0
 void do确定_Click(object sender, EventArgs e)
 {
     var __sw = new StringWriter();
     JsonWriter __writer = new JsonTextWriter(__sw);
     __writer.WriteStartArray();
     foreach (DataGridViewRow __行 in this.out值.Rows)
     {
         if (!__行.IsNewRow)
         {
             var __value = __行.Cells[0].Value == null ? "" : __行.Cells[0].Value.ToString();
             if (_元数据 != null)
             {
                 switch (_元数据.类型)
                 {
                     case "string":
                     case "字符串":
                         __writer.WriteValue(__value);
                         break;
                     default:
                         __writer.WriteRawValue(__value);
                         break;
                 }
             }
             else
             {
                 __writer.WriteRawValue(__value);
             }
         }
     }
     __writer.WriteEndArray();
     __writer.Flush();
     _值 = __sw.GetStringBuilder().ToString();
     this.DialogResult = DialogResult.OK;
 }
Ejemplo n.º 18
0
 static void Main(string[] args)
 {
     StringBuilder sb = new StringBuilder();
     StringWriter sw = new StringWriter(sb);
     using (JsonWriter writer = new JsonTextWriter(sw))
     {
         writer.Formatting = Newtonsoft.Json.Formatting.Indented;
         writer.WriteStartObject();
         writer.WritePropertyName("CPU");
         writer.WriteValue("Intel");
         writer.WritePropertyName("PSU");
         writer.WriteValue("500W");
         writer.WritePropertyName("Drives");
         writer.WriteStartArray();
         writer.WriteValue("DVD read/writer");
         writer.WriteComment("(broken)");
         writer.WriteValue("500 gigabyte hard drive");
         writer.WriteValue("200 gigabype hard drive");
         writer.WriteEnd();
         writer.WriteEndObject();
     }
     File.WriteAllText(Environment.CurrentDirectory + "/rhcdata.json", sw.ToString());
     Console.WriteLine(sw.ToString());
     Console.ReadLine();
 }
        //https://webServiceURL/version/devices/deviceLibraryIdentifier/registrations/passTypeIdentifier?passesUpdatedSince=tag
        public HttpResponseMessage Get(string version, string deviceLibraryIdentifier, string passTypeIdentifier, HttpRequestMessage request)
        {
            //List<string> updatedSerialNumbers = new List<string>();
            //updatedSerialNumbers.Add("121212111");

            //Dictionary<string, string> outputDictionary = new Dictionary<string, string>();
            //outputDictionary.Add("lastUpdated", "21/07/2012");
            //outputDictionary.Add("serialNumbers", JsonConvert.SerializeObject(updatedSerialNumbers));

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            //string json = JsonConvert.SerializeObject(outputDictionary);


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

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                writer.WritePropertyName("lastUpdated");
                writer.WriteValue("21/07/2012");
                writer.WritePropertyName("serialNumbers");
                writer.WriteStartArray();
                writer.WriteValue("121212111");
                writer.WriteEndArray();
                writer.WriteEndObject();
            }

            response.Content = new StringContent(sb.ToString(), Encoding.UTF8, "application/json");

            return response;
        }
Ejemplo n.º 20
0
 internal string ToJson()
 {
     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (JsonWriter jw = new JsonTextWriter(sw))
         {
             jw.WriteStartObject();
             if (!string.IsNullOrEmpty(AreaType))
             {
                 jw.WritePropertyName("areaType");
                 jw.WriteValue(AreaType);
             }
             if (!string.IsNullOrEmpty(BufferUnits))
             {
                 jw.WritePropertyName("bufferUnits");
                 jw.WriteValue(BufferUnits);
             }
             if (BufferRadii != null && BufferRadii.Count > 0)
             {
                 jw.WritePropertyName("Drives");
                 jw.WriteStartArray();
                 foreach (var radius in BufferRadii)
                     jw.WriteValue(radius);
                 jw.WriteEndArray();
             }
             jw.WriteEndObject();
         }
     }
     return sb.ToString();
 }
Ejemplo n.º 21
0
		public override void Execute(object parameter)
		{
			var saveFile = new SaveFileDialog
						   {
							   /*TODO, In Silverlight 5: DefaultFileName = string.Format("Dump of {0}, {1}", ApplicationModel.Database.Value.Name, DateTimeOffset.Now.ToString()), */
							   DefaultExt = ".raven.dump",
							   Filter = "Raven Dumps|*.raven.dump",
						   };

			if (saveFile.ShowDialog() != true)
				return;

			stream = saveFile.OpenFile();
			gZipStream = new GZipStream(stream, CompressionMode.Compress);
			streamWriter = new StreamWriter(gZipStream);
			jsonWriter = new JsonTextWriter(streamWriter)
						 {
							 Formatting = Formatting.Indented
						 };

			output(String.Format("Exporting to {0}", saveFile.SafeFileName));

			output("Begin reading indexes");

			jsonWriter.WriteStartObject();
			jsonWriter.WritePropertyName("Indexes");
			jsonWriter.WriteStartArray();

			ReadIndexes(0).Catch(exception => Infrastructure.Execute.OnTheUI(() => Finish(exception)));
		}
Ejemplo n.º 22
0
    public static string DataTableToJSON(DataTable dt, string dtName)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);

        using (JsonWriter jw = new JsonTextWriter(sw))
        {
            JsonSerializer ser = new JsonSerializer();
            jw.WriteStartObject();
            jw.WritePropertyName(dtName);
            jw.WriteStartArray();
            foreach (DataRow dr in dt.Rows)
            {
                jw.WriteStartObject();

                foreach (DataColumn dc in dt.Columns)
                {
                    jw.WritePropertyName(dc.ColumnName);
                    ser.Serialize(jw, dr[dc].ToString());
                }

                jw.WriteEndObject();
            }
            jw.WriteEndArray();
            jw.WriteEndObject();

            sw.Close();
            jw.Close();

        }

        return sb.ToString();
    }
Ejemplo n.º 23
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.º 24
0
		//JsonWriter writer = new JsonTextWriter();
		protected static string BasicRequest(int requestID, string method, string sessionID, params string[] parameters)
		{
			StringBuilder sb = new StringBuilder();
			StringWriter sw = new StringWriter(sb);

			using (JsonWriter writer = new JsonTextWriter(sw))
			{
				writer.Formatting = Formatting.Indented;

				writer.WriteStartObject();
				writer.WritePropertyName("jsonrpc");
				writer.WriteValue("2.0");
				writer.WritePropertyName("id");
				writer.WriteValue(requestID);
				writer.WritePropertyName("method");
				writer.WriteValue(method);
				writer.WritePropertyName("params");
				writer.WriteStartArray();
				writer.WriteValue(sessionID);
				foreach (var p in parameters)
					writer.WriteValue(p);
				writer.WriteEndArray();
				writer.WriteEndObject();
                return sb.ToString();
				//return sb.ToString().Replace("\n","");
			}
		}
Ejemplo n.º 25
0
 /// <summary>写入列表元素对象开始标记。</summary>
 /// <param name="pName">列表元素对象实例名称。</param>
 public void WriteStartArrayItem(string pName)
 {
     if (_textWriter.WriteState != WriteState.Array)
     {
         _textWriter.WritePropertyName(pName);
         _textWriter.WriteStartArray();
     }
     _textWriter.WriteStartObject();
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Writes union 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.WriteStartArray();
     foreach (Schema schema in this.Schemas)
     {
         schema.WriteJson(writer, names, encspace);
     }
     writer.WriteEndArray();
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Write API JSON.
 /// </summary>
 /// <param name="jw">The JSON writer.</param>
 internal void Write(JsonTextWriter jw)
 {
     jw.WritePropertyName(this.Name);
     jw.WriteStartArray();
     foreach (DirectMethod method in this.methods.Values)
     {
         method.Write(jw);
     }
     jw.WriteEndArray();
 }
Ejemplo n.º 28
0
		protected override void WriteTransaction(JsonTextWriter writer, Transaction tx)
		{
			WritePropertyValue(writer, "hash", tx.GetHash().ToString());
			WritePropertyValue(writer, "ver", tx.Version);

			WritePropertyValue(writer, "vin_sz", tx.Inputs.Count);
			WritePropertyValue(writer, "vout_sz", tx.Outputs.Count);

			WritePropertyValue(writer, "lock_time", tx.LockTime.Value);

			WritePropertyValue(writer, "size", tx.GetSerializedSize());

			writer.WritePropertyName("in");
			writer.WriteStartArray();
			foreach(var input in tx.Inputs.AsIndexedInputs())
			{
				var txin = input.TxIn;
				writer.WriteStartObject();
				writer.WritePropertyName("prev_out");
				writer.WriteStartObject();
				WritePropertyValue(writer, "hash", txin.PrevOut.Hash.ToString());
				WritePropertyValue(writer, "n", txin.PrevOut.N);
				writer.WriteEndObject();

				if(txin.PrevOut.Hash == uint256.Zero)
				{
					WritePropertyValue(writer, "coinbase", Encoders.Hex.EncodeData(txin.ScriptSig.ToBytes()));
				}
				else
				{
					WritePropertyValue(writer, "scriptSig", txin.ScriptSig.ToString());
				}
				if(input.WitScript != WitScript.Empty)
				{
					WritePropertyValue(writer, "witness", input.WitScript.ToString());
				}
				if(txin.Sequence != uint.MaxValue)
				{
					WritePropertyValue(writer, "sequence", (uint)txin.Sequence);
				}
				writer.WriteEndObject();
			}
			writer.WriteEndArray();
			writer.WritePropertyName("out");
			writer.WriteStartArray();
			
			foreach(var txout in tx.Outputs)
			{
				writer.WriteStartObject();
				WritePropertyValue(writer, "value", txout.Value.ToString(false, false));
				WritePropertyValue(writer, "scriptPubKey", txout.ScriptPubKey.ToString());
				writer.WriteEndObject();
			}
			writer.WriteEndArray();
		}
Ejemplo n.º 29
0
        public string ToJsonString()
        {
            var sb = new StringBuilder();

            using(var sw = new StringWriter(sb))
            using(JsonWriter jw = new JsonTextWriter(sw))
            {
                jw.WriteStartArray();

                jw.WriteValue(FunctionName);
                jw.WriteStartArray();

                Argument.ForEach(a => jw.WriteRawValue(a.ToString()));

                jw.WriteEndArray();
                jw.WriteEndArray();
            }

            return sb.ToString();
        }
        public JsonFileSinkAdapter(StreamWriter streamWriter, JsonSerializer serializer)
        {
            Guard.NotNull("streamWriter", streamWriter);
            Guard.NotNull("serializer", serializer);

            this.streamWriter = streamWriter;
            this.serializer = serializer;

            jsonWriter = new JsonTextWriter(streamWriter);
            jsonWriter.WriteStartArray();
        }
Ejemplo n.º 31
0
        public static void WriteCoord(Point coordinate, JsonTextWriter writer)
        {
            if (coordinate == null)
                return;
            if (writer == null)
                throw new ArgumentNullException("writer", "A valid JSON writer object is required");

            writer.WriteStartArray();
            writer.WriteValue(coordinate.X);
            writer.WriteValue(coordinate.Y);
            writer.WriteEndArray();
        }
Ejemplo n.º 32
0
    public void NullableValueFormatting()
    {
      StringWriter sw = new StringWriter();
      using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
      {
        jsonWriter.WriteStartArray();
        jsonWriter.WriteValue((char?)null);
        jsonWriter.WriteValue((char?)'c');
        jsonWriter.WriteValue((bool?)null);
        jsonWriter.WriteValue((bool?)true);
        jsonWriter.WriteValue((byte?)null);
        jsonWriter.WriteValue((byte?)1);
        jsonWriter.WriteValue((sbyte?)null);
        jsonWriter.WriteValue((sbyte?)1);
        jsonWriter.WriteValue((short?)null);
        jsonWriter.WriteValue((short?)1);
        jsonWriter.WriteValue((ushort?)null);
        jsonWriter.WriteValue((ushort?)1);
        jsonWriter.WriteValue((int?)null);
        jsonWriter.WriteValue((int?)1);
        jsonWriter.WriteValue((uint?)null);
        jsonWriter.WriteValue((uint?)1);
        jsonWriter.WriteValue((long?)null);
        jsonWriter.WriteValue((long?)1);
        jsonWriter.WriteValue((ulong?)null);
        jsonWriter.WriteValue((ulong?)1);
        jsonWriter.WriteValue((double?)null);
        jsonWriter.WriteValue((double?)1.1);
        jsonWriter.WriteValue((float?)null);
        jsonWriter.WriteValue((float?)1.1);
        jsonWriter.WriteValue((decimal?)null);
        jsonWriter.WriteValue((decimal?)1.1m);
        jsonWriter.WriteValue((DateTime?)null);
        jsonWriter.WriteValue((DateTime?)new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc));
#if !PocketPC && !NET20
        jsonWriter.WriteValue((DateTimeOffset?)null);
        jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero));
#endif
        jsonWriter.WriteEndArray();
      }

      string json = sw.ToString();
      string expected;

#if !PocketPC && !NET20
      expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""\/Date(0)\/"",null,""\/Date(0+0000)\/""]";
#else
      expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""\/Date(0)\/""]";
#endif

      Assert.AreEqual(expected, json);
    }
        protected override ArraySegment <byte> SerializeObject(object value)
        {
            var type     = value.GetType();
            var typeName = writeCache.GetOrAdd(type, TypeHelper.BuildTypeName); // Get type or Register type

            using (var ms = new MemoryStream())
                using (var tw = new StreamWriter(ms))
                    using (var jw = new Newtonsoft.Json.JsonTextWriter(tw))
                    {
                        jw.WriteStartArray();                // [
                        jw.WriteValue(typeName);             // "type",
                        jsonSerializer.Serialize(jw, value); // obj

                        jw.WriteEndArray();                  // ]

                        jw.Flush();

                        return(new ArraySegment <byte>(ms.ToArray(), 0, (int)ms.Length));
                    }
        }
Ejemplo n.º 34
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();
        }
        public override byte[] GenerateBody(SendDirectMessageOptions args)
        {
            using (var tw = new System.IO.StringWriter())
                using (var writer = new Newtonsoft.Json.JsonTextWriter(tw))
                {
                    writer.WriteStartObject();

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

                    writer.WritePropertyName("type");
                    writer.WriteValue("message_create");

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

                    writer.WritePropertyName("target");
                    writer.WriteStartObject();
                    writer.WritePropertyName("recipient_id");
                    writer.WriteValue(args.Recipientid);
                    writer.WriteEndObject();

                    writer.WritePropertyName("message_data");
                    writer.WriteStartObject();
                    writer.WritePropertyName("text");
                    writer.WriteValue(args.Text);

                    if (args.Mediaid != null)
                    {
                        writer.WritePropertyName("attachment");
                        writer.WriteStartObject();

                        writer.WritePropertyName("type");
                        writer.WriteValue(args.Mediatype);

                        writer.WritePropertyName("media");
                        writer.WriteStartObject();
                        writer.WritePropertyName("id");
                        writer.WriteValue(args.Mediaid);
                        writer.WriteEndObject();

                        writer.WriteEndObject();
                    }

                    if (args.Quickreplies?.Any() ?? false)
                    {
                        writer.WritePropertyName("quick_reply");
                        writer.WriteStartObject();

                        writer.WritePropertyName("type");
                        writer.WriteValue("options");

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

                        foreach (var qr in args.Quickreplies)
                        {
                            writer.WriteStartObject();

                            writer.WritePropertyName("label");
                            writer.WriteValue(qr.Label);
                            writer.WritePropertyName("description");
                            writer.WriteValue(qr.Description);
                            writer.WritePropertyName("metdata");
                            writer.WriteValue(qr.Metadata);

                            writer.WriteEndObject();
                        }

                        writer.WriteEndArray();

                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();

                    writer.WriteEndObject();

                    writer.WriteEndObject();

                    writer.WriteEndObject();

                    return(System.Text.UTF8Encoding.UTF8.GetBytes(tw.ToString()));
                }
        }
Ejemplo n.º 36
0
        public void ExportProductsJson(string path, string storagePath, int workProcessID, bool zipIt = true)
        {
            try
            {
                bool cancelRequested;
                workProcessService.Update(workProcessID, "Export started", 0);

                var totalAll = db.Categories.Count() + db.Products.Count() +
                               db.OptionCategories.Count() + db.Options.Count() +
                               db.Uploads.Count();
                var countAll = 0;

                var fileName = "Products_" + DateTime.Now.ToString("yyyyMMddTHHmmss");

                var serializer = new JsonSerializer();
                serializer.Converters.Add(new JavaScriptDateTimeConverter());
                serializer.NullValueHandling = NullValueHandling.Ignore;
                serializer.Formatting        = Formatting.Indented;
                serializer.ContractResolver  = new CamelCasePropertyNamesContractResolver();

                using (var sw = new StreamWriter(Path.Combine(path, fileName + ".json")))
                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        writer.WriteStartObject();

                        #region Write categories

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

                        var count = 0;
                        var total = categoryService.FindAll().Count();
                        foreach (var category in categoryService.FindAll().OrderBy(c => c.Id).InChunksOf(100))
                        {
                            serializer.Serialize(writer, new
                            {
                                category.Id,
                                category.Name,
                                category.ParentId,
                                category.Description,
                                category.IsVisible,
                                SortOrder = category.SortOrder.AsNullIfDefault()
                            });

                            count++;
                            countAll++;
                            if (count % 100 == 0)
                            {
                                workProcessService.Update(workProcessID,
                                                          string.Format("Exporting product categories ({0} of {1})", count, total),
                                                          ((double)countAll / totalAll) * 100.0, out cancelRequested);
                                if (cancelRequested)
                                {
                                    return;
                                }
                            }
                        }

                        writer.WriteEndArray();

                        #endregion

                        #region Write option categories

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

                        count = 0;
                        total = db.OptionCategories.Count();
                        foreach (var category in db.OptionCategories.OrderBy(c => c.Id).InChunksOf(100))
                        {
                            serializer.Serialize(writer, new
                            {
                                category.Id,
                                category.Name,
                                category.Description,
                                category.Type,
                                category.IncludeInFilters
                            });

                            count++;
                            countAll++;
                            if (count % 100 == 0)
                            {
                                workProcessService.Update(workProcessID,
                                                          string.Format("Exporting option categories ({0} of {1})", count, total),
                                                          ((double)countAll / totalAll) * 100.0, out cancelRequested);
                                if (cancelRequested)
                                {
                                    return;
                                }
                            }
                        }

                        writer.WriteEndArray();

                        #endregion

                        #region Write options

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

                        count = 0;
                        total = db.Options.Count();
                        foreach (var option in db.Options.OrderBy(o => o.Id).InChunksOf(100))
                        {
                            serializer.Serialize(writer, new
                            {
                                option.Id,
                                option.Name,
                                option.OptionCategoryId,
                                option.Description,
                            });

                            count++;
                            countAll++;
                            if (count % 100 == 0)
                            {
                                workProcessService.Update(workProcessID,
                                                          string.Format("Exporting options ({0} of {1})", count, total),
                                                          ((double)countAll / totalAll) * 100.0, out cancelRequested);
                                if (cancelRequested)
                                {
                                    return;
                                }
                            }
                        }

                        writer.WriteEndArray();

                        #endregion

                        #region Write products

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

                        count = 0;
                        total = productFinder.FindAll().Count();
                        foreach (var product in productFinder.FindAll().OrderBy(p => p.Id).InChunksOf(100))
                        {
                            serializer.Serialize(writer, new
                            {
                                product.Id,
                                product.Sku,
                                product.Name,
                                product.Price,
                                product.CostPrice,
                                product.RetailPrice,
                                product.SalePrice,
                                Weight = product.Weight.AsNullIfDefault(),
                                product.Quantity,
                                product.Description,
                                product.Keywords,
                                product.IsFeatured,
                                product.IsVisible,
                                Categories = product.Categories.Select(c => c.Id).ToArray(),
                                TaxClass   =
                                    product.TaxClass != null ? product.TaxClass.Name : null,
                                Sections = product.Sections.Select(s =>
                                                                   new
                                {
                                    s.Title,
                                    s.Type,
                                    s.Position,
                                    s.Settings,
                                    s.Priority
                                }).ToArray(),
                                Options = product.Options.Select(o => o.Id).ToArray(),
                                Uploads = product.Uploads.Select(u =>
                                                                 new
                                {
                                    u.Id,
                                    u.SortOrder,
                                    u.Type
                                }).ToArray(),
                                Skus = product.Skus.Select(s =>
                                                           new
                                {
                                    s.Sku,
                                    s.UPC,
                                    s.Quantity,
                                    s.Price,
                                    s.Weight,
                                    Options = s.Options.Select(o => o.Id).ToArray(),
                                    Uploads = s.Uploads.Select(u => u.Id).ToArray()
                                })
                            });

                            count++;
                            countAll++;
                            if (count % 100 == 0)
                            {
                                workProcessService.Update(workProcessID,
                                                          string.Format("Exporting products ({0} of {1})", count, total),
                                                          ((double)countAll / totalAll) * 100.0, out cancelRequested);
                                if (cancelRequested)
                                {
                                    return;
                                }
                            }
                        }

                        writer.WriteEndArray();

                        #endregion

                        writer.WriteEndObject();
                    }

                if (zipIt)
                {
                    using (var zip = new ZipFile(Path.Combine(path, fileName + ".zip")))
                    {
                        zip.AddFile(Path.Combine(path, fileName + ".json"), "").FileName = "Export.json";
                        zip.Save();

                        foreach (var upload in db.Uploads.Where(u => u.Type == UploadType.ProductImage)
                                 .OrderBy(u => u.Id).InChunksOf(100))
                        {
                            zip.AddFile(Path.Combine(storagePath, upload.Id.ToString()), "")
                            .FileName = upload.Id + ".jpg";
                        }
                        zip.SaveProgress += delegate(object sender, SaveProgressEventArgs args)
                        {
                            if (args.EntriesSaved == 0 || args.EntriesSaved % 100 != 0)
                            {
                                return;
                            }
                            workProcessService.Update(workProcessID,
                                                      string.Format("Archiving photos ({0} of {1})", args.EntriesSaved,
                                                                    args.EntriesTotal),
                                                      ((double)(countAll + args.EntriesSaved) / totalAll) * 100.0,
                                                      out cancelRequested);
                            if (cancelRequested)
                            {
                                args.Cancel = true;
                            }
                        };
                        zip.Save();
                    }

                    File.Delete(Path.Combine(path, fileName + ".json"));
                }

                workProcessService.Update(workProcessID, "Export completed", 100, isComplete: true);
            }
            catch (Exception err)
            {
                try
                {
                    workProcessService.Update(workProcessID, "Export failed", 100, isComplete: true, error: err.Message);
                }
                catch
                {
                    // Probably db issue; do not throw exception to avoid thread kill
                }
            }
        }
Ejemplo n.º 37
-1
        public static void Notice(UserManager.UserClass _user)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;
                writer.WriteStartArray();
                writer.WriteValue((int)ServerOpcode.room_state);

                writer.WriteStartArray();

                writer.WriteStartArray();
                writer.WriteValue("GameServerDB");
                writer.WriteValue("");
                writer.WriteValue(9);
                writer.WriteEndArray();

                writer.WriteStartArray();
                writer.WriteValue("Bienvenido!");
                writer.WriteValue("");
                writer.WriteValue(9);
                writer.WriteEndArray();

                writer.WriteEndArray();

                writer.WriteEndArray();
            }
            _user.sep.Send(sb.ToString());
        }