示例#1
0
 public void FixValuesTest()
 {
     JSONParameters target = new JSONParameters(); // TODO: Initialize to an appropriate value
     target.EnableAnonymousTypes = true;
     target.IgnoreCaseOnDeserialize = false;
     target.UseExtensions = true;
     target.FixValues();
     Assert.IsTrue(target.UsingGlobalTypes);
     target.UseExtensions = false;
     target.FixValues();
     Assert.IsFalse(target.UsingGlobalTypes);
     
 }
示例#2
0
        internal Getters[] GetGetters(Type type, JSONParameters param)
        {
            Getters[] val = null;
            if (_getterscache.TryGetValue(type, out val))
                return val;

            PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            List<Getters> getters = new List<Getters>();
            foreach (PropertyInfo p in props)
            {
                if (!p.CanWrite && param.ShowReadOnlyProperties == false) continue;
                if (param.IgnoreAttributes != null)
                {
                    bool found = false;
                    foreach (var ignoreAttr in param.IgnoreAttributes)
                    {
                        if (p.IsDefined(ignoreAttr, false))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                        continue;
                }
                GenericGetter g = CreateGetMethod(type, p);
                if (g != null)
                    getters.Add(new Getters { Getter = g, Name = p.Name });
            }

            FieldInfo[] fi = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
            foreach (var f in fi)
            {
                if (param.IgnoreAttributes != null)
                {
                    bool found = false;
                    foreach (var ignoreAttr in param.IgnoreAttributes)
                    {
                        if (f.IsDefined(ignoreAttr, false))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                        continue;
                }

                GenericGetter g = CreateGetField(type, f);
                if (g != null)
                    getters.Add(new Getters { Getter = g, Name = f.Name });
            }
            val = getters.ToArray();
            _getterscache.Add(type, val);
            return val;
        }
示例#3
0
 internal JSONSerializer(JSONParameters param)
 {
     _params = param;
     _useEscapedUnicode = _params.UseEscapedUnicode;
     _MAX_DEPTH = _params.SerializerMaxDepth;
 }
示例#4
0
 internal JSONSerializer(JSONParameters param)
 {
     _params = param;
     _useEscapedUnicode = _params.UseEscapedUnicode;
 }
示例#5
0
        public void ConvertToJSONTest()
        {
            JSONParameters param = new JSONParameters();
            param.UseExtensions = true;
            //param.UsingGlobalTypes = false;
            JSONSerializer target = new JSONSerializer(param);
            TestClass tc = new TestClass() { T1 = "4", t2 = 3 };
            string expected = "{\"$types\":{\"Arch.CFramework.AppInternals.Test.TestClass, Arch.CFramework.AppInternals.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\":\"1\"},\"$type\":\"1\",\"T1\":\"4\",\"t2\":3}";//
            string actual;
            actual = target.ConvertToJSON(tc);
            Assert.AreEqual(expected, actual);
            param.UseExtensions = false;
            param.FixValues();
            target = new JSONSerializer(param);
            expected = "{\"T1\":\"4\",\"t2\":3}";
            actual = target.ConvertToJSON(tc);
            Assert.AreEqual(expected, actual);
            param.UseExtensions = true;
            param.UsingGlobalTypes = true;
            target = new JSONSerializer(param);
            TestClass2 tc2 = new TestClass2() { T1 = GetDataTable(), t2 = new DataSet(), T3 = new Dictionary<string, string>(), t4 = DateTime.Parse("2013-02-20 06:42:39Z"), t5 = new List<string>(), t6 = new Guid(), t7 = TEnum.A };
            tc2.t2.Tables.Add(tc2.T1);
            tc2.T3.Add("a", "a1");
            tc2.T3.Add("b", "b1");
            tc2.t5.Add("aa");
            tc2.t5.Add("bb");
            actual = target.ConvertToJSON(tc2);
            
            Assert.AreEqual("{\"$types\":{\"Arch.CFramework.AppInternals.Test.TestClass2, Arch.CFramework.AppInternals.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\":\"1\",\"Arch.CFramework.AppInternals.Serialization.JSONSerialize.DatasetSchema, Arch.CFramework.AppInternals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\":\"2\"},\"$type\":\"1\",\"T1\":{\"$schema\":{\"$type\":\"2\",\"Info\":[\"test\",\"t1\",\"System.Int32\",\"test\",\"t2\",\"System.Int32\",\"test\",\"t3\",\"System.Int32\"],\"Name\":\"test\"},\"test\":[[0,1,2]]},\"t2\":{\"$schema\":{\"$type\":\"2\",\"Info\":[\"test\",\"t1\",\"System.Int32\",\"test\",\"t2\",\"System.Int32\",\"test\",\"t3\",\"System.Int32\"],\"Name\":\"NewDataSet\"},\"test\":[[0,1,2]]},\"T3\":{\"a\":\"a1\",\"b\":\"b1\"},\"t7\":\"A\",\"t6\":\"AAAAAAAAAAAAAAAAAAAAAA==\",\"t4\":\"2013-02-20 06:42:39Z\",\"t5\":[\"aa\",\"bb\"]}"
                , actual);

        }
示例#6
0
 public void JSONSerializerConstructorTest()
 {
     JSONParameters param = new JSONParameters(); // TODO: Initialize to an appropriate value
     JSONSerializer target = new JSONSerializer(param);
     Assert.IsNotNull(target);
 }
示例#7
0
 static ASettings()
 {
     JsonParameters = new JSONParameters { UseEscapedUnicode = false, UseFastGuid = false, UseExtensions = false };
 }
示例#8
0
 public void JSONParametersConstructorTest()
 {
     JSONParameters target = new JSONParameters();
     Assert.IsNotNull(target);
 }
示例#9
0
 /// <summary>
 /// 把对象转换为JSON字符串。
 /// </summary>
 public static string ObjectToJson(object obj, JSONParameters newjp)
 {
     return(JSON.ToJSON(obj, newjp));
 }
示例#10
0
        private void SaveToFile()
        {
            string projectFileName = Path.Combine(ProjectPath, ProjectFileName);

            // Serialize JSON data
            var configFile = new ConfigFile
            {
                ProjectName           = Name,
                KeepUnminifiedFiles   = KeepUnminifiedFiles,
                KeepIntermediaryFiles = KeepIntermediaryFiles
            };

            configFile.Files.AddRange(Files.Select(f => new ConfigFile.File {
                Name = f.FilePath.Replace('\\', '/')
            }));

            string json;

            try
            {
                var jsonParams = new JSONParameters
                {
                    FormatterIndentSpaces     = 2,
                    SerializeToCamelCaseNames = true,
                    UsingGlobalTypes          = false,
                    UseExtensions             = false,
                    UseEscapedUnicode         = false
                };
                json = JSON.ToNiceJSON(configFile, jsonParams);
                json = json.TrimEnd() + Environment.NewLine;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error serializing config file: {ex.Message}", App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // Create backup of existing file
            try
            {
                if (File.Exists(projectFileName))
                {
                    File.Copy(projectFileName, projectFileName + ".bak", true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error backing up config file: {ex.Message}", App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // Write new config file
            try
            {
                File.WriteAllText(projectFileName, json);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error writing config file (backup created): {ex.Message}", App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // Delete backup file
            try
            {
                File.Delete(projectFileName + ".bak");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error deleting backup config file: {ex.Message}", App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }

            //try
            //{
            //	if (File.Exists(projectFileName))
            //	{
            //		File.Copy(projectFileName, projectFileName + ".bak");
            //	}
            //	using (var writer = new StreamWriter(projectFileName))
            //	{
            //		writer.WriteLine("MiniWebCompiler v1");
            //		writer.WriteLine(Name);
            //		foreach (var file in Files)
            //		{
            //			writer.WriteLine(file.FilePath);
            //		}
            //	}
            //	if (File.Exists(projectFileName + ".bak"))
            //	{
            //		File.Delete(projectFileName + ".bak");
            //	}
            //}
            //catch (Exception ex)
            //{
            //	MessageBox.Show("The project file \"" + projectFileName + "\" could not be saved. " + ex.Message, App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            //}
        }
示例#11
0
        private void LoadFromFile()
        {
            string projectFileName = Path.Combine(ProjectPath, ProjectFileName);

            try
            {
                KeepUnminifiedFiles = App.Settings.KeepUnminifiedFilesDefault;

                if (File.Exists(projectFileName))
                {
                    Name = "";
                    Files.Clear();

                    string json;
                    try
                    {
                        json = File.ReadAllText(projectFileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Error reading config file: {ex.Message}", App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    if (json.StartsWith("MiniWebCompiler v1"))
                    {
                        int index = 0;
                        using (var reader = new StreamReader(projectFileName))
                        {
                            while (!reader.EndOfStream)
                            {
                                string line = reader.ReadLine().Trim();
                                index++;
                                if (index == 1)
                                {
                                    if (line != "MiniWebCompiler v1")
                                    {
                                        return;
                                    }
                                }
                                else if (index == 2)
                                {
                                    Name = line;
                                }
                                else
                                {
                                    var file = new ProjectFile(this)
                                    {
                                        FilePath = line
                                    };
                                    Files.Add(file);
                                    file.PropertyChanged += File_PropertyChanged;
                                }
                            }
                        }

                        // Save file in new format now
                        SaveToFile();
                    }
                    else
                    {
                        try
                        {
                            var jsonParams = new JSONParameters
                            {
                                AllowNonQuotedKeys = true,
                                UsingGlobalTypes   = false,
                                UseExtensions      = false
                            };
                            var configFile = JSON.ToObject <ConfigFile>(json, jsonParams);
                            Name = configFile.ProjectName;
                            KeepUnminifiedFiles   = configFile.KeepUnminifiedFiles;
                            KeepIntermediaryFiles = configFile.KeepIntermediaryFiles;
                            foreach (var fileEntry in configFile.Files)
                            {
                                var file = new ProjectFile(this)
                                {
                                    FilePath = fileEntry.Name.Replace('/', Path.DirectorySeparatorChar)
                                };
                                Files.Add(file);
                                file.PropertyChanged += File_PropertyChanged;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Error parsing config file: {ex.Message}", App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The project file \"" + projectFileName + "\" could not be loaded. " + ex.Message, App.Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }