예제 #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Spider v0.1");
            Console.WriteLine("Written by Mason Meirs on a shitty 2020 summer evening whilst on the phone with Kallie");
            if (!File.Exists("sconfig.yml"))
            {
                var serializer = new YamlDotNet.Serialization.Serializer();
                using (TextWriter wrt = File.CreateText("sconfig.yml"))
                {
                    serializer.Serialize(wrt, new
                    {
                        port      = "80",
                        startPage = "index.html",
                        prefix    = "http://localhost/"
                    });
                }
            }
            else
            {
                string config       = File.ReadAllText(Directory.GetCurrentDirectory() + @"\sconfig.yml");
                var    deserializer = new YamlDotNet.Serialization.Deserializer();
                var    dict         = deserializer.Deserialize <Dictionary <string, string> >(config);
                port   = int.Parse(dict["port"]);
                prefix = dict["prefix"];
            }
            Console.WriteLine("Init sequence complete...");
            Spider spd = new Spider();

            spd.StartServer(port, prefix);
        }
예제 #2
0
        public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache)
        {
            var cacheDir = PrepareCacheDirectory(gitPreparer);
            var cacheFileName = GetCacheFileName(cacheKey, cacheDir);

            variablesFromCache.FileName = cacheFileName;

            Dictionary<string, string> dictionary;
            using (Logger.IndentLog("Creating dictionary"))
            {
                dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
            }

            Action writeCacheOperation = () =>
            {
                using (var stream = fileSystem.OpenWrite(cacheFileName))
                {
                    using (var sw = new StreamWriter(stream))
                    {
                        using (Logger.IndentLog("Storing version variables to cache file " + cacheFileName))
                        {
                            var serializer = new Serializer();
                            serializer.Serialize(sw, dictionary);
                        }
                    }
                }
            };

            var retryOperation = new OperationWithExponentialBackoff<IOException>(new ThreadSleep(), writeCacheOperation, maxRetries: 6);
            retryOperation.Execute();
        }
예제 #3
0
 public static string ToString(object o)
 {
     var stringBuilder = new StringBuilder();
     var serializer = new Serializer();
     serializer.Serialize(new IndentedTextWriter(new StringWriter(stringBuilder)), o);
     return stringBuilder.ToString();
 }
        private void OnBtnTest1(object sender, RoutedEventArgs e)
        {
            //バージョンアップでクラスに変更が入った場合、古いバージョンの文字列を新しいバージョンのクラスへデシリアライズできるかどうかの実験。
            //YamlDotNet Ver.6.1.2 + .NET Framework 4.7.2を使用。
            //変数の追加:デシリアライズ成功。追加された変数は、defaultではなくコンストラクタで代入された値となった
            //変数の削除:デシリアライズ失敗。同名の変数が必ず存在している必要があるため、不要になった変数であっても、過去バージョンとの互換のために残しておく必要がある。プレフィックスobsolete_を付けた変数名を用意し、YamlMemberのAliasで過去バージョンの名前を指定することで、不要な変数を分かりやすく分類することはできた。
            //変数の削除 応用:IgnoreUnmatchedProperties()を使用する事で、削除された(存在しない)値を無視する動作にすることができた。互換が取りやすくなる。ドキュメントは無いが、ソースコードおよびWebの情報から存在を確認した。
            //  コード上のコメント:>Determines if an exception or null should be returned if name can't be found in type
            //  Web情報:https://stackoverflow.com/questions/44470352/yamldotnet-need-deserializer-to-ignore-extra
            // リストの読み込み:読み込み対象のリストにデフォルト値がある場合、上書きされる(デフォルト値は消える)。直観通りの動作。(ちなみにJSON.NETの場合、デフォルト値に加えて読み込んだ値が追加されるという動きになる)

            var v1 = new Datav1
            {
                child = new Datav1Child()
                {
                    dataChild1 = 2
                },
                data1 = 3,
                data2 = new List <string> {
                    "1", "2"
                }
            };

            var serializer = new YamlDotNet.Serialization.Serializer();

            var v1str = serializer.Serialize(v1);

            var deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().Build();


            var v2 = deserializer.Deserialize <Datav2>(v1str);

            MessageBox.Show($"{nameof(v2.data3)}={v2.data3},{nameof(v2.child2.dataChild1)}={v2.child2?.dataChild1},{nameof(v2.data2)}={string.Join(",", v2.data2)}");
        }
        public static void SerializeClangTidyFile(ClangTidyProperties Props, string ClangTidyFilePath)
        {
            List<string> CommandList = new List<string>();
            SerializeCheckTree(CommandList, Props.GetCheckTree(), TreeLevelOp.Inherit);

            CommandList.Sort((x, y) =>
            {
                bool LeftSub = x.StartsWith("-");
                bool RightSub = y.StartsWith("-");
                if (LeftSub && !RightSub)
                    return -1;
                if (RightSub && !LeftSub)
                    return 1;
                return StringComparer.CurrentCulture.Compare(x, y);
            });

            string ConfigFile = Path.Combine(ClangTidyFilePath, ".clang-tidy");
            using (StreamWriter Writer = new StreamWriter(ConfigFile))
            {
                Serializer S = new Serializer(namingConvention: new PascalCaseNamingConvention());
                ClangTidyYaml Yaml = new ClangTidyYaml();
                Yaml.Checks = String.Join(",", CommandList.ToArray());
                S.Serialize(Writer, Yaml);
            }
        }
예제 #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GameSystem" /> class.
 /// </summary>
 /// <param name="game">The game.</param>
 public YamlManager(Game game) : base(game)
 {
     Services.AddService(this);
     yamlSettings = new SerializerSettings();
     attributeRegistry = yamlSettings.Attributes;
     serializer = new Serializer(yamlSettings);
 }
예제 #7
0
        static void Main(string[] args)
        {
            var sourceList = new Item[10000];
            for (int i = 0; i < sourceList.Length; i++)
            {
                sourceList[i] = new Item { IntValue = i, StringValue = i.ToString() };
            }
            var mySerializer = new YamlSerializer();
            var myDeserializer = new YamlDeserializer();
            var defaultSerializer = new Serializer();
            var defaultDeserializer = new Deserializer();
            var watch = new Stopwatch();

            while (true)
            {
                var sw = new StringWriter();
                watch.Restart();
                mySerializer.Serialize(sw, sourceList);
                var stime = watch.ElapsedMilliseconds;
                watch.Restart();
                var list = myDeserializer.Deserialize<List<Item>>(new StringReader(sw.ToString()));
                var dtime = watch.ElapsedMilliseconds;
                Console.WriteLine("My - Serialize time: {0}ms, Deserialize time: {1}ms", stime, dtime);

                sw = new StringWriter();
                watch.Restart();
                defaultSerializer.Serialize(sw, sourceList);
                stime = watch.ElapsedMilliseconds;
                watch.Restart();
                list = defaultDeserializer.Deserialize<List<Item>>(new StringReader(sw.ToString()));
                dtime = watch.ElapsedMilliseconds;
                Console.WriteLine("Default - Serialize time: {0}ms, Deserialize time: {1}ms", stime, dtime);
            }
        }
        /// <summary>
        ///     Dumps the input object retrieving al the properties and
        ///     the current value.
        /// </summary>
        /// <param name="value">The object to dump.</param>
        /// <returns></returns>
        public string Dump(object value)
        {
            var stringBuilder = new StringBuilder();
            var serializer = new Serializer();
            var stringWriter = new StringWriter(stringBuilder, CultureInfo.CurrentCulture);
            serializer.Serialize(new IndentedTextWriter(stringWriter), value);

            return stringBuilder.ToString();
        }
예제 #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var serializer = new Serializer();
            var writer = new StringWriter();

            // Additional Ip subnets
            var addSubnets = osm.ListSubnets()
                .Where<Subnet>(s => s.IpVersion == 4 && s.Name.StartsWith("add"));
            foreach (var s in addSubnets)
            {
                writer.Write("===================================\n");
                var subnet = osm.GetSubnet(s.Id);
                serializer.Serialize(writer, subnet);
            }

            ltAddSubnets.Text = writer.ToString();
            writer.GetStringBuilder().Clear();

            // Local Network subnets
            var localSubnets = osm.ListSubnets()
                .Where<Subnet>(s => s.IpVersion == 4 && s.Name.StartsWith("local-"));

            foreach (var s in localSubnets)
            {
                writer.Write("===================================\n");
                var subnet = osm.GetSubnet(s.Id);
                serializer.Serialize(writer, subnet);
            }

            ltLocalSubnets.Text = writer.ToString();
            writer.GetStringBuilder().Clear();

            // Ports
            var ports = osm.ListPorts();
            foreach (var p in ports)
            {
                writer.Write("===================================\n");
                var subnet = osm.GetPort(p.Id);
                serializer.Serialize(writer, subnet);
            }

            ltPorts.Text = writer.ToString();
            writer.GetStringBuilder().Clear();

            // Security Groups
            var groups = osm.ListNetworkSecurityGroups();
            foreach (var g in groups)
            {
                writer.Write("===================================\n");
                var group = osm.GetNetworkSecurityGroup(g.Id);
                serializer.Serialize(writer, group);
            }

            ltSecurityGroups.Text = writer.ToString();
            writer.GetStringBuilder().Clear();

        }
예제 #10
0
파일: Class1.cs 프로젝트: sgqy/PlatformTest
        public string transmiss(Data[] d)
        {
            var tw = new System.IO.StringWriter();

            var ser = new Serializer();
            ser.Serialize(tw, d.Select(x => new { x.id, x.src, x.dst }));

            return tw.ToString();
        }
예제 #11
0
 public static void WriteControls(string cfgPath)
 {
     var s = new Serializer(SerializationOptions.EmitDefaults);
     var graph = InputMaster.controls.Where(c => c.scope != Scope.EditorOnly).Select(c => c.GetSimpleDataView()).ToArray();
     using(var writer = new StreamWriter(cfgPath)) {
         writer.AutoFlush = true;
         s.Serialize(writer, graph);
     }
 }
예제 #12
0
		public void Save(string path)
		{
			var data = new YamlData();
			data.Config = GenerationSettings;
			data.Export = ExportPath;
			data.Meshes = InputMeshes;

			var serializer = new Serializer(SerializationOptions.None, new HyphenatedNamingConvention());
			using (StreamWriter writer = new StreamWriter(path))
				serializer.Serialize(writer, data);
		}
예제 #13
0
    public override string Serialize <T>(T obj)
    {
        Serializer serializer = new YamlDotNet.Serialization.Serializer();

        using (var r = new StringWriter())
        {
            var s = Environment.TickCount;
            serializer.Serialize(r, obj);
            SerializeTimeList.Add(Environment.TickCount - s);
            return(r.GetStringBuilder().ToString());
        }
    }
예제 #14
0
    private string CreateFrontMatter(Dictionary <string, object> data = null)
    {
        var stringBuilder = new StringBuilder();

        stringBuilder.AppendLine("---");
        if (data != null)
        {
            var raw = new YamlDotNet.Serialization.Serializer().Serialize(data);
            stringBuilder.Append(raw);
        }
        stringBuilder.AppendLine("---");
        return(stringBuilder.ToString());
    }
예제 #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var serializer = new Serializer(SerializationOptions.DefaultToStaticType); // to ignore reference type lit System.Net.IpAddres
            var writer = new StringWriter();

            // DbService
            IEnumerable<CloudImage> images = null;
            try
            {
                images = osm.ListGlanceImages();
                if (images.Count() == 0)
                {
                    ltSummary.Text = "no Image.";
                }
                else
                {
                    var sb = new StringBuilder();
                    sb.Append(images.Count() + " Images.\n");
                    sb.Append(images.Where(i => i.Visibility == "public").Count() + " public images\n");
                    sb.Append(images.Where(i => i.Visibility == "private").Count() + " private images\n");

                    ltSummary.Text = sb.ToString();

                    foreach (var i in images.Where(i => i.Visibility == "private"))
                    {
                        writer.Write("===================================\n");
                        var image = osm.GetGlanceImage(i.Id);
                        serializer.Serialize(writer, image);

                        var extensiondata = image.ExtensionData;
                        writer.Write("--ExtensionData--\n");
                        foreach (var key in extensiondata.Keys)
                        {
                            writer.Write(String.Format("{0} : {1}\n", key, extensiondata[key] == null ? "null" : extensiondata[key].ToString()));
                        }

                    }
                    ltImages.Text = writer.ToString();
                }
            }
            catch (ResponseException re)
            {
                if (re.Response.StatusCode == System.Net.HttpStatusCode.Forbidden)
                    ltImages.Text = re.Response.RawBody;
            }
            finally
            {
                writer.GetStringBuilder().Clear();
            }

        }
예제 #16
0
    public static string CollectGenerationRulesToYAML(List <GenerationRules> generationRules)
    {
        OrderedDictionary rules = new OrderedDictionary();

        rules.Add("Delimiter", String.Format("r_bracket{0}r_bracket", generationRules[0].delimiter));
        rules.Add("Separator", String.Format("r_bracket{0}r_bracket", generationRules[0].separator));
        rules.Add("StartDrawMatrixAtLine", String.Format("r_bracket{0}r_bracket", generationRules[0].matrixAtLine));
        rules.Add("NotationRules", generationRules[0].notation);
        rules.Add("Type", String.Format("r_bracket{0}r_bracket", "square"));
        object a          = rules;
        var    serializer = new YamlDotNet.Serialization.Serializer();

        return(serializer.Serialize(a));
    }
예제 #17
0
        /// <summary>
        /// Convert a JSON string document to YAML
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string JsonToYaml(string source)
        {
            var expConverter = new ExpandoObjectConverter();
            var serializer   = new YamlDotNet.Serialization.Serializer();

            object data = Newtonsoft.Json.JsonConvert.DeserializeObject <ExpandoObject>(source, expConverter);

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, data);
                var yaml = writer.ToString();
                return(yaml);
            }
        }
예제 #18
0
        private object[] DisplayEventAndLogInformation(EventLogReader logReader)
        {
            ArrayList eventlog_json_arraylist = new ArrayList();

            for (EventRecord eventInstance = logReader.ReadEvent();
                 null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                string eventlog_json = JsonConvert.SerializeObject(eventInstance);
                eventlog_json_arraylist.Add(eventlog_json);

                var    serializer = new YamlSerializer();
                String yaml       = serializer.Serialize(eventInstance);

                var serializer2 = new YamlDotNet.Serialization.Serializer();
                serializer2.Serialize(System.Console.Out, eventInstance);
                if (Verbose)
                {
                    Console.WriteLine("-----------------------------------------------------");
                    Console.WriteLine("Event ID: {0}", eventInstance.Id);
                    Console.WriteLine("Level: {0}", eventInstance.Level);
                    Console.WriteLine("LevelDisplayName: {0}", eventInstance.LevelDisplayName);
                    Console.WriteLine("Opcode: {0}", eventInstance.Opcode);
                    Console.WriteLine("OpcodeDisplayName: {0}", eventInstance.OpcodeDisplayName);
                    Console.WriteLine("TimeCreated: {0}", eventInstance.TimeCreated);
                    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                }
                try
                {
                    if (Verbose)
                    {
                        Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                    }
                }
                catch (EventLogException)
                {
                    // The event description contains parameters, and no parameters were
                    // passed to the FormatDescription method, so an exception is thrown.
                }
                // Cast the EventRecord object as an EventLogRecord object to
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                if (Verbose)
                {
                    Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
                }
            }
            object[] result = eventlog_json_arraylist.ToArray();
            return(result);
        }
예제 #19
0
        public string JsonToYaml(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return(string.Empty);
            }

            var     expConverter       = new ExpandoObjectConverter();
            dynamic deserializedObject = JsonConvert.DeserializeObject <ExpandoObject>(source, expConverter);

            var    serializer = new YamlDotNet.Serialization.Serializer();
            string yaml       = serializer.Serialize(deserializedObject);

            return(yaml);
        }
예제 #20
0
        private object[] DisplayEventAndLogInformation(EventLogReader logReader)
        {
            ArrayList eventlog_json_arraylist = new ArrayList();
            for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                string eventlog_json = JsonConvert.SerializeObject(eventInstance);
                eventlog_json_arraylist.Add(eventlog_json);

                var serializer = new YamlSerializer();
                String yaml = serializer.Serialize(eventInstance);

                var serializer2 = new YamlDotNet.Serialization.Serializer();
                serializer2.Serialize(System.Console.Out, eventInstance);
                if (Verbose)
                {
                    Console.WriteLine("-----------------------------------------------------");
                    Console.WriteLine("Event ID: {0}", eventInstance.Id);
                    Console.WriteLine("Level: {0}", eventInstance.Level);
                    Console.WriteLine("LevelDisplayName: {0}", eventInstance.LevelDisplayName);
                    Console.WriteLine("Opcode: {0}", eventInstance.Opcode);
                    Console.WriteLine("OpcodeDisplayName: {0}", eventInstance.OpcodeDisplayName);
                    Console.WriteLine("TimeCreated: {0}", eventInstance.TimeCreated);
                    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                }
                try
                {
                    if (Verbose)
                    {
                        Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                    }
                }
                catch (EventLogException)
                {
                    // The event description contains parameters, and no parameters were 
                    // passed to the FormatDescription method, so an exception is thrown.
                }
                // Cast the EventRecord object as an EventLogRecord object to 
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                if (Verbose)
                {
                    Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
                }
            }
            object[] result = eventlog_json_arraylist.ToArray();
            return result;
        }
예제 #21
0
        public static string MakeYamlString( object obj, SerializationOptions options = SerializationOptions.None )
        {
            var serializer = new Serializer( options );
            var sw = new StringWriter();

            serializer.Serialize( sw, obj );

            return sw
                .ToString()
                .UnescapeSlashes()
                .Replace( "\r", "" )
                .Replace( "\n\n", "\n" )
                .Replace( ": >-\n", ":\n" )
                .Replace( ": >\n", ":\n" )
                ;
        }
예제 #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var serializer = new Serializer(SerializationOptions.DefaultToStaticType); // to ignore reference type lit System.Net.IpAddres
            var writer = new StringWriter();


            // volue
            IEnumerable<Volume> volumes = null;
            try
            {
                volumes = osm.ListVolumes();
                if (volumes.Count() == 0)
                {
                    ltSummary.Text = "no volume.";
                }
                else
                {
                    ltSummary.Text = volumes.Count() + " volumes.";

                    foreach (var v in volumes)
                    {
                        writer.Write("===================================\n");
                        var volume = osm.GetVolume(v.Id);
                        serializer.Serialize(writer, volume);

                        var extensiondata = volume.ExtensionData;
                        writer.Write("--ExtensionData--\n");
                        foreach (var key in extensiondata.Keys)
                        {
                            writer.Write(String.Format("{0} : {1}\n", key, extensiondata[key] == null ? "null" : extensiondata[key].ToString()));
                        }

                    }
                    ltVolumes.Text = writer.ToString();
                }
            }
            catch (ResponseException re)
            {
                if (re.Response.StatusCode == System.Net.HttpStatusCode.Forbidden)
                    ltVolumes.Text = re.Response.RawBody;
            }
            finally
            {
                writer.GetStringBuilder().Clear();
            }

        }
        /// <summary>
        /// Save all Settings.
        /// </summary>
        public void Save()
        {
            try
            {
                using (FileStream FileStream = new FileStream($"{Directory.ApplicationDirectory}\\ApplicationSetting.yml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                {
                    using (StreamWriter Writer = new StreamWriter(FileStream, Encoding.UTF8))
                    {
                        Serializer Serializer = new Serializer();
                        Serializer.Serialize(Writer, Core.Setting);
                    }
                }

                Core.Logger.Log("Setting saved.", Pokemon_3D_Server_Core.Logger.LogTypes.Info);
            }
            catch (Exception ex) { ex.CatchError(); }
        }
예제 #24
0
        public static string Json2Yaml(string json)
        {
            try {
                var swaggerDocument = ConvertJTokenToObject(JsonConvert.DeserializeObject <JToken>(json));

                var serializer = new YamlDotNet.Serialization.Serializer();

                using (var writer = new StringWriter()) {
                    serializer.Serialize(writer, swaggerDocument);
                    var yaml = writer.ToString();
                    return(yaml);
                }
            }
            catch (Exception e) {
                return(e.ToString());
            }
        }
        public void Run(string[] args)
        {
            var address = new
            {
                street = "123 Tornado Alley\nSuite 16",
                city = "East Westville",
                state = "KS"
            };

            var receipt = new
            {
                receipt = "Oz-Ware Purchase Invoice",
                date = new DateTime(2007, 8, 6),
                customer = new
                {
                    given = "Dorothy",
                    family = "Gale"
                },
                items = new[]
                {
                    new
                    {
                        part_no = "A4786",
                        descrip = "Water Bucket (Filled)",
                        price = 1.47M,
                        quantity = 4
                    },
                    new
                    {
                        part_no = "E1628",
                        descrip = "High Heeled \"Ruby\" Slippers",
                        price = 100.27M,
                        quantity = 1
                    }
                },
                bill_to = address,
                ship_to = address,
                specialDelivery = "Follow the Yellow Brick\n" +
                                  "Road to the Emerald City.\n" +
                                  "Pay no attention to the\n" +
                                  "man behind the curtain."
            };

            var serializer = new Serializer();
            serializer.Serialize(Console.Out, receipt);
        }
예제 #26
0
    private void InitMetaData()
    {
        var       rootText  = Resources.Load <TextAsset>("meta/root" + SceneManager.GetActiveScene().name);
        var       docStream = new StringReader(rootText.text);
        RootGraph root      = RootGraph.Construct(docStream);

        foreach (var clip in root.Clips)
        {
            //load clip
            var      clipText      = Resources.Load <TextAsset>("meta/" + clip.Path);
            var      clipDocStream = new StringReader(clipText.text);
            ClipTree clipGraph     = ClipTree.Construct(clipDocStream);
            var      ser           = new YamlDotNet.Serialization.Serializer();

            clipGraphs.Add(clip.Name, clipGraph);
            var midiFile = Resources.Load <TextAsset>("clips/" + clipGraph.Midi);
            Debug.Log(clipGraph.Midi);

            AudioSource audioSource = AddAudioSourceToScene(clipGraph.Audio);

            //parse midi
            Midi midi = new MidiParser().Parse(midiFile.bytes);
            //debug
            Debug.Log(midi.Tracks[2].Bpm);
            foreach (var msg in midi.Tracks[2].Messages)
            {
                Debug.Log(msg);
            }
            Debug.Log(ser.Serialize(clipGraph));
            clips.Add(clip.Name, new Assets.Core.Clip(audioSource, midi));
        }
        foreach (var graph in root.Scriptgraphs)
        {
            var graphText = Resources.Load <TextAsset>("meta/" + graph.Path);
            Debug.Log(graphText);
            var        graphDocStream = new StringReader(graphText.text);
            ScriptTree scriptGraph    = ScriptTree.Construct(graphDocStream);
            var        ser            = new YamlDotNet.Serialization.Serializer();

            scriptGraphs.Add(graph.Name, scriptGraph);
            Debug.Log("Constructed a script graph : " + graph.Name);
            Debug.Log(ser.Serialize(scriptGraph));
        }
    }
예제 #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var serializer = new Serializer(SerializationOptions.DefaultToStaticType); // to ignore reference type lit System.Net.IpAddres
            var writer = new StringWriter();

            // UserAccess
            var ua = osm.CreateUserAccess();
            writer.Write("===================================\n");
            serializer.Serialize(writer, osm.CreateUserAccess());

            var extensiondata = ua.ExtensionData;
            writer.Write("--ExtensionData--\n");
            foreach (string key in extensiondata.Keys)
            {
                writer.Write(String.Format("{0} : {1}\n", key, extensiondata[key] == null ? "null" : extensiondata[key].ToString()));
            }


            ltUserAccess.Text = writer.ToString();
            writer.GetStringBuilder().Clear();

            // Owner User
            var ownerUser = osm.ListTenantUsers(osm.TenantId).SingleOrDefault<User>(u => u.Username == this.UserName);
            writer.Write("===================================\n");
            serializer.Serialize(writer, ownerUser);

            if (ownerUser == null)
            {
                ltOwnerUser.Text = "no owner user";
            }
            else
            {
                extensiondata = ownerUser.ExtensionData;
                writer.Write("--ExtensionData--\n");
                foreach (string key in extensiondata.Keys)
                {
                    writer.Write(String.Format("{0} : {1}\n", key, extensiondata[key] == null ? "null" : extensiondata[key].ToString()));
                }
                ltOwnerUser.Text = writer.ToString();
                writer.GetStringBuilder().Clear();
            }

        }
예제 #28
0
    static void export()
    {
        AssetBundleInfo abi = new AssetBundleInfo();
        var             abs = AssetDatabase.GetAllAssetBundleNames();

        for (int i = 0; i < abs.Length; i++)
        {
            var files = AssetDatabase.GetAssetPathsFromAssetBundle(abs[i]);
            abi.AssetBundles[abs[i]] = files;
            foreach (var f in files)
            {
                Debug.Log(abs[i] + ":" + f);
            }
        }
        var    writer = new YamlDotNet.Serialization.Serializer();
        string str    = writer.Serialize(abi);

        Debug.Log(str);
        File.WriteAllText(getconfpath(), str);
    }
예제 #29
0
        public string ReadYaml()
        {
            fileYamlPath = @"config.yml";
            var read         = new StreamReader(fileYamlPath);
            var deserializer = new DeserializerBuilder().Build();
            var yamlObject   = deserializer.Deserialize(read);
            var buildToJson  = new SerializerBuilder()
                               .JsonCompatible()
                               .Build();

            var json       = buildToJson.Serialize(yamlObject);
            var reviseJson = json.Replace("-", "");
            var jsonToObj  = JsonConvert.DeserializeObject <ConfigLED>(reviseJson);
            var serializer = new YamlDotNet.Serialization.Serializer();

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, jsonToObj);
                var yaml = writer.ToString();
                getYaml = yaml;
            }
            return(getYaml);
        }
예제 #30
0
        public void WriteVariablesToDiskCache(IRepository repo, string gitDir, VersionVariables variablesFromCache)
        {
            var cacheFileName = GetCacheFileName(GetKey(repo, gitDir), GetCacheDir(gitDir));
            variablesFromCache.FileName = cacheFileName;

            using (var stream = fileSystem.OpenWrite(cacheFileName))
            {
                using (var sw = new StreamWriter(stream))
                {
                    Dictionary<string, string> dictionary;
                    using (Logger.IndentLog("Creating dictionary"))
                    {
                        dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value);
                    }

                    using (Logger.IndentLog("Storing version variables to cache file " + cacheFileName))
                    {
                        var serializer = new Serializer();
                        serializer.Serialize(sw, dictionary);
                    }
                }
            }
        }
예제 #31
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var serializer = new Serializer();
            var writer = new StringWriter();

            // DbService
            IEnumerable<Domain> domains = null;
            try
            {
                domains = osm.ListDomains();
                if (domains.Count() == 0)
                {
                    ltSummary.Text = "no domain service.";
                }
                else
                {
                    ltSummary.Text = domains.Count() + " domain(s)";

                    foreach (var domain in domains)
                    {
                        writer.Write("===================================\n");
                        serializer.Serialize(writer, domain);
                    }
                    ltDomains.Text = writer.ToString();
                }
            }
            catch (ResponseException re)
            {
                if (re.Response.StatusCode == System.Net.HttpStatusCode.Forbidden)
                    ltDomains.Text = "Forbidden";
            }
            finally
            {
                writer.GetStringBuilder().Clear();
            }

        }
예제 #32
0
 public static void SerializeCollection(List<KeysView> infos, TextWriter output)
 {
     Serializer serializer = new Serializer();
     serializer.Serialize(output, infos);
 }
예제 #33
0
        public void SerializaionUtilizeNamingConventions()
        {
            var convention = A.Fake<INamingConvention>();
            A.CallTo(() => convention.Apply(A<string>._)).ReturnsLazily((string x) => x);
            var obj = new NameConvention { FirstTest = "1", SecondTest = "2" };

            var serializer = new Serializer(namingConvention: convention);
            serializer.Serialize(new StringWriter(), obj);

            A.CallTo(() => convention.Apply("FirstTest")).MustHaveHappened();
            A.CallTo(() => convention.Apply("SecondTest")).MustHaveHappened();
        }
예제 #34
0
 private static void DumpAsYaml(TestCaseSession session)
 {
     var stringBuilder = new StringBuilder();
     var serializer = new Serializer();
     serializer.Serialize(new IndentedTextWriter(new StringWriter(stringBuilder)), session);
     Console.WriteLine(stringBuilder);
 }
예제 #35
0
        public void SerializeGenericDictionaryPropertyAndDoNotApplyNamingConvention()
        {
            var obj = new Dictionary<string, object>();
            obj["property_one"] = new GenericTestDictionary<string, object>();
            ((IDictionary<string, object>)obj["property_one"]).Add("new_key_here", "new_value");

            var mockNamingConvention = A.Fake<INamingConvention>();
            A.CallTo(() => mockNamingConvention.Apply(A<string>.Ignored)).Returns("xxx");

            var serializer = new Serializer(namingConvention: mockNamingConvention);
            var writer = new StringWriter();
            serializer.Serialize(writer, obj);

            writer.ToString().Should().Contain("new_key_here: new_value");
        }
예제 #36
0
        public void SerializeDynamicPropertyAndApplyNamingConvention()
        {
            dynamic obj = new ExpandoObject();
            obj.property_one = new ExpandoObject();
            ((IDictionary<string, object>)obj.property_one).Add("new_key_here", "new_value");

            var mockNamingConvention = A.Fake<INamingConvention>();
            A.CallTo(() => mockNamingConvention.Apply(A<string>.Ignored)).Returns("xxx");

            var serializer = new Serializer(namingConvention: mockNamingConvention);
            var writer = new StringWriter();
            serializer.Serialize(writer, obj);

            writer.ToString().Should().Contain("xxx: new_value");
        }
예제 #37
0
        public void SerializationRespectsYamlIgnoreOverride()
        {

            var writer = new StringWriter();
            var obj = new Simple();

            var overrides = new YamlAttributeOverrides();
            var ignore = new YamlIgnoreAttribute();
            overrides.Add(typeof(Simple), "aaa", ignore);
            var serializer = new Serializer(overrides: overrides);
            
            serializer.Serialize(writer, obj);
            var serialized = writer.ToString();
            Dump.WriteLine(serialized);

            serialized.Should().NotContain("aaa");
        }
예제 #38
0
        public void SpecialFloatsAreSerializedCorrectly()
        {
            var serializer = new Serializer();

            var buffer = new StringWriter();
            serializer.Serialize(buffer, new double[]
            {
                double.NaN,
                double.PositiveInfinity,
                double.NegativeInfinity,
            });

            var text = buffer.ToString();

            Assert.Contains("- .nan", text);
            Assert.Contains("- .inf", text);
            Assert.Contains("- -.inf", text);
        }
        /// <summary>
        ///     Store a <see cref="UpdateReport" /> in a <see cref="ZipFile" />.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> to write to.</param>
        /// <param name="report"><see cref="UpdateReport" /> to store.</param>
        private static void StoreReport(ZipFile zip, UpdateReport report)
        {
            var textTarget = string.Format(UpdateReportTextFile, report.PreviousVersion, report.UpdateVersion);
            zip.UpdateEntry(textTarget, string.Join(Environment.NewLine, report.Changes.Select(_ => _.ToString())),
                ZipEncoding);

            var yamlTarget = string.Format(UpdateReportYamlFile, report.PreviousVersion, report.UpdateVersion);
            var serializer = new Serializer();
            byte[] yamlBuffer;
            using (var ms = new MemoryStream()) {
                using (TextWriter writer = new StreamWriter(ms, ZipEncoding)) {
                    serializer.Serialize(writer, report);
                    writer.Flush();
                    yamlBuffer = ms.ToArray();
                }
            }
            zip.UpdateEntry(yamlTarget, yamlBuffer);

            var binTarget = string.Format(UpdateReportBinFile, report.PreviousVersion, report.UpdateVersion);
            var formatter = new BinaryFormatter();
            byte[] binBuffer;

            using (var ms = new MemoryStream()) {
                formatter.Serialize(ms, report);
                binBuffer = ms.ToArray();
            }

            zip.UpdateEntry(binTarget, binBuffer);
        }
예제 #40
0
        public void SerializationBaseAttributeOverride()
        {
            var writer = new StringWriter();
            var obj = new Derived { DerivedProperty = "Derived", BaseProperty = "Base" };

            var overrides = new YamlAttributeOverrides();
            var ignore = new YamlIgnoreAttribute();
            overrides.Add(typeof(Base), "BaseProperty", ignore);
            
            var serializer = new Serializer(overrides: overrides);
            
            serializer.Serialize(writer, obj);
            var serialized = writer.ToString();
            Dump.WriteLine(serialized);

            serialized.Should()
                .Be("DerivedProperty: Derived\r\n", "the base property should be specifically ignored");
        }
예제 #41
0
        public void SerializationRespectsScalarStyleOverride()
        {
            var writer = new StringWriter();
            var obj = new ScalarStyleExample();

            var overrides = new YamlAttributeOverrides();
            var style1 = new YamlMemberAttribute();
            style1.ScalarStyle = ScalarStyle.DoubleQuoted;
            var style2 = new YamlMemberAttribute();
            style2.ScalarStyle = ScalarStyle.Literal;
            overrides.Add(typeof(ScalarStyleExample), "LiteralString", style1);
            overrides.Add(typeof(ScalarStyleExample), "DoubleQuotedString", style2);
            
            var serializer = new Serializer(overrides: overrides);
            
            serializer.Serialize(writer, obj);
            var serialized = writer.ToString();
            Dump.WriteLine(serialized);

            serialized.Should()
                .Be("LiteralString: \"Test\"\r\nDoubleQuotedString: |-\r\n  Test\r\n", "the properties should be specifically styled");
        }
        public async Task <IActionResult> PostSolutionTemplate([FromBody] SolutionTemplateViewModel solutionTemplateViewModel)
        {
            Console.WriteLine(solutionTemplateViewModel);
            try
            {
                var deserializer     = new Deserializer();
                var solutionTemplate = new SolutionTemplate();
                Console.WriteLine(JsonConvert.SerializeObject(solutionTemplateViewModel));
                solutionTemplate.Intent = solutionTemplateViewModel.Intent;

                solutionTemplate.Tasks = deserializer.Deserialize(new StringReader(solutionTemplateViewModel.Tasks));
                Console.WriteLine(JsonConvert.SerializeObject(solutionTemplate));

                List <dynamic> actions = new List <dynamic>();

                foreach (var e in solutionTemplate.Tasks as List <dynamic> )
                {
                    Guid   g          = Guid.NewGuid();
                    string GuidString = Convert.ToBase64String(g.ToByteArray());
                    GuidString = GuidString.Replace("=", "");
                    GuidString = GuidString.Replace("+", "");

                    if (e["stage"] == "action")
                    {
                        e["tags"] = new List <string> {
                            GuidString
                        }
                    }
                    ;

                    var data = JObject.Parse(JsonConvert.SerializeObject(e));
                    //Console.WriteLine(data);

                    if (data["stage"].ToString() == "action")
                    {
                        var values = data.ToObject <Dictionary <string, object> >();
                        values.Remove("stage");
                        actions.Add(values);

                        try {
                            if (values["register"] != null)
                            {
                                object redisobj = new { name = "Store gitdata in redis", shell = "redis-cli -h ${{REDIS_HOST}} -p ${{REDIS_PORT}} HSET ${{threadId}}" + " " + values["register"] + " '{{" + values["register"] + ".content}}'", tags = values["tags"] };
                                actions.Add(redisobj);
                            }
                        }
                        catch (Exception ex) {}
                    }
                }
                Console.WriteLine(JsonConvert.SerializeObject(solutionTemplate.Tasks));

                object        scriptobj = new { hosts = "localhost", gather_facts = false, tasks = actions };
                List <object> final     = new List <object>()
                {
                    scriptobj
                };
                var finalJson = JsonConvert.SerializeObject(final);

                var     expConverter     = new ExpandoObjectConverter();
                dynamic desiralizeObject = JsonConvert.DeserializeObject <List <ExpandoObject> >(finalJson, expConverter);

                var    serializer = new YamlDotNet.Serialization.Serializer();
                string yaml       = serializer.Serialize(desiralizeObject);
                //Console.Write(solutionTemplate.Intent);
                solutionTemplate.Actions = yaml;

                var solutionTemplateAsJsonString   = JsonConvert.SerializeObject(solutionTemplate);
                var solutionTemplateAsBsonDocument = BsonDocument.Parse(solutionTemplateAsJsonString);
                Console.WriteLine(solutionTemplateAsBsonDocument);
                await _service.CreateSolution(solutionTemplateAsBsonDocument);

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.StackTrace));
            }
        }
예제 #43
0
        public void GuidsShouldBeQuotedWhenSerializedAsJson()
        {
            var sut = new Serializer(SerializationOptions.JsonCompatible | SerializationOptions.EmitDefaults);

            var yamlAsJson = new StringWriter();
            sut.Serialize(yamlAsJson, new
            {
                id = Guid.Empty
            });

            Assert.Contains("\"00000000-0000-0000-0000-000000000000\"", yamlAsJson.ToString());
        }