WriteStartObject() public method

Writes the beginning of a JSON object.
public WriteStartObject ( ) : void
return void
Esempio n. 1
1
	private string CreateStatusText()
	{
		using (var sw = new StringWriter())
		using (var jsonWriter = new JsonTextWriter(sw))
		{
			jsonWriter.WriteStartObject();
			{
				// Login
				jsonWriter.WritePropertyName("login");
				jsonWriter.WriteStartObject();
				{
					jsonWriter.WritePropertyName("port");
					jsonWriter.WriteValue(LoginServer.Instance.Conf.Login.Port);
				}
				jsonWriter.WriteEndObject();

				// Servers
				jsonWriter.WritePropertyName("servers");
				jsonWriter.WriteStartObject();
				{
					foreach (var server in LoginServer.Instance.ServerList.List)
					{
						// Channels
						jsonWriter.WritePropertyName(server.Name);
						jsonWriter.WriteStartObject();
						{
							foreach (var channel in server.Channels)
							{
								// Channel
								jsonWriter.WritePropertyName(channel.Key);
								jsonWriter.WriteStartObject();
								{
									jsonWriter.WritePropertyName("host");
									jsonWriter.WriteValue(channel.Value.Host);

									jsonWriter.WritePropertyName("port");
									jsonWriter.WriteValue(channel.Value.Port);

									jsonWriter.WritePropertyName("online");
									jsonWriter.WriteValue(channel.Value.Users);

									jsonWriter.WritePropertyName("onlineMax");
									jsonWriter.WriteValue(channel.Value.MaxUsers);

									jsonWriter.WritePropertyName("state");
									jsonWriter.WriteValue(channel.Value.State);
								}
								jsonWriter.WriteEndObject();
							}
						}
						jsonWriter.WriteEndObject();
					}
				}
				jsonWriter.WriteEndObject();
			}
			jsonWriter.WriteEndObject();

			return sw.ToString();
		}
	}
Esempio n. 2
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();
        }
Esempio n. 3
0
        public string Serialize()
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

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

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("public");
                jsonWriter.WriteValue(true);

                jsonWriter.WritePropertyName("files");

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName(File);

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("content");
                jsonWriter.WriteValue(Code);
                jsonWriter.WriteEndObject();

                jsonWriter.WriteEndObject();

                jsonWriter.WriteEndObject();
            }

            return sb.ToString();
        }
Esempio n. 4
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();
        }
 /// <summary>
 /// Serializes <see cref="Graphic"/> into JSON string.
 /// </summary>
 /// <param name="graphic">graphic to serialize into JSON.</param>
 /// <returns>string representation of the JSON object.</returns>
 public static string ToJson(this  Graphic graphic)
 {
     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (JsonWriter jw = new JsonTextWriter(sw))
         {
             if (graphic.Geometry != null)
             {
                 jw.WriteStartObject();
                 jw.WritePropertyName("geometry");
                 // Gets the JSON string representation of the Geometry.
                 jw.WriteRawValue(graphic.Geometry.ToJson());
                 jw.WriteEndObject();
             }
             if (graphic.Attributes.Count > 0)
             {
                 jw.WriteStartObject();
                 foreach (var item in graphic.Attributes)
                 {
                     jw.WritePropertyName(item.Key);
                     jw.WriteValue(item.Value);
                 }
                 jw.WriteEndObject();
             }
         }
         return sb.ToString();
     }
 }
        /// <summary>
        /// Generate the json output for the page.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GenerateJson(IContent page)
        {
            string json;

            List<KeyValuePair<string, string>> propertyValues = page.GetPropertyValues();

            StringBuilder stringBuilder = new StringBuilder();

            using (StringWriter sw = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
            {
                JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented };

                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName(page.Name);

                jsonWriter.WriteStartObject();

                foreach (KeyValuePair<string, string> content in propertyValues)
                {
                    jsonWriter.WritePropertyName(content.Key);
                    jsonWriter.WriteValue(TextIndexer.StripHtml(content.Value, content.Value.Length));
                }

                jsonWriter.WriteEndObject();

                jsonWriter.WriteEndObject();

                json = sw.ToString();
            }

            return json;
        }
Esempio n. 7
0
        internal string MapFromAttributes()
        {
            var sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.Indented;
                jsonWriter.WriteStartObject();
                {
                    var typeName = this.TypeName.Resolve(this._connectionSettings);
                    jsonWriter.WritePropertyName(typeName);
                    jsonWriter.WriteStartObject();
                    {
                        this.WriteRootObjectProperties(jsonWriter);

                        jsonWriter.WritePropertyName("properties");
                        jsonWriter.WriteStartObject();
                        {
                            this.WriteProperties(jsonWriter);
                        }
                        jsonWriter.WriteEnd();
                    }
                    jsonWriter.WriteEnd();
                }
                jsonWriter.WriteEndObject();

                return sw.ToString();
            }
        }
Esempio n. 8
0
        private void SelectEmailExist()
        {
            string email = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"]))
            {
                email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"]));
            }
            int result = userBll.SelectEmailExist(email);

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (result == 0)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("500");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
        /// <summary>
        /// Serialize this phase to JSON.
        /// </summary>
        /// <returns>The phase as a JSON string.</returns>
        public string ToJsonString()
        {
            /*
             * NB: JsonTextWriter is guaranteed to close the StringWriter
             * https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonTextWriter.cs#L150-L160
             */
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                writer.WritePropertyName(PhaseType);

                // phase start
                writer.WriteStartObject();

                WriteJson(writer);
                writer.WriteProperty("keep", keep);
                writer.WriteEndObject();

                // phase end
                writer.WriteEndObject();
            }

            return sb.ToString();
        }
        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();
        }
Esempio n. 11
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();
    }
Esempio n. 12
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();
        }
Esempio n. 13
0
        public override bool DeleteFromIndex(ISearchableItem item)
        {
            Initialise();

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

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

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

                writer.WritePropertyName("id");
                writer.WriteValue(item.ItemKey.TypeId.ToString() + "," + item.Id.ToString());

                writer.WriteEndObject();
                writer.WriteEndObject();
            }

            try
            {
                WebClient wc = new WebClient();
                wc.Headers[HttpRequestHeader.ContentType] = "type:application/json";
                wc.UploadString("http://" + server + "/update/json", sb.ToString());
                wc.DownloadString("http://" + server + "/update?commit=true");
            }
            catch
            {
            }

            return true;
        }
Esempio n. 14
0
        private void GetUserInfoHead()
        {
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            string username = userMethod.CheckUserIndentity_Username();

            if (username.Trim() != "")
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("username");
                writer.WriteValue(username);
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("username");
                writer.WriteValue("");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Esempio n. 15
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();
		}
        private static void Go(Engine engine)
        {
            var missionDefinitionClass = engine.GetClass("WillowGame.MissionDefinition");
            if (missionDefinitionClass == null)
            {
                throw new InvalidOperationException();
            }

            using (var output = new StreamWriter("Missions.json", false, Encoding.Unicode))
            using (var writer = new JsonTextWriter(output))
            {
                writer.Indentation = 2;
                writer.IndentChar = ' ';
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();

                var missionDefinitions = engine.Objects
                    .Where(o => o.IsA(missionDefinitionClass) &&
                                o.GetName().StartsWith("Default__") ==
                                false)
                    .OrderBy(o => o.GetPath());
                foreach (dynamic missionDefinition in missionDefinitions)
                {
                    writer.WritePropertyName(missionDefinition.GetPath());
                    writer.WriteStartObject();

                    writer.WritePropertyName("number");
                    writer.WriteValue(missionDefinition.MissionNumber);

                    string missionName = missionDefinition.MissionName;
                    if (string.IsNullOrEmpty(missionName) == false)
                    {
                        writer.WritePropertyName("name");
                        writer.WriteValue(missionName);
                    }

                    string missionDescription = missionDefinition.MissionDescription;
                    if (string.IsNullOrEmpty(missionDescription) == false)
                    {
                        writer.WritePropertyName("description");
                        writer.WriteValue(missionDescription);
                    }

                    // TODO: objective info

                    writer.WriteEndObject();
                }

                writer.WriteEndObject();
                writer.Flush();
            }
        }
Esempio n. 17
0
        public bool Start(string context)
        {
            this.context = context;
            string uri = baseURI + @"start/";
            string method = "POST";
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
 
            using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.Indented;
 
                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("context");
                jsonWriter.WriteValue(this.context);
                jsonWriter.WritePropertyName("participants");
                jsonWriter.WriteStartArray();
                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("name");
                // use the current window user
                jsonWriter.WriteValue(Environment.UserName);
                jsonWriter.WritePropertyName("id");
                // use the computer name + windows user name
                jsonWriter.WriteValue(Environment.MachineName + "-" + Environment.UserName);
                jsonWriter.WriteEndObject();
                jsonWriter.WriteEnd();
                jsonWriter.WriteEndObject();
            }
            string json = sb.ToString();
            
            HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
            req.KeepAlive = false;
            req.Method = method;
            byte[] buffer = Encoding.ASCII.GetBytes(json);
            req.ContentLength = buffer.Length;
            req.ContentType = "application/json";
            Stream PostData = req.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();

            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            StreamReader tr = new StreamReader(resp.GetResponseStream());
            json = tr.ReadToEnd();            
            Dictionary<string, string> respValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            if (respValues.ContainsKey("status") && respValues["status"] == "success")
            {
                this.dialogueID = respValues["dlg_id"];
                this.IsRunning = true;
                return true;
            }
            return false;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();

             var oSB = new StringBuilder();
             var oSW = new StringWriter(oSB);

             using (JsonWriter oWriter = new JsonTextWriter(oSW))
             {
            oWriter.Formatting = Formatting.Indented;

            oWriter.WriteStartObject();

            if (IsAuthenticated && ApplicationContext.IsStaff)
            {
               oWriter.WritePropertyName("results");
               oWriter.WriteStartArray();

               if (!string.IsNullOrEmpty(Request.QueryString["q"]))
               {
                  var sQuery = Request.QueryString["q"];
                  DataAccess.Log = new DebugTextWriter();

                  var oResults = DataAccess.fn_Producer_GetCustomerLookup();
                  oResults = oResults.Where(row => (row.FirstName + " " + row.LastName + " (" + row.Username + ")").Contains(sQuery))
                                     .Distinct().Take(30);

                  foreach (var oResult in oResults)
                  {
                     oWriter.WriteStartObject();
                     oWriter.WritePropertyName("id");
                     oWriter.WriteValue(oResult.MPUserID.ToString());
                     oWriter.WritePropertyName("name");
                     oWriter.WriteValue(string.Format("{0} {1} ({2})", oResult.FirstName, oResult.LastName, oResult.Username));
                     oWriter.WriteEndObject();
                  }

                  oWriter.WriteEnd();
               }
            }

            oWriter.WriteEndObject();
             }

             Response.ContentType = "application/json";
             Response.Write(oSB.ToString());
             Response.End();
        }
        //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;
        }
        internal static string JsonSerializePayload(IEnumerable<KeyValuePair<string, object>> payload)
        {
            try
            {
                using (var writer = new StringWriter(CultureInfo.InvariantCulture))
                using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Newtonsoft.Json.Formatting.Indented, CloseOutput = false })
                {
                    jsonWriter.WriteStartObject();

                    foreach (var item in payload)
                    {
                        JsonWriteProperty(jsonWriter, item.Key, item.Value);
                    }

                    jsonWriter.WriteEndObject();
                    jsonWriter.Flush();
                    return writer.ToString();
                }
            }
            catch (JsonWriterException jwe)
            {
                SemanticLoggingEventSource.Log.EventEntrySerializePayloadFailed(jwe.ToString());

                var errorDictionary = new Dictionary<string, object>
                {
                    {
                        "Error",
                        string.Format(CultureInfo.CurrentCulture, Properties.Resources.JsonSerializationError, jwe.Message)
                    }
                };

                return JsonConvert.SerializeObject(errorDictionary, Newtonsoft.Json.Formatting.Indented);
            }
        }
Esempio n. 21
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();
 }
Esempio n. 22
0
 public static void Emit(string msg, params object[] data)
 {
     if(outputFile != null)
     {
         outputFile.Write(DateTime.Now.ToString("o"));
         outputFile.Write(" " + msg + " ");
         try
         {
             JsonTextWriter json = new JsonTextWriter(outputFile);
             int ndata = data.Length / 2;
             json.WriteStartObject();
             for(int k = 0; k < ndata; k++)
             {
                 json.WritePropertyName((string) data[2 * k]);
                 jsonSerializer.Serialize(json, data[2 * k + 1]);
             }
             json.WriteEndObject();
         }
         catch(Exception e)
         {
             outputFile.WriteLine("...<" + e.ToString() + ">");
             outputFile.Flush();
             return;
         }
         outputFile.WriteLine();
         outputFile.Flush();
     }
 }
Esempio n. 23
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;
        }
Esempio n. 24
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);
 }
Esempio n. 25
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();
 }
        /// <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();
        }
Esempio n. 27
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","");
			}
		}
Esempio n. 28
0
        /// <summary>
        /// Create new JSON data with the original and name value list.
        /// </summary>
        /// <param name="json">The original JSON data.</param>
        /// <param name="nameValues">The name values to add to the JSON data.</param>
        /// <returns>The new JSON data.</returns>
        public string Create(string json, JsonNameValue[] nameValues)
        {
            // Using string builder.
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            // Create the writer.
            using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                writer.WriteRaw(json.Trim(new char[] { '{', '}' }) + ",");

                // For each name value pair.
                foreach (JsonNameValue item in nameValues)
                {
                    writer.WritePropertyName(item.Name);
                    writer.WriteValue(item.Value);
                }

                // Write the end object.
                writer.WriteEndObject();
            }

            // Return the JSON data.
            return(sb.ToString());
        }
Esempio n. 29
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();
        }
Esempio n. 30
0
        public static void WriteTo(this SecsMessage msg, JsonTextWriter jwtr)
        {
            jwtr.WriteStartObject();

            jwtr.WritePropertyName(nameof(msg.S));
            jwtr.WriteValue(msg.S);

            jwtr.WritePropertyName(nameof(msg.F));
            jwtr.WriteValue(msg.S);

            jwtr.WritePropertyName(nameof(msg.ReplyExpected));
            jwtr.WriteValue(msg.ReplyExpected);

            jwtr.WritePropertyName(nameof(msg.Name));
            jwtr.WriteValue(msg.Name);

            if (msg.SecsItem != null)
            {
                jwtr.WritePropertyName(nameof(msg.SecsItem));
                msg.SecsItem.WriteTo(jwtr);
            }

            jwtr.WriteEndObject();

            jwtr.Flush();
        }
Esempio n. 31
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();
            }
Esempio n. 32
0
        /// <summary/>
        private static void                     WriteRow(IRow row, JsonTextWriter writer)
        {
            // Row
            //  => { c1:v1, c2:v2, ...}

            // Header
            writer.WriteStartObject();

            // Fields
            var columns = row.Schema;
            for(int i=0; i<columns.Count; i++)
            {
                // Note: We simply delegate to Json.Net for all data conversions
                //  For data conversions beyond what Json.Net supports, do an explicit projection:
                //      ie: SELECT datetime.ToString(...) AS datetime, ...
                object value = row.Get<object>(i);

                // Note: We don't bloat the JSON with sparse (null) properties
                if(value != null)
                { 
                    writer.WritePropertyName(columns[i].Name, escape:true);
                    writer.WriteValue(value);
                }
            }

            // Footer
            writer.WriteEndObject();
        }
Esempio n. 33
0
        public void Compile()
        {
            System.Diagnostics.Debug.Assert(_inputs != null);
            if(!string.IsNullOrWhiteSpace(_query))
            {
                return;
            }

            var sb = new StringBuilder();

            using(var sw = new StringWriter(sb))
            using(JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.WriteStartObject();

                if(_inputs != null)
                {
                    _inputs.WriteJson(writer);
                }

                writer.WritePropertyName("query");

                writer.WriteStartArray();
                _phases.ForEach(p => writer.WriteRawValue(p.ToJsonString()));
                writer.WriteEndArray();

                writer.WriteEndObject();
            }

            _query = sb.ToString();
        }
Esempio n. 34
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)));
		}
Esempio n. 35
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 + "}");
        }
Esempio n. 36
0
        /// <summary>
        /// Returns the canonical JSON representation of this schema.
        /// </summary>
        /// <returns>The canonical JSON representation of this schema.</returns>
        public override string ToString()
        {
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
                using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("type");

                    WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space

                    writer.WriteEndObject();

                    return(sw.ToString());
                }
        }
Esempio n. 37
0
        /// <summary>
        /// Returns the canonical JSON representation of this schema.
        /// </summary>
        /// <returns>The canonical JSON representation of this schema.</returns>
        public override string ToString()
        {
            System.IO.StringWriter         sw     = new System.IO.StringWriter();
            Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (this is PrimitiveSchema || this is UnionSchema)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("type");
            }

            WriteJson(writer, new SchemaNames(), null); // stand alone schema, so no enclosing name space

            if (this is PrimitiveSchema || this is UnionSchema)
            {
                writer.WriteEndObject();
            }

            return(sw.ToString());
        }
Esempio n. 38
0
        /// <summary>
        /// 泛型对象转换到JSON表示字符串
        /// </summary>
        /// <param name="objectT">目标对象</param>
        /// <param name="totalResults">总记录数</param>
        /// <returns>返回JSON表示字符串</returns>
        public static string ToJSON(object objectT, int totalResults)
        {
            StringBuilder sbJSON;
            string        rawJSON = JsonConvert.SerializeObject(objectT);

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

            writer.WriteStartObject();

            writer.WritePropertyName("TotalRecord"); //总记录数
            writer.WriteValue(totalResults);

            writer.WritePropertyName("Data"); //数据集合
            writer.WriteRaw(rawJSON);
            writer.WriteEndObject();
            writer.Flush();

            sbJSON = sw.GetStringBuilder();
            return(sbJSON.ToString());
        }
Esempio n. 39
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
                }
            }
        }
Esempio n. 40
0
 /// <summary>写入文档开始标记。</summary>
 public void WriteStartDocument()
 {
     _textWriter.WriteStartObject();
 }
        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()));
                }
        }
Esempio n. 42
0
        private void LoginManage()
        {
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            int code_result = ValidCheckCode();//检测验证码:1、成功  2、验证码错误  3、请更换验证码重试

            if (code_result == 1)
            {
                string name = "";
                if (!string.IsNullOrEmpty(HttpContext.Current.Request["name"]))
                {
                    name = InText.SafeSql(HttpContext.Current.Request["name"]);
                }
                string pwd = "";
                if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
                {
                    pwd = WebBasic.Encryption.Encrypt(InText.SafeSql(HttpContext.Current.Request["pwd"]));
                }

                String    sql = string.Format("select * from t_admin where name='{0}' and pwd='{1}'", name, pwd);
                DataTable dt  = artBll.SelectToDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    //将后台人员信息保存至session
                    Session["adminId"]    = dt.Rows[0]["id"].ToString();
                    Session["login_name"] = dt.Rows[0]["name"].ToString();
                    Session["pwd"]        = WebBasic.Encryption.Encrypt(dt.Rows[0]["pwd"].ToString());

                    //----将信息保存到Cookie----
                    HttpCookie hc = new HttpCookie("Cookie_admin");
                    hc.Values["adminId"]    = HttpUtility.UrlEncode(dt.Rows[0]["id"].ToString());
                    hc.Values["login_name"] = HttpUtility.UrlEncode(dt.Rows[0]["name"].ToString());
                    hc.Values["pwd"]        = WebBasic.Encryption.Encrypt(dt.Rows[0]["pwd"].ToString());//密码再次加密

                    if (cookie_domain != "")
                    {
                        hc.Domain = cookie_domain;
                    }
                    hc.Expires = DateTime.Now.AddDays(1);
                    Response.Cookies.Add(hc);

                    //writer.WriteStartArray();
                    writer.WriteStartObject();
                    writer.WritePropertyName("result");
                    writer.WriteValue("success");
                    writer.WriteEndObject();
                    writer.Flush();
                    //writer.WriteEndArray();
                }
                else
                {
                    //writer.WriteStartArray();
                    writer.WriteStartObject();
                    writer.WritePropertyName("result");
                    writer.WriteValue("failed");
                    writer.WritePropertyName("message");
                    writer.WriteValue("用户名或密码错误");
                    writer.WriteEndObject();
                    writer.Flush();
                    //writer.WriteEndArray();
                }
            }
            else
            {
                //writer.WriteStartArray();
                writer.WriteStartObject();
                writer.WritePropertyName("result");
                writer.WriteValue("failed");
                writer.WritePropertyName("message");
                if (code_result == 2)
                {
                    writer.WriteValue("验证码错误");
                }
                else
                {
                    writer.WriteValue("请更换验证码重试");
                }
                writer.WriteEndObject();
                writer.Flush();
                //writer.WriteEndArray();
            }

            string jsonText = sw.GetStringBuilder().ToString();

            //jsonText = "{\"returnValue\":" + jsonText + "}";
            Response.Write(jsonText);
        }
Esempio n. 43
0
        private void register()
        {
            string username = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            {
                username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"]));
            }
            string pwd = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            {
                pwd = Utils.Encrypt(InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"])));
            }
            string email = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"]))
            {
                email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"]));
            }
            int sex = 2;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["sex"]))
            {
                sex = Utils.CheckInt(HttpContext.Current.Request["sex"]);
            }
            int baby = 2;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby"]))
            {
                baby = Utils.CheckInt(HttpContext.Current.Request["baby"]);
            }
            DateTime baby_date = DateTime.Now;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby_date"]))
            {
                baby_date = Convert.ToDateTime(HttpContext.Current.Request["baby_date"]);
            }
            string remark = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["remark"]))
            {
                remark = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["remark"]));
            }

            int result = userBll.Add_User(username, pwd, email, sex, baby, baby_date, remark);

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (result > 0)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("newid");
                writer.WriteValue(result.ToString());
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("500");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Esempio n. 44
0
        private void Login()
        {
            //string username = "";
            //if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            //{
            //    username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"]));
            //}
            //string pwd = "";
            //if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            //{
            //    pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"]));
            //    //pwd = WebBasic.Encryption.Encrypt(pwd);
            //    pwd = Utils.Encrypt(pwd);
            //}
            string username = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            {
                username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["username"]));
            }
            string pwd = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            {
                pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["pwd"]));
                //pwd = WebBasic.Encryption.Encrypt(pwd);
                pwd = Utils.Encrypt(pwd);
            }
            int valid_type = 1;//1、根据用户名判断  2、根据邮箱判断

            if (username.Contains("@"))
            {
                valid_type = 2;
            }
            int result = 0;

            if (userBll.SelectUsernameEmailExist(username) > 0)

            {
                int count = userBll.SelectUserPwdIsTrue(username, pwd, valid_type);
                if (count > 0)
                {
                    result = UserLogin(username);//执行登录,并返回登录结果
                }
                else
                {
                    result = 2;//用户名或密码错误
                }
            }
            else
            {
                result = 4;//用户名不存在
            }
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            writer.WriteStartObject();
            writer.WritePropertyName("status");
            writer.WriteValue("200");
            writer.WritePropertyName("result");
            writer.WriteValue(result.ToString());
            writer.WriteEndObject();
            writer.Flush();

            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }