Beispiel #1
0
    public static void SerializeBeatmap(Beatmap map, string fileName)
    {
        StringBuilder sb = new StringBuilder();

        using (StringWriter stream = new StringWriter(sb))
            using (JsonWriter writer = new JsonTextWriter(stream))
            {
                writer.Formatting = Formatting.Indented;

                writer.WriteStartObject();
                {
                    writer.WritePropertyName("version"); writer.WriteValue(m_latestDeserializer.Version);
                    writer.WriteWhitespace("\n");
                    writer.WriteComment("Metadata");
                    {
                        writer.WritePropertyName("SongName"); writer.WriteValue(map.SongName);
                        writer.WritePropertyName("RomanizedSongName"); writer.WriteValue(map.RomanizedSongName);
                        writer.WritePropertyName("DifficultyName"); writer.WriteValue(map.DifficultyName);
                        writer.WritePropertyName("Author"); writer.WriteValue(map.Author);
                        writer.WritePropertyName("Artist"); writer.WriteValue(map.Artist);
                        writer.WritePropertyName("RomanizedArtist"); writer.WriteValue(map.RomanizedArtist);
                    }
                    writer.WriteWhitespace("\n");
                    writer.WriteComment("Modifierdata");
                    {
                        writer.WritePropertyName("SpeedMod"); writer.WriteValue(map.SpeedMod);
                        writer.WritePropertyName("AccMod"); writer.WriteValue(map.AccMod);
                        writer.WritePropertyName("SliceCount"); writer.WriteValue(map.SliceCount);
                    }
                    writer.WriteWhitespace("\n");
                    writer.WriteComment("Filedata");
                    {
                        writer.WritePropertyName("SongPath"); writer.WriteValue(map.SongPath);
                        writer.WritePropertyName("BackgroundPath"); writer.WriteValue(map.BackgroundPath);
                    }
                    writer.WriteWhitespace("\n");
                    writer.WriteComment("Notedata");
                    {
                        writer.WritePropertyName("Notes");
                        writer.WriteStartArray();
                        foreach (Note note in map.Notes)
                        {
                            writer.WriteStartObject();
                            {
                                writer.WritePropertyName("time"); writer.WriteValue(note.time.Ms);
                                writer.WritePropertyName("slice"); writer.WriteValue(note.slice);
                            }
                            writer.WriteEndObject();
                        }
                        writer.WriteEndArray();
                    }
                }
                writer.WriteEndObject();
            }
        File.WriteAllText(fileName, sb.ToString());
    }
Beispiel #2
0
        public static void TestJsonWrite()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

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

                writer.WriteStartObject();
                writer.WritePropertyName("inhospitalno");
                writer.WriteValue("6458290");
                writer.WritePropertyName("bedno");
                writer.WriteValue("51床");
                writer.WritePropertyName("name");
                writer.WriteValue("姜国臣");
                writer.WritePropertyName("age");
                writer.WriteValue("64");
                writer.WritePropertyName("tagcode");
                writer.WriteStartArray();
                writer.WriteValue("0110111441287");
                writer.WriteComment("二维码-NG,OCR-OK;");
                writer.WriteValue("0110111441288");
                writer.WriteValue("0110111441289");
                writer.WriteValue("0110111441290");
                writer.WriteValue("0110111441291");
                writer.WriteComment("二维码-NG,OCR-NG,需人工");
                writer.WriteValue("0110111441292");
                writer.WriteValue("0110111441293");
                writer.WriteValue("0110111441294");
                writer.WriteEnd();
                writer.WriteEndObject();
                //string output = JsonConvert.DeserializeObject(writer);
                //Convert to string and save
                string StringJson = sb.ToString();
                Console.WriteLine(StringJson);
                //System.IO.File.WriteAllText(@"D:\path.txt", StringJson);
                System.IO.File.WriteAllText(AppDirectory + "\\Result.txt", StringJson);
                Console.WriteLine("save Json at " + AppDirectory + "\\Result.txt");
            }

            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabyte hard drive"
            //   ]
            // }
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = 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 gigabyte hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }
            Console.WriteLine(sb.ToString());
        }
Beispiel #4
0
        public static string WriteDepthArray(int depth, bool writeComment = false)
        {
            var sb         = new StringBuilder();
            var textWriter = new StringWriter();
            var json       = new JsonTextWriter(textWriter);

            json.WriteStartArray();
            for (int i = 0; i < depth; i++)
            {
                json.WriteStartArray();
            }
            if (writeComment)
            {
                json.WriteComment("Random comment string");
            }
            json.WriteValue("Hello, World!");
            for (int i = 0; i < depth; i++)
            {
                json.WriteEndArray();
            }
            json.WriteEndArray();
            json.Flush();

            return(textWriter.ToString());
        }
Beispiel #5
0
        /// <summary>
        /// 写入Jeson字符串到文件中
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="jesonStr">jeson字符串</param>
        /// <returns></returns>
        public static bool WriteJesonFile(string fileName, string jesonStr)
        {
            try
            {
                string filePath = jesonFileMainPath + "//" + fileName;
                if (!Directory.Exists(jesonFileMainPath))
                {
                    Directory.CreateDirectory(jesonFileMainPath);
                }
                //JsonSerializer serializer = new JsonSerializer();
                //serializer.Converters.Add(new JavaScriptDateTimeConverter());
                //serializer.NullValueHandling = NullValueHandling.Ignore;

                StreamWriter sw     = new StreamWriter(filePath);
                JsonWriter   writer = new JsonTextWriter(sw);

                //把模型数据序列化并写入Json.net的JsonWriter流中
                //serializer.Serialize(writer, jesonStr);
                writer.WriteComment(jesonStr);

                writer.Close();
                sw.Close();
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #6
0
        public static string WriteDepthObject(int depth, bool writeComment = false)
        {
            var sb         = new StringBuilder();
            var textWriter = new StringWriter();
            var json       = new JsonTextWriter(textWriter);

            json.WriteStartObject();
            for (int i = 0; i < depth; i++)
            {
                json.WritePropertyName("message" + i);
                json.WriteStartObject();
            }
            if (writeComment)
            {
                json.WriteComment("Random comment string");
            }
            json.WritePropertyName("message" + depth);
            json.WriteValue("Hello, World!");
            for (int i = 0; i < depth; i++)
            {
                json.WriteEndObject();
            }
            json.WriteEndObject();
            json.Flush();

            return(textWriter.ToString());
        }
Beispiel #7
0
        private string ModsToJson(List <Mod> mods)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteComment("DO NOT EDIT THIS BY HAND WITHOUT KNOWING EXACTLY WHAT YOU ARE DOING" + Environment.NewLine + "THIS FILE IS CREATED BY MCM AND IS USED FOR KNOWING WHICH MODS ARE INSTALLED!");
                writer.WriteStartObject();
                writer.WritePropertyName("mods");
                writer.WriteStartArray();
                foreach (Mod mod in mods)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("name");
                    writer.WriteValue(mod.name);
                    writer.WritePropertyName("path");
                    writer.WriteValue(mod.path);
                    writer.WritePropertyName("type");
                    writer.WriteValue(mod.type);
                    writer.WritePropertyName("level");
                    writer.WriteValue(mod.level);
                    writer.WritePropertyName("version");
                    writer.WriteValue(mod.version.Key);
                    writer.WriteEndObject();
                }
                writer.WriteEnd();
            }
            return(sb.ToString());
        }
Beispiel #8
0
        private void WriteToken(JsonTextWriter writer, string propertyName, Object propertyValue)
        {
            if (isMetadataResolver && (
                    propertyName.StartsWith("Raven-Replication-") ||
                    propertyName.StartsWith("@") ||
                    propertyName == "Last-Modified" ||
                    propertyName == "Raven-Last-Modified"
                    ))
            {
                return;
            }

            writer.WritePropertyName(propertyName);
            var ravenJToken = propertyValue as RavenJToken;

            if (ravenJToken != null)
            {
                ravenJToken.WriteTo(writer);
                return;
            }
            var conflicted = propertyValue as Conflicted;

            if (conflicted != null)
            {
                writer.WriteComment(">>>> conflict start");
                writer.WriteStartArray();
                foreach (var token in conflicted.Values)
                {
                    token.WriteTo(writer);
                }
                writer.WriteEndArray();
                writer.WriteComment("<<<< conflict end");
                return;
            }

            var arrayWithWarning = propertyValue as ArrayWithWarning;

            if (arrayWithWarning != null)
            {
                writer.WriteComment(">>>> auto merged array start");
                arrayWithWarning.MergedArray.WriteTo(writer);
                writer.WriteComment("<<<< auto merged array end");
                return;
            }

            throw new InvalidOperationException("Could not understand how to deal with: " + propertyValue);
        }
Beispiel #9
0
        /// <summary>
        /// Reads a JSON string into a new, formatted JSON string.
        /// This function will keep all JSON properties with the same name, whereas <see cref="Newtonsoft.Json"/>
        /// equivalents consolidate properties of the same name and only includes the last property with a particular name.
        /// </summary>
        /// <remarks>
        /// This is not an efficient function and should be used conservatively for displaying JSON to users in a readable format.
        /// </remarks>
        public static string PrettyPrintJson(string json)
        {
            using (var sbPool = Pools.GetStringBuilder())
                using (var reader = new JsonTextReader(new StringReader(json)))
                {
                    using (var writer = new JsonTextWriter(new StringWriter(sbPool.Instance)))
                    {
                        writer.Formatting = Formatting.Indented;

                        var parentStack = new Stack <JsonNode>();
                        var currentNode = new JsonNode();

                        while (reader.Read())
                        {
                            switch (reader.TokenType)
                            {
                            case JsonToken.StartObject:
                                writer.WriteStartObject();
                                break;

                            case JsonToken.PropertyName:
                                writer.WritePropertyName(reader.Value.ToString());
                                break;

                            // BuildXL JSON, only allow string values
                            case JsonToken.String:
                                writer.WriteValue(reader.Value.ToString());
                                break;

                            case JsonToken.EndObject:
                                writer.WriteEndObject();
                                break;

                            case JsonToken.StartArray:
                                writer.WriteStartArray();
                                break;

                            case JsonToken.EndArray:
                                writer.WriteEndArray();
                                break;

                            case JsonToken.Comment:
                                writer.WriteComment(reader.Value.ToString());
                                break;

                            default:
                                break;
                            }
                        }

                        // Make sure writer is fully closed and done writing before using the underlying string
                        return(sbPool.Instance.ToString());
                    }
                }
        }
Beispiel #10
0
        public static string InsertCommentsEverywhere(string jsonString)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

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

                var newtonsoft = new JsonTextReader(new StringReader(jsonString));
                writer.WriteComment("comment");
                while (newtonsoft.Read())
                {
                    writer.WriteToken(newtonsoft, writeChildren: false);
                    writer.WriteComment("comment");
                }
                writer.WriteComment("comment");
            }
            return(sb.ToString());
        }
Beispiel #11
0
        private void WriteEnumComment <T>(JsonTextWriter writer)
        {
            var descriptions = new List <string>();

            foreach (Enum value in Enum.GetValues(typeof(T)))
            {
                descriptions.Add($"'{value.GetDescription()}'");
            }

            writer.WriteComment($"Possible values are: {string.Join(", ", descriptions)}");
        }
        public void Indenting()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

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

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("CPU");
                jsonWriter.WriteValue("Intel");
                jsonWriter.WritePropertyName("PSU");
                jsonWriter.WriteValue("500W");
                jsonWriter.WritePropertyName("Drives");
                jsonWriter.WriteStartArray();
                jsonWriter.WriteValue("DVD read/writer");
                jsonWriter.WriteComment("(broken)");
                jsonWriter.WriteValue("500 gigabyte hard drive");
                jsonWriter.WriteValue("200 gigabype hard drive");
                jsonWriter.WriteEnd();
                jsonWriter.WriteEndObject();
            }

            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }

            string expected = @"{
  ""CPU"": ""Intel"",
  ""PSU"": ""500W"",
  ""Drives"": [
    ""DVD read/writer""
    /*(broken)*/,
    ""500 gigabyte hard drive"",
    ""200 gigabype hard drive""
  ]
}";
            string result   = sb.ToString();

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

            Assert.AreEqual(expected, result);
        }
        public void Example()
        {
            #region Usage
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = 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 gigabyte hard drive");
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            Console.WriteLine(sb.ToString());
            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabyte hard drive"
            //   ]
            // }
            #endregion

            StringAssert.AreEqual(
                @"{
  ""CPU"": ""Intel"",
  ""PSU"": ""500W"",
  ""Drives"": [
    ""DVD read/writer""
    /*(broken)*/,
    ""500 gigabyte hard drive"",
    ""200 gigabyte hard drive""
  ]
}",
                sb.ToString()
                );
        }
        public void Example()
        {
            #region Usage
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = 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();
            }

            Console.WriteLine(sb.ToString());
            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion

            Assert.AreEqual(@"{
  ""CPU"": ""Intel"",
  ""PSU"": ""500W"",
  ""Drives"": [
    ""DVD read/writer""
    /*(broken)*/,
    ""500 gigabyte hard drive"",
    ""200 gigabype hard drive""
  ]
}", sb.ToString());
        }
        void WriteGameObject(object ob, TypeInfo typeInfo, bool writeType)
        {
            m_writer.WriteStartObject();

            m_writer.WriteWhitespace(" ");
            m_writer.WriteComment(ob.ToString());

            bool canRef = typeInfo.UseRef;
            int  id     = canRef == false ? -1 : m_referenceResolver.Get(ob);

            if (canRef && id != -1)
            {
                m_writer.WritePropertyName("$ref");
                m_writer.WriteValue(id);
            }
            else
            {
                if (canRef)
                {
                    id = m_referenceResolver.Create(ob);
                    m_writer.WritePropertyName("$id");
                    m_writer.WriteValue(id);
                }

                if (writeType)
                {
                    m_writer.WritePropertyName("$type");
                    // XXX fully qualified name is rather long...
                    m_writer.WriteValue(typeInfo.Type.AssemblyQualifiedName);
                }

                WriteGameObjectData(ob, typeInfo);
            }

            m_writer.WriteEndObject();
        }
Beispiel #16
0
        public void SaveSettings()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");

            JsonSerializer jser = new JsonSerializer();
            var            json = JsonConvert.SerializeObject(Manager);

            using (StreamWriter sw = new StreamWriter(path))
            {
                using (JsonWriter JWriter = new JsonTextWriter(sw))
                {
                    JWriter.Formatting = Formatting.Indented;
                    JWriter.WriteCommentAsync($"\\***Auto Generated Settings****\\ \n");
                    jser.Serialize(JWriter, Manager);
                    JWriter.WriteComment($" \n Последнее изменение : {DateTime.Now} ");
                }
            }
        }
Beispiel #17
0
        public static void SerializeToFile(string filename, object value, string comment = null)
        {
            using (var writer = new StreamWriter(filename))
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jsonWriter.Formatting  = Formatting.Indented;
                    jsonWriter.Indentation = 1;
                    jsonWriter.IndentChar  = '\t';

                    if (comment != null)
                    {
                        jsonWriter.WriteComment(comment);
                        jsonWriter.WriteWhitespace(Environment.NewLine);
                    }
                    var serializer = new JsonSerializer
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    };
                    serializer.Serialize(jsonWriter, value);
                }
        }
        internal void ToString(JsonTextWriter jtw)
        {
            jtw.WritePropertyName(Name);
            if (Value is MyJArray)
            {
                ((MyJArray)Value).ToString(jtw);
            }
            else if (Value is MyJObject)
            {
                ((MyJObject)Value).ToString(jtw);
            }
            else
            {
                jtw.WriteValue(Value);
            }

            if (Comment != null)
            {
                jtw.WriteComment(Comment);
            }
        }
        // Save Settings
        public static void Save()
        {
            var sb           = new StringBuilder();
            var sw           = new StringWriter(sb);
            var settingsFile = Path.Combine(SettingsDir, "settings.cfg");

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

                writer.WriteStartObject();
                writer.WriteComment("Do not edit this file, you might break something!");
                writer.WritePropertyName("backupDir");
                writer.WriteValue(BackupDir);
                writer.WritePropertyName("steamDir");
                writer.WriteValue(SteamDir);
                writer.WritePropertyName("compresion");
                writer.WriteValue(Compression);
                writer.WritePropertyName("threadsBup");
                writer.WriteValue(ThreadsBup);
                writer.WritePropertyName("threadsRest");
                writer.WriteValue(ThreadsRest);
                writer.WritePropertyName("checkSteamRun");
                writer.WriteValue(CheckSteamRun);
                writer.WritePropertyName("debugMode");
                writer.WriteValue(DebugMode);
                writer.WritePropertyName("useLzma2");
                writer.WriteValue(UseLzma2);
                writer.WritePropertyName("lzma2UnlockThreads");
                writer.WriteValue(Lzma2UnlockThreads);
                writer.WritePropertyName("lzma2Threads");
                writer.WriteValue(Lzma2Threads);

                writer.WriteEndObject();
            }
            sw.Close();

            Directory.CreateDirectory(SettingsDir);
            File.WriteAllText(settingsFile, sb.ToString());
        }
Beispiel #20
0
        public static string WriteDepthObjectWithArray(int depth, bool writeComment = false)
        {
            var sb         = new StringBuilder();
            var textWriter = new StringWriter();
            var json       = new JsonTextWriter(textWriter);

            json.WriteStartObject();
            for (int i = 0; i < depth; i++)
            {
                json.WritePropertyName("message" + i);
                json.WriteStartObject();
            }
            if (writeComment)
            {
                json.WriteComment("Random comment string");
            }
            json.WritePropertyName("message" + depth);
            json.WriteStartArray();
            json.WriteValue("string1");
            json.WriteValue("string2");
            json.WriteEndArray();
            json.WritePropertyName("address");
            json.WriteStartObject();
            json.WritePropertyName("street");
            json.WriteValue("1 Microsoft Way");
            json.WritePropertyName("city");
            json.WriteValue("Redmond");
            json.WritePropertyName("zip");
            json.WriteValue(98052);
            json.WriteEndObject();
            for (int i = 0; i < depth; i++)
            {
                json.WriteEndObject();
            }
            json.WriteEndObject();
            json.Flush();

            return(textWriter.ToString());
        }
        public void ReadingAndWritingJsonText()
        {
            #region ReadingAndWritingJsonText
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = 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();
            }

            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion
        }
        public void ReadingAndWritingJsonText()
        {
            #region ReadingAndWritingJsonText
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = 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();
            }

            // {
            //   "CPU": "Intel",
            //   "PSU": "500W",
            //   "Drives": [
            //     "DVD read/writer"
            //     /*(broken)*/,
            //     "500 gigabyte hard drive",
            //     "200 gigabype hard drive"
            //   ]
            // }
            #endregion
        }
Beispiel #23
0
        /// <summary>
        /// Writes the fields contained in this configuration section to the given JsonTextWriter
        /// </summary>
        /// <param name="writer">The JsonTextWriter to write the section to.</param>
        /// <param name="containingProperty">The PropertyInfo object of the ConfigFile property that contains this section.</param>
        public void Write(JsonTextWriter writer, PropertyInfo containingProperty)
        {
            string indentation = new(writer.IndentChar, writer.Indentation * 2);

            writer.WritePropertyName(containingProperty.Name);
            writer.WriteStartObject();

            //Get all fields this configuration class contains
            foreach (PropertyInfo P in GetType().GetProperties())
            {
                //If this field has a comment attribute, add a comment now.
                CommentAttribute Attr = P.GetCustomAttribute <CommentAttribute>();
                if (Attr != null)
                {
                    writer.WriteWhitespace($"\n{indentation}");
                    writer.WriteComment(Attr.Comment.Replace("\n", $"\n{indentation}"));
                }

                //Write the field. If the field is an IList, write it as a JSON array instead of a regular field.
                writer.WritePropertyName(P.Name);
                if (P.PropertyType.IsGenericType && P.PropertyType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    writer.WriteStartArray();
                    var L = (IList)P.GetValue(this);
                    foreach (object Entry in L)
                    {
                        writer.WriteValue(Entry);
                    }
                    writer.WriteEndArray();
                }
                else
                {
                    writer.WriteValue(P.GetValue(this));
                }
            }
            writer.WriteEndObject();
        }
        public void CloseWithRemainingContent()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

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

                jsonWriter.WriteStartObject();
                jsonWriter.WritePropertyName("CPU");
                jsonWriter.WriteValue("Intel");
                jsonWriter.WritePropertyName("PSU");
                jsonWriter.WriteValue("500W");
                jsonWriter.WritePropertyName("Drives");
                jsonWriter.WriteStartArray();
                jsonWriter.WriteValue("DVD read/writer");
                jsonWriter.WriteComment("(broken)");
                jsonWriter.WriteValue("500 gigabyte hard drive");
                jsonWriter.WriteValue("200 gigabype hard drive");
                jsonWriter.Close();
            }

            string expected = @"{
  ""CPU"": ""Intel"",
  ""PSU"": ""500W"",
  ""Drives"": [
    ""DVD read/writer""
    /*(broken)*/,
    ""500 gigabyte hard drive"",
    ""200 gigabype hard drive""
  ]
}";
            string result   = sb.ToString();

            Assert.AreEqual(expected, result);
        }
        public void MakeConfigFile()
        {
            var configDir = Path.Combine(m_backupDir, "config.sbt");
            var sb        = new StringBuilder();
            var sw        = new StringWriter(sb);

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

                writer.WriteComment("DO NOT edit this file! you might destroy the backup!");
                writer.WriteWhitespace(Environment.NewLine);
                writer.WriteStartObject();
                writer.WritePropertyName("Archiver Version");
                writer.WriteValue(m_archiveVer);
                writer.WritePropertyName("ACF IDs");
                writer.WriteStartObject();

                var cfgFile = new ConfigFile();
                // Add already archived apps back into the list if they are not being backed up again (so we don't get any orphaned acf files).
                if (File.Exists(configDir))
                {
                    writer.WriteWhitespace(Environment.NewLine);
                    writer.WriteComment("From older backups");

                    using (var streamReader = new StreamReader(configDir))
                    {
                        try
                        {
                            cfgFile = JsonConvert.DeserializeObject <ConfigFile>(streamReader.ReadToEnd());
                        }
                        catch (Exception)
                        {
                            cfgFile = new ConfigFile();
                        }
                        finally
                        {
                            foreach (var acfId in cfgFile.AcfIds)
                            {
                                writer.WritePropertyName(acfId.Key);
                                writer.WriteValue(acfId.Value);
                            }
                        }
                    }
                }

                // Add new apps to the list
                writer.WriteWhitespace(Environment.NewLine);
                writer.WriteComment("From latest backup");
                foreach (var job in m_jobList)
                {
                    if (string.IsNullOrEmpty(job.m_acfFiles) || job.m_status != JobStatus.Waiting)
                    {
                        continue;
                    }

                    var name = Path.GetFileName(job.m_steamDir) ?? string.Empty;

                    if (cfgFile.AcfIds != null && cfgFile.AcfIds.ContainsKey(name))
                    {
                        continue;
                    }

                    writer.WritePropertyName(name);
                    writer.WriteValue(job.m_acfFiles);
                }
                writer.WriteEndObject();
                writer.WriteEndObject();
            }


            Directory.CreateDirectory(m_backupDir);
            File.WriteAllText(configDir, sb.ToString());
            sw.Close();
        }
Beispiel #26
0
        public string Serialize(IRestEaseOptions options)
        {
            var stringBuilder = new StringBuilder();

            using (var textWriter = new JsonTextWriter(new StringWriter(stringBuilder)))
            {
                textWriter.Formatting = Formatting.Indented;

                textWriter.WriteStartObject();
                textWriter.WriteComment("Use this file to overrule the RestEase Client Generator Options");

                textWriter.WritePropertyName(nameof(options.ApiNamespace));
                textWriter.WriteValue(options.ApiNamespace);

                textWriter.WritePropertyName(nameof(options.AppendAsync));
                textWriter.WriteValue(options.AppendAsync);

                textWriter.WritePropertyName(nameof(options.ApplicationOctetStreamType));
                textWriter.WriteValue(options.ApplicationOctetStreamType.GetDescription());
                WriteEnumComment <ApplicationOctetStreamType>(textWriter);

                textWriter.WritePropertyName(nameof(options.ArrayType));
                textWriter.WriteValue(options.ArrayType.GetDescription());
                WriteEnumComment <ArrayType>(textWriter);

                textWriter.WritePropertyName(nameof(options.FailOnOpenApiErrors));
                textWriter.WriteValue(options.FailOnOpenApiErrors);

                textWriter.WritePropertyName(nameof(options.ForceContentTypeToApplicationJson));
                textWriter.WriteValue(options.ForceContentTypeToApplicationJson);

                textWriter.WritePropertyName(nameof(options.GenerateApplicationOctetStreamExtensionMethods));
                textWriter.WriteValue(options.GenerateApplicationOctetStreamExtensionMethods);

                textWriter.WritePropertyName(nameof(options.GenerateMultipartFormDataExtensionMethods));
                textWriter.WriteValue(options.GenerateMultipartFormDataExtensionMethods);

                textWriter.WritePropertyName(nameof(options.GenerateFormUrlEncodedExtensionMethods));
                textWriter.WriteValue(options.GenerateFormUrlEncodedExtensionMethods);

                textWriter.WritePropertyName(nameof(options.GeneratePrimitivePropertiesAsNullableForOpenApi20));
                textWriter.WriteValue(options.GeneratePrimitivePropertiesAsNullableForOpenApi20);

                textWriter.WritePropertyName(nameof(options.MakeNonRequiredParametersOptional));
                textWriter.WriteValue(options.MakeNonRequiredParametersOptional);

                textWriter.WritePropertyName(nameof(options.MethodReturnType));
                textWriter.WriteValue(options.MethodReturnType.GetDescription());
                WriteEnumComment <MethodReturnType>(textWriter);

                textWriter.WritePropertyName(nameof(options.ModelsNamespace));
                textWriter.WriteValue(options.ModelsNamespace);

                textWriter.WritePropertyName(nameof(options.MultipartFormDataFileType));
                textWriter.WriteValue(options.MultipartFormDataFileType.GetDescription());
                WriteEnumComment <MultipartFormDataFileType>(textWriter);

                textWriter.WritePropertyName(nameof(options.PreferredContentType));
                textWriter.WriteValue(options.PreferredContentType.GetDescription());
                WriteEnumComment <ContentType>(textWriter);

                textWriter.WritePropertyName(nameof(options.PreferredSecurityDefinitionType));
                textWriter.WriteValue(options.PreferredSecurityDefinitionType.GetDescription());
                WriteEnumComment <SecurityDefinitionType>(textWriter);

                textWriter.WritePropertyName(nameof(options.ReturnObjectFromMethodWhenResponseIsDefinedButNoModelIsSpecified));
                textWriter.WriteValue(options.ReturnObjectFromMethodWhenResponseIsDefinedButNoModelIsSpecified);

                textWriter.WritePropertyName(nameof(options.SupportExtensionXNullable));
                textWriter.WriteValue(options.SupportExtensionXNullable);

                textWriter.WritePropertyName(nameof(options.UseDateTimeOffset));
                textWriter.WriteValue(options.UseDateTimeOffset);

                textWriter.WritePropertyName(nameof(options.UseOperationIdAsMethodName));
                textWriter.WriteValue(options.UseOperationIdAsMethodName);

                textWriter.WriteEndObject();
            }

            return(stringBuilder.ToString());
        }
Beispiel #27
0
        // Saves config to file
        public static bool SaveConfig()
        {
            try
            {
                FileStream fs         = File.Open("config.json", FileMode.Create, FileAccess.Write);
                JsonWriter jsonConfig = new JsonTextWriter(new StreamWriter(fs));
                jsonConfig.Formatting = Formatting.Indented;

                jsonConfig.WriteComment("Please don't edit the contents of this file directly and rather use the in-app Settings menu. " +
                                        "Please mind that deleting this file will also reset BRB statistics.");
                jsonConfig.WriteStartObject();

                jsonConfig.WritePropertyName("ConfigVersion");
                jsonConfig.WriteValue(ConfigVersion);
                jsonConfig.WritePropertyName("BRBDirectory");
                jsonConfig.WriteValue(BRBDirectory);
                jsonConfig.WritePropertyName("StartPlayerOnDifferentScreen");
                jsonConfig.WriteValue(StartPlayerOnDifferentScreen);
                jsonConfig.WritePropertyName("MakePlayerTopMost");
                jsonConfig.WriteValue(MakePlayerTopMost);
                jsonConfig.WritePropertyName("Chapter");
                jsonConfig.WriteValue(Chapter);
                jsonConfig.WritePropertyName("PermittedOvertimeMinutes");
                jsonConfig.WriteValue(PermittedOvertimeMinutes);
                jsonConfig.WritePropertyName("PermittedUndertimePercent");
                jsonConfig.WriteValue(PermittedUndertimePercent);
                jsonConfig.WritePropertyName("AvoidForChaptersAfterPlay");
                jsonConfig.WriteValue(AvoidForChaptersAfterPlay);
                jsonConfig.WritePropertyName("PreferredPlayAfterChapters");
                jsonConfig.WriteValue(PreferredPlayAfterChapters);
                jsonConfig.WritePropertyName("ChapterHistoryConsidered");
                jsonConfig.WriteValue(ChapterHistoryConsidered);
                jsonConfig.WritePropertyName("ReservedChanceForPriorityBRBs");
                jsonConfig.WriteValue(ReservedChanceForPriorityBRBs);
                jsonConfig.WritePropertyName("AutoGuaranteedPlaysForNewBRBs");
                jsonConfig.WriteValue(AutoGuaranteedPlaysForNewBRBs);
                jsonConfig.WritePropertyName("AutoPriorityPlaysForNewBRBs");
                jsonConfig.WriteValue(AutoPriorityPlaysForNewBRBs);
                jsonConfig.WritePropertyName("FavouriteMultiplier");
                jsonConfig.WriteValue(FavouriteMultiplier);
                jsonConfig.WritePropertyName("SortingMode");
                jsonConfig.WriteValue((int)SortingMode);
                jsonConfig.WritePropertyName("StandardPlayerVolume");
                jsonConfig.WriteValue(StandardPlayerVolume);
                jsonConfig.WritePropertyName("InterBRBCountdown");
                jsonConfig.WriteValue(InterBRBCountdown);
                jsonConfig.WritePropertyName("TimeUntilHobbVLC");
                jsonConfig.WriteValue(TimeUntilHobbVLC);
                jsonConfig.WritePropertyName("HobbVLCCountdown");
                jsonConfig.WriteValue(HobbVLCCountdown);
                jsonConfig.WritePropertyName("HobbVLCMaxDuration");
                jsonConfig.WriteValue(HobbVLCMaxDuration);
                jsonConfig.WritePropertyName("HobbVLCIgnoreMaxDurationAfterTries");
                jsonConfig.WriteValue(HobbVLCIgnoreMaxDurationAfterTries);

                jsonConfig.WriteEndObject();

                jsonConfig.Close();
                fs.Close();

                return(true);
            }
            catch (IOException)
            {
                return(false);
            }
            catch (JsonException)
            {
                return(false);
            }
        }
Beispiel #28
0
 public override void WriteComment(string text)
 {
     _textWriter.WriteComment(text);
     _innerWriter.WriteComment(text);
     base.WriteComment(text);
 }
Beispiel #29
0
        private static void WriteJson(JsonTextReader reader, JsonTextWriter writer)
        {
            switch (reader.TokenType)
            {
            case JsonToken.None:
                break;

            case JsonToken.StartObject:
                writer.WriteStartObject();
                break;

            case JsonToken.StartArray:
                writer.WriteStartArray();
                break;

            case JsonToken.StartConstructor:
                break;

            case JsonToken.PropertyName:
                writer.WritePropertyName((string)reader.Value);
                break;

            case JsonToken.Comment:
                writer.WriteComment((string)reader.Value);
                break;

            case JsonToken.Raw:
                break;

            case JsonToken.Integer:
            case JsonToken.Float:
            case JsonToken.String:
            case JsonToken.Boolean:
            case JsonToken.Date:
            case JsonToken.Bytes:
                writer.WriteValue(reader.Value);
                break;

            case JsonToken.Null:
                writer.WriteNull();
                break;

            case JsonToken.Undefined:
                writer.WriteUndefined();
                break;

            case JsonToken.EndObject:
                writer.WriteEndObject();
                break;

            case JsonToken.EndArray:
                writer.WriteEndArray();
                break;

            case JsonToken.EndConstructor:
                break;

            default:
                break;
            }
        }
Beispiel #30
0
        public override bool Read()
        {
            if (m_reader.Read())
            {
                ReadOtherReader();
                switch (m_otherReader.TokenType)
                {
                case JsonToken.Boolean:
                case JsonToken.Bytes:
                case JsonToken.Date:
                case JsonToken.String:
                case JsonToken.Integer:
                case JsonToken.Float:
                    m_writer.WriteValue(m_otherReader.Value);
                    break;

                case JsonToken.Comment:
                    m_writer.WriteComment((string)m_otherReader.Value);
                    break;

                case JsonToken.EndArray:
                    m_writer.WriteEndArray();
                    break;

                case JsonToken.EndConstructor:
                    m_writer.WriteEndConstructor();
                    break;

                case JsonToken.EndObject:
                    m_writer.WriteEndObject();
                    break;

                case JsonToken.Null:
                    m_writer.WriteNull();
                    break;

                case JsonToken.Raw:
                    break;

                case JsonToken.StartArray:
                    m_writer.WriteStartArray();
                    break;

                case JsonToken.StartConstructor:
                    m_writer.WriteStartConstructor((string)m_otherReader.Value);
                    break;

                case JsonToken.StartObject:
                    m_writer.WriteStartObject();
                    break;

                case JsonToken.PropertyName:
                    // Property names will be handled when value is written
                    break;

                default:
                    Contract.Assert(false, "unhandled token type");
                    break;
                }

                return(true);
            }

            return(false);
        }
        private string JsonDocumentationGenerator()
        {
            StringBuilder strBuilder = new StringBuilder();
            StringWriter  strWriter  = new StringWriter(strBuilder);
            JsonWriter    jsnWriter  = new JsonTextWriter(strWriter);
            char          IndentChar = '\t';

            string returnValue = "";

            using (strWriter)
            {
                using (jsnWriter)
                {
                    jsnWriter.Formatting          = Newtonsoft.Json.Formatting.Indented;
                    jsnWriter.AutoCompleteOnClose = true;

                    jsnWriter.WriteComment(
                        "* <B>Created by</B>: Will O\'Malley" + Environment.NewLine +
                        "* <B>For</B>: Used by the Query Wizard Sharepoint Web Part" + Environment.NewLine +
                        "* <B>Routes</B>:" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "<B>[</B><FONT COLOR=\"MidnightBlue\"><B>HttpGet</B></FONT><B>]</B> <FONT COLOR=\"DarkRed\">Get()</FONT>" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<B>URL</B>: /api/SqlServer" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Param</B>:</FONT> <FONT COLOR=\"DimGray\"><B>None</B></FONT>" + Environment.NewLine +
                        "*" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "<B>[</B><FONT COLOR=\"MidnightBlue\"><B>HttpGet</B></FONT><B>]</B> <FONT COLOR=\"DarkRed\">Get(<FONT COLOR=\"DimGray\"><B>StringFormat</B></FONT>)</FONT>" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<B>URL</B>: /api/SqlServer/json" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Param</B>:</FONT> <FONT COLOR=\"DimGray\"><B>StringFormat</B></FONT>" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Type</B>:</FONT> string" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Values</B>:</FONT> Json, Xml, HTML" + Environment.NewLine +
                        "*" + new string(IndentChar, 3) + "These values are <B><U>NOT</U></B> case sensitive." + Environment.NewLine +
                        "*" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "<B>[</B><FONT COLOR=\"MidnightBlue\"><B>HttpPost</B></FONT><B>]</B> <FONT COLOR=\"DarkRed\">Post(<FONT COLOR=\"DimGray\"><B>SqlCommunicatorConnection</B> value</FONT>)</FONT>" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Param</B>:</FONT> <FONT COLOR=\"DarkGray\"><B>value</B></FONT>" + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Type</B>:</FONT> " + typeof(SqlCommunicatorConnection).FullName.Trim() + Environment.NewLine +
                        "*" + new string(IndentChar, 2) + "<FONT COLOR=\"DarkBlue\"><B>Values</B>:</FONT> Serialized Json string representing Object." + Environment.NewLine +

                        // Add section seperator line:
                        "*" + new string('*', 90) + Environment.NewLine +

                        // Begin Example section:
                        "* <B>Example</B>:" + Environment.NewLine +
                        "* ||[" + Environment.NewLine +

                        // I'm using Concat to generate the Key/Value pairs.
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"WindowsUserName\"", "</FONT>", " <B>:</B> ", "\"DOMAIN\\UserName\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"SqlServerName\"", "</FONT>", " <B>:</B> ", "\"SQL Server Name\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"SqlServerInstanceName\"", "</FONT>", " <B>:</B> ", "\"Instance\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"SqlServerPort\"", "</FONT>", " <B>:</B> ", "1433", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"UseSqlServerAuthentication\"", "</FONT>", " <B>:</B> ", "\"true / false\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"UseWindowsAuthentication\"", "</FONT>", " <B>:</B> ", "\"true / false\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"UseAzureEncryption\"", "</FONT>", " <B>:</B> ", "\"true / false\"" + "," + Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"UseTrustedConnection\"", "</FONT>", " <B>:</B> ", "\"true / false\"" + "," + Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"UseNamedInstance\"", "</FONT>", " <B>:</B> ", "\"true / false\"" + "," + Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"SqlServerLoginUserName\"", "</FONT>", " <B>:</B> ", "\"SQL User Login Name\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"SqlServerLoginPassword\"", "</FONT>", " <B>:</B> ", "\"SQL User Login Password\"", ",", Environment.NewLine) +
                        "*" + new string(IndentChar, 1) + string.Concat("<FONT COLOR=\"DarkRed\">", "\"SqlQuery\"", "</FONT>", " <B>:</B> ", "\"SELECT * FROM SOME_TABLE...\"", Environment.NewLine) +
                        "* ]||" + Environment.NewLine +
                        // End Example section:

                        // Add section seperator line:
                        new string('*', 90) + Environment.NewLine +

                        // Begin Notes section:
                        "* <B>Notes</B>:" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "<B>Comments</B> are\'t really permitted in a JSON string, so, you will want to copy the string" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "below and paste it into NOTEPAD and remove them. " + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "This should also help remove the HTML formatting."
                        // End Notes section:
                        );

                    jsnWriter.WriteStartObject();

                    jsnWriter.WriteComment(
                        "* <B>Windows User Name</B>:" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "The application will try to get this info from SharePoint" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "If the app is not able to do that, the value for SqlServerLoginUserName gets passed." + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "However, because the app was unable to get the users User Name, this value never gets used." + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "This service will check the UseWindowsAuthentication and UseSqlServerAuthentication values to make sure" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "the user did not select Windows Authentication on accident."
                        );
                    jsnWriter.WritePropertyName("WindowsUserName", false);
                    jsnWriter.WriteValue("Windows User Name");

                    jsnWriter.WritePropertyName("SqlServerName", false);
                    jsnWriter.WriteValue("Server Name");

                    jsnWriter.WritePropertyName("SqlServerInstanceName", false);
                    jsnWriter.WriteValue("Instance Name");

                    jsnWriter.WritePropertyName("SqlServerPort", false);
                    jsnWriter.WriteValue("Depends on Server Configuration.");

                    jsnWriter.WritePropertyName("UseSqlServerAuthentication", false);
                    jsnWriter.WriteValue("true OR false");

                    jsnWriter.WritePropertyName("UseWindowsAuthentication", false);
                    jsnWriter.WriteValue("true OR false");

                    jsnWriter.WritePropertyName("UseAzureEncryption", false);
                    jsnWriter.WriteValue("true OR false");

                    jsnWriter.WriteComment(
                        "* <B>Trusted Connection</B>:" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "When connecting to SQL Server, this value tells us to use a Trusted Connection. " + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "This value is set on the backend and is not configurable from the connection wizard UI."
                        );
                    jsnWriter.WritePropertyName("UseTrustedConnection", false);
                    jsnWriter.WriteValue("true OR false");

                    jsnWriter.WritePropertyName("UseNamedInstance", false);
                    jsnWriter.WriteValue("true OR false");

                    jsnWriter.WriteComment(
                        "* <B>SQL Server Login User Name</B>: " + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "Make sure the SQL Login you are using has access to the Server and Database you are trying to query."
                        );
                    jsnWriter.WritePropertyName("SqlServerLoginUserName", false);
                    jsnWriter.WriteValue("SQL Login User Name");

                    jsnWriter.WritePropertyName("SqlServerLoginPassword", false);
                    jsnWriter.WriteValue("SQL Login Password");

                    jsnWriter.WriteComment(
                        "* <B>SQL Query</B>:" + Environment.NewLine +
                        "*" + new string(IndentChar, 1) + "This is the final/formatted query that gets passed to SQL Server for execution."
                        );
                    jsnWriter.WritePropertyName("SqlQuery", false);
                    jsnWriter.WriteValue("SQL Query");

                    jsnWriter.WriteEndObject();

                    jsnWriter.Close();
                }

                strWriter.Close();
            }

            returnValue = strBuilder.ToString();

            strBuilder.Clear();

            return(returnValue.Replace(Environment.NewLine, "<BR />")
                   .Replace("/*", string.Concat("<BR />", "<FONT COLOR=\"DarkGreen\">", "/", new string('*', 90), "<BR />"))
                   .Replace("*/", string.Concat("<BR />", new string('*', 90), "/</FONT><BR />"))
                   // I'm going to place the Json in a DIV.
                   .Replace("{", string.Concat("<BR />", "<B>", "Formatted JSON string:", "</B>", "<BR />", "<DIV STYLE=\"background: #d3d3d3; width: 95%; height: 60%; overflow: scroll;\">", "<B>", "{", "</B>", "<BR />"))
                   .Replace("}", string.Concat("<BR />", "<B>", "}", "</B>", "</DIV>", "<BR />"))
                   // Get rid of extra <BR /> tags.
                   .Replace("<BR /><BR />", "<BR />")
                   // Indenting:
                   .Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
                   .Replace("||[", "<B>{</B>")
                   .Replace("]||", "<B>}</B>")
                   .Trim());
        }
        string DataReaderToJson(SqlDataReader rdr, string tokenData, bool closeReader)
        {
            string returnValue = string.Empty;
            string schema      = string.Empty;

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

                using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                {
                    int  totalRecords = -1;
                    bool msgSuccess   = true;
                    jsonWriter.Formatting           = Formatting.Indented;
                    jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Local;

                    jsonWriter.WriteStartObject();
                    jsonWriter.WritePropertyName(RESULT);

                    jsonWriter.WriteStartArray();

                    for (int i = 0; i < rdr.FieldCount; i++)
                    {
                        schema = string.Concat(schema, rdr.GetName(i), " - ", rdr.GetFieldType(i), Environment.NewLine);
                    }

                    while (rdr.Read())
                    {
                        jsonWriter.WriteStartObject();

                        int fields = rdr.FieldCount;

                        for (int i = 0; i < fields; i++)
                        {
                            string colName = rdr.GetName(i);
                            if (colName.Equals(RECORDS_TOTAL) && totalRecords.Equals(-1))
                            {
                                totalRecords = Convert.ToInt32(rdr.GetInt32(i));
                                continue;
                            }
                            if (colName.Equals(RECORDS_TOTAL) && !totalRecords.Equals(-1))
                            {
                                continue;
                            }
                            jsonWriter.WritePropertyName(rdr.GetName(i));
                            if (rdr.IsDBNull(i))
                            {
                                jsonWriter.WriteNull();
                                continue;
                            }

                            try
                            {
                                if (rdr.GetFieldType(i) == typeof(int))
                                {
                                    jsonWriter.WriteValue(rdr.GetInt32(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(string))
                                {
                                    jsonWriter.WriteValue(rdr.GetString(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(double))
                                {
                                    jsonWriter.WriteValue(rdr.GetDouble(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(decimal))
                                {
                                    jsonWriter.WriteValue(rdr.GetDecimal(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(long))
                                {
                                    jsonWriter.WriteValue(rdr.GetInt64(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(DateTime))
                                {
                                    jsonWriter.WriteValue(rdr.GetDateTime(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(byte))
                                {
                                    jsonWriter.WriteValue(rdr.GetByte(i));
                                }
                                else if (rdr.GetFieldType(i) == typeof(short))
                                {
                                    jsonWriter.WriteValue(rdr.GetInt16(i));
                                }
                                else
                                {
                                    jsonWriter.WriteValue(rdr[i]);
                                }
                            }
                            catch (Exception ex)
                            {
                                jsonWriter.WriteComment(colName);
                                jsonWriter.WriteComment(ex.Message);
                                jsonWriter.WriteComment(ex.StackTrace);
                                jsonWriter.WriteValue("");
                            }
                        }
                        jsonWriter.WriteEndObject();
                    }

                    jsonWriter.WriteEndArray();

                    if (!string.IsNullOrEmpty(tokenData))
                    {
                        jsonWriter.WritePropertyName(TOKEN_DATA);
                        jsonWriter.WriteStartObject();

                        jsonWriter.WritePropertyName("Logon");
                        jsonWriter.WriteValue(string.Empty);

                        jsonWriter.WritePropertyName("Nome");
                        jsonWriter.WriteValue(string.Empty);

                        jsonWriter.WritePropertyName("Dominio");
                        jsonWriter.WriteValue(string.Empty);

                        jsonWriter.WritePropertyName("DataHora");
                        jsonWriter.WriteValue(DateTime.Now);

                        jsonWriter.WriteEndObject();
                    }
                    jsonWriter.WritePropertyName(RECORDS_TOTAL);
                    jsonWriter.WriteValue(totalRecords);
                    jsonWriter.WritePropertyName(SUCCESS);
                    jsonWriter.WriteValue(true);
                    jsonWriter.WriteEndObject();
                }
                returnValue = sb.ToString();
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);
                using (JsonWriter jsonWriter = new JsonTextWriter(sw))
                {
                    jsonWriter.WriteStartObject();
                    jsonWriter.WriteComment(ex.Message);
                    jsonWriter.WriteComment(Environment.NewLine);
                    jsonWriter.WriteComment(schema);
                    jsonWriter.WriteComment(Environment.NewLine);
                    jsonWriter.WriteComment(ex.StackTrace);
                    jsonWriter.WriteEndObject();
                }
                returnValue = sb.ToString();
            }
            finally
            {
                if (rdr != null && closeReader)
                {
                    if (!rdr.IsClosed)
                    {
                        rdr.Close();
                    }
                    rdr.Dispose();
                }
            }
            return(returnValue);
        }