public static UniversityPortalConfig GetInstance (int portalId)
        {
            var lazyPortalConfig = portalConfigs.GetOrAdd (portalId, newKey => 
                new Lazy<UniversityPortalConfig> (() => {

                    var portalSettings = new PortalSettings (portalId);
                    var portalConfigFile = Path.Combine (portalSettings.HomeDirectoryMapPath, "R7.University.yml");

                    // ensure portal config file exists
                    if (!File.Exists (portalConfigFile)) {
                        File.Copy (Path.Combine (
                            Globals.ApplicationMapPath,
                            "DesktopModules\\R7.University\\R7.University\\R7.University.yml"), 
                            portalConfigFile);
                    }

                    using (var configReader = new StringReader (File.ReadAllText (portalConfigFile))) {
                        var deserializer = new Deserializer (namingConvention: new HyphenatedNamingConvention ());
                        return deserializer.Deserialize<UniversityPortalConfig> (configReader);
                    }
                }
                ));

            return lazyPortalConfig.Value;
        }
 // Use this for initialization
 void Start () {
     var input = new StringReader(Document);
     
     var deserializer = new Deserializer();
     
     var reader = new EventReader(new Parser(input));
     
     // Consume the stream start event "manually"
     reader.Expect<StreamStart>();
     
     var output = new StringBuilder();
     while(reader.Accept<DocumentStart>())
     {
         // Deserialize the document
         var doc = deserializer.Deserialize<List<string>>(reader);
     
         output.AppendLine("## Document");
         foreach(var item in doc)
         {
             output.AppendLine(item);
         }
     }    
     Debug.Log(output);
     
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Loads an article from a .yml file.
        /// </summary>
        static Article FromYaml(string path)
        {
            // Get the file path from the given URL path
            var filename = "articles/" + path + ".yml";

            if (!File.Exists(filename))
                throw new FileNotFoundException(filename);

            // Load the article with a YamlDotNet deserializer
            var articleFile = File.OpenRead(filename);
            var deserializer = new Deserializer();
            var article = deserializer.Deserialize<Article>(new StreamReader(articleFile));

            // Set some default values if they are not specified in the file
            if (article.Slug == null)
                article.Slug = path;

            if (article.Summary == null)
            {
                var firstLine = article.Content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)[0];
                article.Summary = firstLine;
            }

            // Convert the Markdown content to HTML
            var markdownConverter = new Markdown();
            article.Content = markdownConverter.Transform(article.Content);
            article.Summary = Utils.StripHtmlTags(markdownConverter.Transform(article.Summary));

            return article;
        }
Ejemplo n.º 4
0
        public static void Notify(StringReader reader)
        {
            var deserializer = new Deserializer(null, new NullNamingConvention(), ignoreUnmatched: true);
            var legacyConfig = deserializer.Deserialize<LegacyConfig>(reader);
            if (legacyConfig == null)
                return;

            var issues = new List<string>();

            var oldConfigs = legacyConfig.Branches.Keys.Where(k => OldConfigKnownRegexes.Keys.Contains(k) && k != OldConfigKnownRegexes[k]).ToList();
            if (oldConfigs.Any())
            {
                var max = oldConfigs.Max(c => c.Length);
                var oldBranchConfigs = oldConfigs.Select(c => string.Format("{0} -> {1}", c.PadRight(max), OldConfigKnownRegexes[c]));
                var branchErrors = string.Join("\r\n    ", oldBranchConfigs);
                issues.Add(string.Format(
            @"GitVersion branch configs no longer are keyed by regexes, update:
            {0}", branchErrors));
            }

            if (legacyConfig.assemblyVersioningScheme != null)
                issues.Add("assemblyVersioningScheme has been replaced by assembly-versioning-scheme");

            if (legacyConfig.DevelopBranchTag != null)
                issues.Add("develop-branch-tag has been replaced by branch specific configuration. See http://gitversion.readthedocs.org/en/latest/configuration/#branch-configuration");

            if (legacyConfig.ReleaseBranchTag != null)
                issues.Add("release-branch-tag has been replaced by branch specific configuration. See http://gitversion.readthedocs.org/en/latest/configuration/#branch-configuration");

            if (legacyConfig.Branches != null && legacyConfig.Branches.Any(branches => branches.Value.IsDevelop != null))
                issues.Add("'is-develop' is deprecated, use 'tracks-release-branches' instead. See http://gitversion.readthedocs.org/en/latest/configuration/#branch-configuration");

            if (issues.Any())
                throw new OldConfigurationException("GitVersion configuration file contains old configuration, please fix the following errors:\r\n" + string.Join("\r\n", issues));
        }
Ejemplo n.º 5
0
        public static void Load(string filename)
        {
            var buffer = File.ReadAllText(filename);

            var deserializer = new Deserializer();
            var config = deserializer.Deserialize<Config>(new StringReader(buffer));
        }
Ejemplo n.º 6
0
        public static void LoadFiles(AddFunc addFunc)
        {
            TextAsset dirTxt = Resources.Load<TextAsset>(HFT_WEB_DIR);
            if (dirTxt == null)
            {
                Debug.LogError("could not load: " + HFT_WEB_DIR);
                return;
            }

            Deserializer deserializer = new Deserializer();
            string[] files = deserializer.Deserialize<string[] >(dirTxt.text);

            foreach (string file in files)
            {
                string path = HFT_WEB_PATH + file;
                TextAsset asset = Resources.Load(path) as TextAsset;
                if (asset == null)
                {
                    Debug.LogError("Could not load: " + path);
                }
                else
                {
                    addFunc(file, asset.bytes);
                }
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 8
0
        //private static Configuration ConfigOnDisk;
        public static LoadResult Load(string fileName)
        {
            if (!File.Exists(fileName))
            {
                Logger.Log(null, "Config file not found. Creating a new one...", LogLevel.Info);
                try
                {
                    var exampleConfigStream =
                        Assembly.GetExecutingAssembly().GetManifestResourceStream("BaggyBot.src.EmbeddedData.Configuration.example-config.yaml");
                    exampleConfigStream.CopyTo(File.Create(fileName));
                }
                catch (Exception e) when (e is FileNotFoundException || e is FileLoadException || e is IOException)
                {
                    Logger.Log(null, "Unable to load the default config file.", LogLevel.Error);
                    Logger.Log(null, "Default config file not created. You might have to create one yourself.", LogLevel.Warning);
                    return LoadResult.Failure;
                }

                return LoadResult.NewFileCreated;
            }

            var deserialiser = new Deserializer(namingConvention: new HyphenatedNamingConvention(), ignoreUnmatched: false);
            using (var reader = File.OpenText(fileName))
            {
                Config = deserialiser.Deserialize<Configuration>(reader);
            }
            /*using (var reader = File.OpenText(fileName))
            {
                ConfigOnDisk = deserialiser.Deserialize<Configuration>(reader);
            }*/
            return LoadResult.Success;
        }
 private void Initialize()
 {
     if (!JustInitialized) return;
     _serializer = new Serializer<SimpleJsonWriter>(_primaryType);
     _deserializer = new Deserializer<SimpleJsonReader>(_primaryType);
     JustInitialized = false;
 }
        public void Generate_All()
        {
            Clean();
            EnsurePathsExist();

            var files = GetAllYamlFiles();

            var deser = new Deserializer();

            foreach( var file in files )
            {
                //if( !file.Contains("random", StringComparison.OrdinalIgnoreCase) )
                //    continue;//just deal with random for now.
                Console.WriteLine("READING: " + file);
                var sr = new StringReader(File.ReadAllText(file));
                var yamlTest = deser.Deserialize<YamlTest>(sr);

                var mutator = new CSharpTestMutator(yamlTest);
                mutator.MutateTests();


                var outputFile =
                    Path.Combine(OutputDir,
                        Path.GetFileName(
                            Path.ChangeExtension(file, ".cs")));

                Console.WriteLine("OUTPUT: " + outputFile);

                var template = new TestTemplate() {YamlTest = yamlTest};

                File.WriteAllText(outputFile, template.TransformText());
            }
        }
Ejemplo n.º 11
0
        public static AgentConfig LoadFromFile(string file)
        {
            AgentConfig ac;

            using (StreamReader sr = File.OpenText(file))
            {
                Deserializer ds = new Deserializer(namingConvention: new CamelCaseNamingConvention());
                ac = ds.Deserialize<AgentConfig>(sr);
            }

            CheckAgentConfigForNull(ac);
            ac = InitializeAgentConfigLists(ac);

            ac = SetDefaultTaskValues(ac);

            if (ac._checks != null)
                ac = LoadSerializedCheck(ac);

            if (ac._info != null)
                ac = LoadSerializedInfo(ac);

            if (ac._actions != null)
                ac = LoadSerializedActions(ac);

            return ac;
        }
Ejemplo n.º 12
0
 public static NemesisConfig LoadFromFile(string file)
 {
     using (var sr = File.OpenText(file))
     {
         var ds = new Deserializer(namingConvention: new CamelCaseNamingConvention());
         return ds.Deserialize<NemesisConfig>(sr);
     }
 }
Ejemplo n.º 13
0
        public void TestInit()
        {
            _fixture = new Fixture();
            _jsonSerializer = new Mock<IJsonSerializer>(MockBehavior.Strict);
            _jsonDeserializer = new Mock<IJsonSerializer>(MockBehavior.Strict);

            _deserializer = new Deserializer<SampleSource>(_jsonSerializer.Object, _jsonDeserializer.Object);
        }
Ejemplo n.º 14
0
    // Use this for initialization
    void Awake()
    { 
        //Read in archetype file
        Reader = new StringReader(Resources.Load<TextAsset>("creatures").text);
		NPCReader = new StringReader(Resources.Load<TextAsset>("npcDefinitions").text);
        CamelCaseDeserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
        DialogNPCs = new List<NpcData>();
    }
Ejemplo n.º 15
0
		static Config()
		{
			using (var reader = new StreamReader(File.OpenRead("config.yml")))
			{
				var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
				Instance = deserializer.Deserialize<Config>(reader);
			}
		}
Ejemplo n.º 16
0
		public NavMeshConfigurationFile(StreamReader input)
		{
			var deserializer = new Deserializer(namingConvention: new HyphenatedNamingConvention());
			var data = deserializer.Deserialize<YamlData>(input);

			GenerationSettings = data.Config;
			ExportPath = data.Export;
			InputMeshes = data.Meshes;
		}
Ejemplo n.º 17
0
 public override void Deserialize(Deserializer deserializer)
 {
     base.Deserialize(deserializer);
     var touched = new Capo<bool>(fingerprint, tag.Offset);
     if (touched[0])
     {
         deserializer.Read(out message_);
     }
 }
Ejemplo n.º 18
0
        public static void Load(string filename)
        {
            var buffer = File.ReadAllText("data//" + filename);

            var deserializer = new Deserializer(ignoreUnmatched: true);
            var config = deserializer.Deserialize<Config>(new StringReader(buffer));

            Users = config.Users;
        }
Ejemplo n.º 19
0
 public static SimpleDataView[] ReadControls(string cfgPath)
 {
     SimpleDataView[] views = null;
     var d = new Deserializer();
     using(var reader = new StreamReader(cfgPath)) {
         views = d.Deserialize<SimpleDataView[]>(reader);
     }
     return views;
 }
        public void PortalConfigDeserializationTest ()
        {
            var defaultConfigFile = Path.Combine ("..", "..", "..", "R7.Epsilon", "Skins", "R7.Epsilon.yml");

            using (var configReader = new StringReader (File.ReadAllText (defaultConfigFile))) {
                var deserializer = new Deserializer (namingConvention: new HyphenatedNamingConvention ());
                Assert.NotNull (deserializer.Deserialize<EpsilonPortalConfig> (configReader));
            } 
        }
 private void Initialize()
 {
     if (!JustInitialized) return;
     _serializer = new Serializer<FastBinaryWriter<OutputBuffer>>(_primaryType);
     _deserializer = new Deserializer<FastBinaryReader<InputBuffer>>(_primaryType);
     _serializerStream = new Serializer<FastBinaryWriter<OutputStream>>(_primaryType);
     _deserializerStream = new Deserializer<FastBinaryReader<InputStream>>(_primaryType);
     JustInitialized = false;
 }
        public void InvalidXml_ThrowsXmlDeserializationFailureException()
        {
            var deserializer = new Deserializer();

            var xml = XDocument.Parse("<?xml version=\"1.0\" encoding=\"UTF-16\"?><root></root>");

            var exception = Assert.Throws<XmlDeserializationFailureException>(() => deserializer.Deserialize<schemeType>(xml));
            Assert.NotNull(exception.InnerException);
        }
        public void PortalConfigDeserializationTest (int portalNumber)
        {
            var configFile = Path.Combine ("..", "..", "..", "R7.Epsilon", "Customizations",
                "volgau.com", "Portals", portalNumber.ToString (), "R7.Epsilon.yml");

            using (var configReader = new StringReader (File.ReadAllText (configFile))) {
                var deserializer = new Deserializer (namingConvention: new HyphenatedNamingConvention ());
                Assert.NotNull (deserializer.Deserialize<EpsilonPortalConfig> (configReader));
            } 
        }
Ejemplo n.º 24
0
        public static void Load(string filename)
        {
            var buffer = File.ReadAllText(filename);

            var deserializer = new Deserializer(ignoreUnmatched: true);
            var config = deserializer.Deserialize<Config>(new StringReader(buffer));

            DatabaseConfiguration = config.DatabaseConfiguration;
            DebugLog = config.DebugLog;
        }
Ejemplo n.º 25
0
        public void ReadString_ReadsCompactEmptyString()
        {
            var data = new byte[] { 0x00 };
            var stream = new MemoryStream(data);
            var ds = new Deserializer(stream);

            var str = ds.ReadString();

            Assert.AreEqual(string.Empty, str);
        }
Ejemplo n.º 26
0
        private void LoadPlugins()
        {
            string text = File.ReadAllText(_pluginsYmlFile);

            Deserializer deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());

            PluginsConf pluginsConf = deserializer.Deserialize<PluginsConf>(new StringReader(text));

            OnPluginsLoaded(new PluginsConfLoadedEventArgs(pluginsConf));
        }
Ejemplo n.º 27
0
    private List<CardDescriptor> LoadCards ()
    {
        var deserializer = new Deserializer (namingConvention: new CamelCaseNamingConvention ());
        var cardsString = new StringReader (cardAsset.text);
        List<CardDescriptor> cards = deserializer.Deserialize<List<CardDescriptor>> (cardsString);

        //PrintDebug(cards);

        return cards;
    }
Ejemplo n.º 28
0
 public static Config Read(TextReader reader)
 {
     var deserializer = new Deserializer(null, new CamelCaseNamingConvention());
     var deserialize = deserializer.Deserialize<Config>(reader);
     if (deserialize == null)
     {
         return new Config();
     }
     return deserialize;
 }
Ejemplo n.º 29
0
        public GameServer(Options options, GameObject gameObject)
        {
            m_options = options;
            m_gameObject = gameObject;
            m_players = new Dictionary<int, NetPlayer>();
            m_sendQueue = new List<String>();
            m_deserializer = new Deserializer();

            m_eventProcessor = m_gameObject.AddComponent<EventProcessor>();
        }
Ejemplo n.º 30
0
		public void Run(string[] args)
		{
			// Setup the input
			var input = new StringReader(_document);

			var deserializer = new Deserializer();
			var order = (Order)deserializer.Deserialize(input, typeof(Order));

			Console.WriteLine("Receipt: {0}", order.Receipt);
			Console.WriteLine("Customer: {0} {1}", order.Customer.Given, order.Customer.Family);
		}
Ejemplo n.º 31
0
 static JsonExtensions()
 {
     _javaScriptSerializer = new JavaScriptSerializer();
     _serializer           = _javaScriptSerializer.Serialize;
     _deserializer         = _javaScriptSerializer.Deserialize;
 }
        private void LoadData()
        {
            var deserializer   = new Deserializer();
            var fishYamlObject = deserializer.Deserialize(new StringReader(Resources.Fish));
            var fishJToken     = JToken.FromObject(fishYamlObject);

            Data.FishList = ((JObject)fishJToken["content"]).Properties().Select(pro => new
            {
                Id    = int.Parse(pro.Name),
                Value = pro.Value.Value <string>().Split('/')
            }).Where(item => item.Value[1] != "trap")
                            .Select(item => new Fish
            {
                Id              = item.Id,
                Name            = item.Value[0],
                MoveType        = (MoveType)Enum.Parse(typeof(MoveType), item.Value[2].FirstLetterToUpper()),
                TimeRangeStart  = int.Parse(item.Value[5].Split(' ')[0]) / 100,
                TimeRangeFinish = int.Parse(item.Value[5].Split(' ')[1]) / 100,
                Season          = EnumIntialTool.GetSeason(item.Value[6].Split(' ')),
                Weather         = (Weather)Enum.Parse(typeof(Weather), item.Value[7].FirstLetterToUpper())
            }).ToList();
            var locationObject = deserializer.Deserialize(new StringReader(Resources.Locations));
            var locationJToken = JToken.FromObject(locationObject);

            Data.LocationList = ((JObject)locationJToken["content"]).Properties().Select(pro => new
            {
                Location = pro.Name,
                Value    = pro.Value.Value <string>().Split('/')
            }).Select(item => new Location
            {
                Name  = item.Location,
                Range = new Dictionary <Season, List <IdAndRate> >
                {
                    { Season.Spring, IdAndRate.FromStrings(item.Value[0].Split(' ')) },
                    { Season.Summer, IdAndRate.FromStrings(item.Value[1].Split(' ')) },
                    { Season.Fall, IdAndRate.FromStrings(item.Value[2].Split(' ')) },
                    { Season.Winter, IdAndRate.FromStrings(item.Value[3].Split(' ')) },
                },
                Fish = new Dictionary <Season, List <IdAndState> >
                {
                    { Season.Spring, IdAndState.FromStrings(item.Value[4].Split(' ')) },
                    { Season.Summer, IdAndState.FromStrings(item.Value[5].Split(' ')) },
                    { Season.Fall, IdAndState.FromStrings(item.Value[6].Split(' ')) },
                    { Season.Winter, IdAndState.FromStrings(item.Value[7].Split(' ')) },
                },
                Unkonw = IdAndRate.FromStrings(item.Value[8].Split(' '))
            }).ToList();

            List <string> fishNameCbItem = new List <string> {
                "Any"
            };

            fishNameCbItem.AddRange(Data.FishList.Select(fish => fish.Name));

            cbFishName.DataSource    = fishNameCbItem;
            cbFishName.SelectedIndex = 0;

            cbSeason.DataSource = new List <string> {
                "Any", "Spring", "Summer", "Fall", "Winter"
            };
            cbSeason.SelectedIndex = 0;

            List <string> locationCbItem = new List <string> {
                "Any"
            };

            locationCbItem.AddRange(Data.LocationList.Select(loc => loc.Name));
            cbLocation.DataSource    = locationCbItem;
            cbLocation.SelectedIndex = 0;

            cbWeather.DataSource = new List <string> {
                "Any", "Both", "Sunny", "Rainy"
            };
            cbWeather.SelectedIndex = 0;
            _loaded = true;
            ShowData();
        }
Ejemplo n.º 33
0
 private T ParseData <T>(Deserializer reader) where T : BaseMsg, new()
 {
     return(reader.Parse <T>());
 }
Ejemplo n.º 34
0
        internal void Import()
        {
            CreateFileStream();
            _deserializer = new Deserializer(_xr);
            // If total count has been requested, return a dummy object with zero confidence
            if (_cmdlet.PagingParameters.IncludeTotalCount)
            {
                PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0);
                _cmdlet.WriteObject(totalCount);
            }

            ulong skip  = _cmdlet.PagingParameters.Skip;
            ulong first = _cmdlet.PagingParameters.First;

            // if paging is not specified then keep the old V2 behavior
            if (skip == 0 && first == ulong.MaxValue)
            {
                while (!_deserializer.Done())
                {
                    object result = _deserializer.Deserialize();
                    _cmdlet.WriteObject(result);
                }
            }
            // else try to flatten the output if possible
            else
            {
                ulong skipped = 0;
                ulong count   = 0;
                while (!_deserializer.Done() && count < first)
                {
                    object   result   = _deserializer.Deserialize();
                    PSObject psObject = result as PSObject;

                    if (psObject != null)
                    {
                        ICollection c = psObject.BaseObject as ICollection;
                        if (c != null)
                        {
                            foreach (object o in c)
                            {
                                if (count >= first)
                                {
                                    break;
                                }

                                if (skipped++ >= skip)
                                {
                                    count++;
                                    _cmdlet.WriteObject(o);
                                }
                            }
                        }
                        else
                        {
                            if (skipped++ >= skip)
                            {
                                count++;
                                _cmdlet.WriteObject(result);
                            }
                        }
                    }
                    else if (skipped++ >= skip)
                    {
                        count++;
                        _cmdlet.WriteObject(result);
                        continue;
                    }
                }
            }
        }
Ejemplo n.º 35
0
        public void Rate()
        {
            ConsoleLogger.Log("Starting rate.");

            ConsoleLogger.Log("Loading policy.");

            // load policy - open file policy.json
            string policyJson = PolicyReader.GetPolicyContent();

            var policy = Deserializer.DeserializePolicy(policyJson);

            switch (policy.Type)
            {
            case PolicyType.Auto:
                ConsoleLogger.Log("Rating AUTO policy...");
                ConsoleLogger.Log("Validating policy.");
                if (String.IsNullOrEmpty(policy.Make))
                {
                    ConsoleLogger.Log("Auto policy must specify Make");
                    return;
                }
                if (policy.Make == "BMW")
                {
                    if (policy.Deductible < 500)
                    {
                        Rating = 1000m;
                    }
                    Rating = 900m;
                }
                break;

            case PolicyType.Land:
                ConsoleLogger.Log("Rating LAND policy...");
                ConsoleLogger.Log("Validating policy.");
                if (policy.BondAmount == 0 || policy.Valuation == 0)
                {
                    ConsoleLogger.Log("Land policy must specify Bond Amount and Valuation.");
                    return;
                }
                if (policy.BondAmount < 0.8m * policy.Valuation)
                {
                    ConsoleLogger.Log("Insufficient bond amount.");
                    return;
                }
                Rating = policy.BondAmount * 0.05m;
                break;

            case PolicyType.Life:
                ConsoleLogger.Log("Rating LIFE policy...");
                ConsoleLogger.Log("Validating policy.");
                if (policy.DateOfBirth == DateTime.MinValue)
                {
                    ConsoleLogger.Log("Life policy must include Date of Birth.");
                    return;
                }
                if (policy.DateOfBirth < DateTime.Today.AddYears(-100))
                {
                    ConsoleLogger.Log("Centenarians are not eligible for coverage.");
                    return;
                }
                if (policy.Amount == 0)
                {
                    ConsoleLogger.Log("Life policy must include an Amount.");
                    return;
                }
                int age = DateTime.Today.Year - policy.DateOfBirth.Year;
                if (policy.DateOfBirth.Month == DateTime.Today.Month &&
                    DateTime.Today.Day < policy.DateOfBirth.Day ||
                    DateTime.Today.Month < policy.DateOfBirth.Month)
                {
                    age--;
                }
                decimal baseRate = policy.Amount * age / 200;
                if (policy.IsSmoker)
                {
                    Rating = baseRate * 2;
                    break;
                }
                Rating = baseRate;
                break;

            default:
                ConsoleLogger.Log("Unknown policy type");
                break;
            }

            ConsoleLogger.Log("Rating completed.");
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Deserializes the specified json string as either a Dictionary[string, object] or as a List[object]
 /// depending on the syntax of the JSON string.
 /// </summary>
 /// <param name="json">The json.</param>
 /// <returns>Type of the current deserializes.</returns>
 /// <example>
 /// The following code shows how to deserialize a JSON string into a Dictionary.
 /// <code>
 /// using Unosquare.Swan.Formatters;
 ///
 /// class Example
 /// {
 ///     static void Main()
 ///     {
 ///         // json to deserialize
 ///         var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}";
 ///
 ///         // deserializes the specified json into a Dictionary&lt;string, object&gt;.
 ///         var data = Json.Deserialize(basicJson);
 ///     }
 /// }
 /// </code>
 /// </example>
 public static object Deserialize(string json) => Deserializer.DeserializeInternal(json);
Ejemplo n.º 37
0
 public override void Deserialize(Deserializer deserializer)
 {
     this.Unknown0 = deserializer.ReadInt16();
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Deserializes the property value
 /// </summary>
 /// <param name="Input">Binary representation.</param>
 /// <param name="ExpectedType">Expected Type</param>
 /// <returns>Deserialized value.</returns>
 public abstract object Deserialize(Deserializer Input, Type ExpectedType);
Ejemplo n.º 39
0
 public override void DeserializeRequest(ArraySegment <byte> val)
 {
     Request = Deserializer.Deserialize <TRequest>(val);
 }
Ejemplo n.º 40
0
 internal EncodedConnection(Options opts)
     : base(opts)
 {
     onSerialize   = defaultSerializer;
     onDeserialize = defaultDeserializer;
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Loads and fills a <see cref="ConfigurationStore"/> using UTF-8 encoding.
 /// </summary>
 /// <param name="entryFilePath">Path of the entry file.</param>
 /// <param name="deserializer">The deserializer to deserialize files. It must support <see cref="DeserializerBuilder.IgnoreUnmatchedProperties"/>.</param>
 /// <returns></returns>
 public static ConfigurationStore Load([NotNull] string entryFilePath, [NotNull] Deserializer deserializer)
 {
     return(Load(entryFilePath, deserializer, Encoding.UTF8));
 }
Ejemplo n.º 42
0
 public override void Deserialize(Deserializer deserializer)
 {
     this.Unknown0 = deserializer.ReadVarint();
 }
Ejemplo n.º 43
0
 public override void Deserialize(Deserializer deserializer)
 {
     this.Unknown0 = deserializer.ReadVarint();
     this.Unknown1 = deserializer.ReadWorldPosition();
     this.Unknown2 = deserializer.ReadSingle();
 }
Ejemplo n.º 44
0
 public static GameObject FromJson(Deserializer deserializer)
 {
     var(coords, halfsize, origin) = PositionJson.FromJson(deserializer.getData());
     return(new Ladder(coords, halfsize));
 }
 /// <summary>
 /// Adds serialization delegates for <paramref name="type"/>.
 /// </summary>
 /// <param name="serializerFeature">The serializer feature.</param>
 /// <param name="type">The type.</param>
 /// <param name="copier">The copy delegate.</param>
 /// <param name="serializer">The serializer delegate.</param>
 /// <param name="deserializer">The deserializer delegate.</param>
 /// <param name="overrideExisting">Whether or not to override existing registrations.</param>
 public static void AddSerializerDelegates(this SerializerFeature serializerFeature, Type type, DeepCopier copier, Serializer serializer, Deserializer deserializer, bool overrideExisting)
 {
     serializerFeature.SerializerDelegates.Add(new SerializerDelegateMetadata(type, copier, serializer, deserializer, overrideExisting));
 }
Ejemplo n.º 46
0
 public void Deserialize(Deserializer deserializer)
 {
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Deserializes the specified json string and converts it to the specified object type.
 /// </summary>
 /// <param name="json">The json.</param>
 /// <param name="resultType">Type of the result.</param>
 /// <param name="includeNonPublic">if set to true, it also uses the non-public constructors and property setters.</param>
 /// <returns>Type of the current conversion from json result.</returns>
 public static object Deserialize(string json, Type resultType, bool includeNonPublic = false)
 => Converter.FromJsonResult(Deserializer.DeserializeInternal(json), resultType, includeNonPublic);
Ejemplo n.º 48
0
 public void Deserialize(Deserializer deserializer)
 {
     this.Unknown0 = deserializer.ReadUtf16String();
 }
Ejemplo n.º 49
0
 public static T Deserialize <T>(IReader reader)
 {
     return(Deserializer <T> .DeserializeFunc(reader));
 }
Ejemplo n.º 50
0
 public override void Deserialize(Deserializer reader)
 {
     AnnotationStr = reader.ReadString();
 }
Ejemplo n.º 51
0
 public override void Deserialize(Deserializer deserializer)
 {
 }
Ejemplo n.º 52
0
 public MarkdownConverterService(ILogger <MarkdownConverterService> logger)
 {
     this.logger      = logger;
     yamlDeserializer = new Deserializer();
     jsonSerializer   = new JsonSerializer();
 }
Ejemplo n.º 53
0
 public override void Deserialize(Deserializer deserializer)
 {
     this.Unknown0 = deserializer.ReadVarint();
     this.Unknown1 = deserializer.ReadUtf16String();
 }
Ejemplo n.º 54
0
 public override void Deserialize(Deserializer reader)
 {
     tick       = reader.GetInt32();
     inputDatas = reader.GetBytes();
     AfterDeserialize();
 }
Ejemplo n.º 55
0
        public void TestVariableLengthInt64()
        {
            //using (var stream = new MemoryStream())
            {
                var          stream       = new x2net.Buffer();
                Serializer   serializer   = new Serializer(stream);
                Deserializer deserializer = new Deserializer(stream);

                // Boundary value tests

                serializer.Write(0L);
                serializer.Write(-1L);
                serializer.Write(Int64.MaxValue);
                serializer.Write(Int64.MinValue);

                stream.Rewind();
                //stream.Seek(0, SeekOrigin.Begin);

                long l;
                long bytes = deserializer.Read(out l);
                Assert.Equal(1, bytes);
                Assert.Equal(0L, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(1, bytes);
                Assert.Equal(-1L, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(10, bytes);
                Assert.Equal(Int64.MaxValue, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(10, bytes);
                Assert.Equal(Int64.MinValue, l);

                stream.Trim();
                //stream.SetLength(0);

                // Intermediate value tests

                serializer.Write(0x00003f80L >> 1);         // 2
                serializer.Write(0x001fc000L >> 1);         // 3
                serializer.Write(0x0fe00000L >> 1);         // 4
                serializer.Write(0x00000007f0000000L >> 1); // 5
                serializer.Write(0x000003f800000000L >> 1); // 6
                serializer.Write(0x0001fc0000000000L >> 1); // 7
                serializer.Write(0x00fe000000000000L >> 1); // 8
                serializer.Write(0x7f00000000000000L >> 1); // 9

                stream.Rewind();
                //stream.Seek(0, SeekOrigin.Begin);

                bytes = deserializer.Read(out l);
                Assert.Equal(2, bytes);
                Assert.Equal(0x00003f80L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(3, bytes);
                Assert.Equal(0x001fc000L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(4, bytes);
                Assert.Equal(0x0fe00000L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(5, bytes);
                Assert.Equal(0x00000007f0000000L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(6, bytes);
                Assert.Equal(0x000003f800000000L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(7, bytes);
                Assert.Equal(0x0001fc0000000000L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(8, bytes);
                Assert.Equal(0x00fe000000000000L >> 1, l);

                bytes = deserializer.Read(out l);
                Assert.Equal(9, bytes);
                Assert.Equal(0x7f00000000000000L >> 1, l);
            }
        }
Ejemplo n.º 56
0
 public override void Deserialize(Deserializer reader)
 {
     type = reader.GetByte();
     size = reader.GetByte();
     name = reader.GetString();
 }
Ejemplo n.º 57
0
        public static List <Weather> GetClimate()
        {
            var deserializer = new Deserializer();

            return(deserializer.Deserialize <List <Weather> >(ForestClimate));
        }
Ejemplo n.º 58
0
 public void Deserialize(Deserializer reader)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 59
0
        private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, System.Type mainControlType, Collection <string> typeNames, string viewName)
        {
            TypeMatch match = new TypeMatch(expressionFactory, db, typeNames);

            foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList)
            {
                if (vd == null || mainControlType != vd.mainControl.GetType())
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), (vd != null ? vd.name : string.Empty));
                    continue;
                }

                if (IsOutOfBandView(vd))
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH OutOfBand {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }

                if (vd.appliesTo == null)
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}  No applicable types",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }
                // first make sure we match on name:
                // if not, we do not try a match at all
                if (viewName != null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase))
                {
                    ActiveTracer.WriteLine(
                        "NOT MATCH {0}  NAME: {1}",
                        ControlBase.GetControlShapeName(vd.mainControl), vd.name);
                    continue;
                }

                // check if we have a perfect match
                // if so, we are done
                try
                {
                    TypeMatch.SetTracer(ActiveTracer);
                    if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo)))
                    {
                        TraceHelper(vd, true);
                        return(vd);
                    }
                }
                finally
                {
                    TypeMatch.ResetTracer();
                }

                TraceHelper(vd, false);
            }

            // this is the best match we had
            ViewDefinition result = GetBestMatch(match);

            // we were unable to find a best match so far..try
            // to get rid of Deserialization prefix and see if a
            // match can be found.
            if (result == null)
            {
                Collection <string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
                if (typesWithoutPrefix != null)
                {
                    result = GetView(expressionFactory, db, mainControlType, typesWithoutPrefix, viewName);
                }
            }

            return(result);
        }
Ejemplo n.º 60
0
 public void Deserialize(Deserializer deserializer)
 {
     this.Unknown0 = deserializer.ReadVarint();
     this.Unknown1 = deserializer.ReadVarint();
 }