Exemple #1
0
        public void WriteKeyValuePairTest()
        {
            var converter = GetConverter();
            var value     = new KeyValuePair <int, string>(1, "item");
            var expected  = "<xml><key>1</key><value>item</value></xml>";
            var actual    = converter.ToXml(value.GetType(), value);

            Assert.AreEqual(expected, actual);
        }
Exemple #2
0
        public void KeyValuePairTiposAnidados()
        {
            KeyValuePair <IdUnico, KeyValuePair <long, string> > pair = new KeyValuePair <IdUnico, KeyValuePair <long, string> >(new IdUnico(), new KeyValuePair <long, string>(125, "Gabriel"));
            ElementoBinario serializador = ElementoBinario.GetSerializador(pair.GetType());

            byte[] data = serializador.GetBytes(pair);
            KeyValuePair <IdUnico, KeyValuePair <long, string> > pairDeserializada = (KeyValuePair <IdUnico, KeyValuePair <long, string> >)serializador.GetObject(data);

            Assert.IsTrue(pair.Key.GetId().ArrayEqual(pairDeserializada.Key.GetId()) && pair.Value.Key.Equals(pairDeserializada.Value.Key) && pair.Value.Value.Equals(pairDeserializada.Value.Value));
        }
Exemple #3
0
        public void WriteField(Writer writer, SerializerSession session, uint fieldIdDelta, Type expectedType, KeyValuePair <TKey, TValue> value)
        {
            ReferenceCodec.MarkValueField(session);
            writer.WriteFieldHeader(session, fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            this.keyCodec.WriteField(writer, session, 0, typeof(TKey), value.Key);
            this.valueCodec.WriteField(writer, session, 1, typeof(TValue), value.Value);

            writer.WriteEndObject();
        }
Exemple #4
0
        public void KeyValuePairTiposMios()
        {
            KeyValuePair <IdUnico, byte[]> pair = new KeyValuePair <IdUnico, byte[]>(new IdUnico(), Serializar.GetBytes("Gabriel"));
            ElementoBinario serializador        = ElementoBinario.GetSerializador(pair.GetType());

            byte[] data = serializador.GetBytes(pair);
            KeyValuePair <IdUnico, byte[]> pairDeserializada = (KeyValuePair <IdUnico, byte[]>)serializador.GetObject(data);

            Assert.IsTrue(pair.Key.GetId().ArrayEqual(pairDeserializada.Key.GetId()) && pair.Value.ArrayEqual(pairDeserializada.Value));
        }
Exemple #5
0
        /// <summary>
        /// 将键值对转换至字符串
        /// </summary>
        /// <param name="value"></param>
        /// <param name="split1"></param>
        /// <returns></returns>
        public static string KVPConvertToString <K, V>(this KeyValuePair <K, V> value, char split1 = ':')
        {
            var type      = value.GetType();
            var pairKey   = type.GetProperty("Key").GetValue(value, null);
            var pairValue = type.GetProperty("Value").GetValue(value, null);

            var keyStr   = ConverToString(pairKey);
            var valueStr = ConverToString(pairValue);

            return(keyStr + Spriter2 + valueStr);
        }
Exemple #6
0
        void IFieldCodec <KeyValuePair <TKey, TValue> > .WriteField <TBufferWriter>(ref Writer <TBufferWriter> writer,
                                                                                    uint fieldIdDelta,
                                                                                    Type expectedType,
                                                                                    KeyValuePair <TKey, TValue> value)
        {
            ReferenceCodec.MarkValueField(writer.Session);
            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            _keyCodec.WriteField(ref writer, 0, typeof(TKey), value.Key);
            _valueCodec.WriteField(ref writer, 1, typeof(TValue), value.Value);

            writer.WriteEndObject();
        }
Exemple #7
0
        public void InvokeGenericVtype()
        {
            KeyValuePair <string, uint> kvp = new KeyValuePair <string, uint> ("a", 21);
            Type type = kvp.GetType();

            Type []    arguments      = type.GetGenericArguments();
            MethodInfo method         = typeof(MethodInfoTest).GetMethod("Go");
            MethodInfo generic_method = method.MakeGenericMethod(arguments);

            kvp = (KeyValuePair <string, uint>)generic_method.Invoke(null, new object [] { kvp });

            Assert.AreEqual("a", kvp.Key, "#1");
            Assert.AreEqual(21, kvp.Value, "#2");
        }
Exemple #8
0
        public void GetTest()
        {
            var model = new Model {
                name = "laojiu"
            };
            var p = model.GetType().GetProperty("name");

            var getter = Lambda.CreateGetFunc <Model, string>(p);
            var name   = getter.Invoke(model);

            Assert.True(name == model.name);


            var getter2 = Lambda.CreateGetFunc <object, string>(p);
            var name2   = getter2.Invoke(model);

            Assert.True(name2 == model.name);

            var getter3 = Lambda.CreateGetFunc <object, object>(p.DeclaringType, p.Name);
            var name3   = getter2.Invoke(model).ToString();

            Assert.True(name3 == model.name);

            var kv      = new KeyValuePair <string, int>("k", 10);
            var getter4 = Lambda.CreateGetFunc <object, object>(kv.GetType(), "Value");
            var value   = (int)getter4.Invoke(kv);

            Assert.True(value == kv.Value);

            var getter5 = Lambda.CreateGetFunc <object, int>(kv.GetType(), "Value");

            Assert.True(getter5.Invoke(kv) == kv.Value);

            var getter6 = Lambda.CreateGetFunc <object, long>(kv.GetType(), "Value");

            Assert.True(getter6.Invoke(kv) == kv.Value);
        }
        public static int Solution(int[] A)
        {
            KeyValuePair <int, string> kvp = new KeyValuePair <int, string>();

            Type t = kvp.GetType();
            // Get the IsValueType property of the myTestEnum variable.
            bool flag = t.IsValueType;
            int  h    = 0;

            return(h);


            string s = "sduhdfksuddhfksddjhfdskdjhdfkjfd";

            string[] blah = s.Split('d');
        }
Exemple #10
0
        public static void Write <K, V>(TextWriter os, KeyValuePair <K, V> x)
        {
            string key = x.Key.ToString();

            if (x.Value is XmlObject)
            {
                XmlObject v     = x.Value as XmlObject;
                string    pName = x.GetType().Name;
                os.WriteLine("<{0}  {1}=\"{2}\">", pName, KEYNAME, key);
                v.Write(os);
                os.WriteLine("</{0}>", pName);
            }
            else
            {
                os.WriteLine("<{0}  {1}=\"{2}\">{3}</{0}>", NODENAME, KEYNAME, key, x.Value);
            }
        }
Exemple #11
0
        // Auto-load/save functions
        public void loadFromFile() // List itself should contain the default values
        {
            // Check for nonexistent files (to speed things up)
            if (!File.Exists(SettingsFilePath))
            {
                return;
            }

            // Load values
            for (int i = 0; i < settings.Count; i++)
            {
                KeyValuePair <string, object> kvp = settings.ElementAt <KeyValuePair <string, object> >(i);

                string key   = kvp.Key;
                object value = kvp.Value;

                string type = Convert.ToString(kvp.GetType()).ToLowerInvariant();

                if (SettingsFileLowLevelIO.keyExistsInFile(key, SettingsFilePath))
                {
                    // Any errors triggered by the read... functions should NOT be handled here (so the programmer is notified of them)!
                    if (value is int)
                    {
                        value = SettingsFileLowLevelIO.readInteger(key, SettingsFilePath);
                    }
                    if (value is double)
                    {
                        value = SettingsFileLowLevelIO.readDouble(key, SettingsFilePath);
                    }
                    if (value is string)
                    {
                        value = SettingsFileLowLevelIO.readString(key, SettingsFilePath);
                    }
                    if (value is bool)
                    {
                        value = SettingsFileLowLevelIO.readBoolean(key, SettingsFilePath);
                    }
                }

                // Update value
                settings[key] = value;
            }
        }
        static void Main(string[] args)
        {
            KeyValuePair <string, int> testar = new KeyValuePair <string, int>();

            var s = testar.GetType().FullName;
            var l = Type.GetType(s);

            var path = AppDomain.CurrentDomain.BaseDirectory;
            var pos  = path.IndexOf(@"\src\Tools\");

            path = path.Substring(0, pos + 5);

            var destDir = Path.Combine(path, @"Server\OneTrueError.Web\Scripts\Models\");

            ResolvePath = Path.Combine(path, @"Server\OneTrueError.Api\bin\Debug");
            var srcPath = Path.Combine(path, @"Server\OneTrueError.Api\bin\Debug");

            AppDomain.CurrentDomain.AssemblyResolve += OnLoadAssembly;

            var assemblies  = Directory.GetFiles(srcPath, "*api*.dll").Select(Assembly.LoadFile);
            var nameFilters = assemblies.Select(x => x.GetName().Name).ToArray();

            //var nameFilters = new[]
            //{
            //    "OneTrueError.Core.WebApi",
            //    "OneTrueError.GlobalCore.WebApi",
            //    "OneTrueError.Core.Api",
            //    "OneTrueError.GlobalCore.Api",
            //    "OneTrueError"
            //};

            var tsGen = new TypescriptGenerator("OneTrueError", nameFilters);

            //tsGen.Generate(new[] { asm1, asm2 }, @"C:\temp\Typescript");
            tsGen.Generate(assemblies, destDir);
        }
        /// <summary>
        /// Converts simple primitives.
        /// </summary>
        /// <param name="pbfPrimitive"></param>
        /// <returns></returns>
        internal OsmSharp.Osm.OsmGeo Convert(KeyValuePair<PrimitiveBlock, object> pbfPrimitive)
        {
            if (pbfPrimitive.Value == null || pbfPrimitive.Key == null)
            {
                throw new ArgumentNullException("pbfPrimitive");
            }

            PrimitiveBlock block = pbfPrimitive.Key; // get the block properties this object comes from.
            if (pbfPrimitive.Value is OsmSharp.Osm.PBF.Node)
            {
                var node = (pbfPrimitive.Value as OsmSharp.Osm.PBF.Node);
                var simpleNode = new OsmSharp.Osm.Node();
                simpleNode.ChangeSetId = node.info.changeset;
                simpleNode.Id = node.id;
                simpleNode.Latitude = .000000001 * ((double)block.lat_offset
                    + ((double)block.granularity * (double)node.lat));
                simpleNode.Longitude = .000000001 * ((double)block.lon_offset
                    + ((double)block.granularity * (double)node.lon));
                if (node.keys.Count > 0)
                {
                    simpleNode.Tags = new TagsCollection();
                    for (int tag_idx = 0; tag_idx < node.keys.Count; tag_idx++)
                    {
                        string key = Encoding.UTF8.GetString(block.stringtable.s[(int)node.keys[tag_idx]]);
                        string value = Encoding.UTF8.GetString(block.stringtable.s[(int)node.vals[tag_idx]]);

                        if (!simpleNode.Tags.ContainsKey(key))
                        {
                            simpleNode.Tags.Add(new Tag() { Key = key, Value = value });
                        }
                    }
                }
                simpleNode.TimeStamp = Utilities.FromUnixTime((long)node.info.timestamp *
                    (long)block.date_granularity);
                simpleNode.Visible = true;
                simpleNode.Version = (uint)node.info.version;
                simpleNode.UserId = node.info.uid;
                simpleNode.UserName = Encoding.UTF8.GetString(block.stringtable.s[node.info.user_sid]);
                simpleNode.Version = (ulong)node.info.version;
                simpleNode.Visible = true;

                return simpleNode;
            }
            else if (pbfPrimitive.Value is OsmSharp.Osm.PBF.Way)
            {
                var way = (pbfPrimitive.Value as OsmSharp.Osm.PBF.Way);

                var simple_way = new OsmSharp.Osm.Way();
                simple_way.Id = way.id;
                simple_way.Nodes = new List<long>(way.refs.Count);
                long node_id = 0;
                for (int node_idx = 0; node_idx < way.refs.Count; node_idx++)
                {
                    node_id = node_id + way.refs[node_idx];
                    simple_way.Nodes.Add(node_id);
                }
                if (way.keys.Count > 0)
                {
                    simple_way.Tags = new TagsCollection();
                    for (int tag_idx = 0; tag_idx < way.keys.Count; tag_idx++)
                    {
                        string key = Encoding.UTF8.GetString(block.stringtable.s[(int)way.keys[tag_idx]]);
                        string value = Encoding.UTF8.GetString(block.stringtable.s[(int)way.vals[tag_idx]]);

                        if (!simple_way.Tags.ContainsKey(key))
                        {
                            simple_way.Tags.Add(new Tag(key, value));
                        }
                    }
                }
                if (way.info != null)
                { // add the metadata if any.
                    simple_way.ChangeSetId = way.info.changeset;
                    simple_way.TimeStamp = Utilities.FromUnixTime((long)way.info.timestamp *
                        (long)block.date_granularity);
                    simple_way.UserId = way.info.uid;
                    simple_way.UserName = Encoding.UTF8.GetString(block.stringtable.s[way.info.user_sid]);
                    simple_way.Version = (ulong)way.info.version;
                }
                simple_way.Visible = true;

                return simple_way;
            }
            else if (pbfPrimitive.Value is OsmSharp.Osm.PBF.Relation)
            {
                var relation = (pbfPrimitive.Value as OsmSharp.Osm.PBF.Relation);

                var simple_relation = new OsmSharp.Osm.Relation();
                simple_relation.Id = relation.id;
                if (relation.types.Count > 0)
                {
                    simple_relation.Members = new List<OsmSharp.Osm.RelationMember>();
                    long member_id = 0;
                    for (int member_idx = 0; member_idx < relation.types.Count; member_idx++)
                    {
                        member_id = member_id + relation.memids[member_idx];
                        string role = Encoding.UTF8.GetString(
                            block.stringtable.s[relation.roles_sid[member_idx]]);
                        var member = new OsmSharp.Osm.RelationMember();
                        member.MemberId = member_id;
                        member.MemberRole = role;
                        switch (relation.types[member_idx])
                        {
                            case Relation.MemberType.NODE:
                                member.MemberType = OsmSharp.Osm.OsmGeoType.Node;
                                break;
                            case Relation.MemberType.WAY:
                                member.MemberType = OsmSharp.Osm.OsmGeoType.Way;
                                break;
                            case Relation.MemberType.RELATION:
                                member.MemberType = OsmSharp.Osm.OsmGeoType.Relation;
                                break;
                        }

                        simple_relation.Members.Add(member);
                    }
                }
                if (relation.keys.Count > 0)
                {
                    simple_relation.Tags = new TagsCollection();
                    for (int tag_idx = 0; tag_idx < relation.keys.Count; tag_idx++)
                    {
                        string key = Encoding.UTF8.GetString(block.stringtable.s[(int)relation.keys[tag_idx]]);
                        string value = Encoding.UTF8.GetString(block.stringtable.s[(int)relation.vals[tag_idx]]);

                        if (!simple_relation.Tags.ContainsKey(key))
                        {
                            simple_relation.Tags.Add(new Tag(key, value));
                        }
                    }
                }
                if (relation.info != null)
                { // read metadata if any.
                    simple_relation.ChangeSetId = relation.info.changeset;
                    simple_relation.TimeStamp = Utilities.FromUnixTime((long)relation.info.timestamp *
                        (long)block.date_granularity);
                    simple_relation.UserId = relation.info.uid;
                    simple_relation.UserName = Encoding.UTF8.GetString(block.stringtable.s[relation.info.user_sid]);
                    simple_relation.Version = (ulong)relation.info.version;
                }
                simple_relation.Visible = true;

                return simple_relation;
            }
            throw new Exception(string.Format("PBF primitive with type {0} not supported!",
                pbfPrimitive.GetType().ToString()));
        }
Exemple #14
0
        static CodeTypeDeclaration _CreateParserClass(Cfg cfg, string name)
        {
            var sm   = new Dictionary <string, int>();
            var ii   = 0;
            var syms = new List <string>();

            cfg.FillSymbols(syms);


            foreach (var sym in syms)
            {
                sm.Add(sym, ii);
                ++ii;
            }
            var pt        = cfg.ToLL1ParseTable();
            var ipt       = pt.ToLL1Array(syms);
            var nodeFlags = new int[syms.Count];

            for (var i = 0; i < nodeFlags.Length; ++i)
            {
                var o = cfg.AttributeSets.GetAttribute(syms[i], "hidden", false);
                if (o is bool && (bool)o)
                {
                    nodeFlags[i] |= 2;
                }
                o = cfg.AttributeSets.GetAttribute(syms[i], "collapsed", false);
                if (o is bool && (bool)o)
                {
                    nodeFlags[i] |= 1;
                }
            }
            var attrSets = new KeyValuePair <string, object> [syms.Count][];

            for (ii = 0; ii < attrSets.Length; ii++)
            {
                AttributeSet attrs;
                if (cfg.AttributeSets.TryGetValue(syms[ii], out attrs))
                {
                    attrSets[ii] = new KeyValuePair <string, object> [attrs.Count];
                    var j = 0;
                    foreach (var attr in attrs)
                    {
                        attrSets[ii][j] = new KeyValuePair <string, object>(attr.Key, attr.Value);
                        ++j;
                    }
                }
                else
                {
                    attrSets[ii] = null;                    // new KeyValuePair<string, object>[0];
                }
            }


            var result = new CodeTypeDeclaration();

            result.Name       = name;
            result.Attributes = MemberAttributes.FamilyOrAssembly;
            result.BaseTypes.Add(typeof(LL1TableParser));
            CodeMemberField f;

            foreach (var s in syms)
            {
                if (null != s)
                {
                    f                = new CodeMemberField();
                    f.Attributes     = MemberAttributes.Const | MemberAttributes.Public;
                    f.Name           = s.Replace("#", "_").Replace("'", "_").Replace("<", "_").Replace(">", "_");
                    f.Type           = new CodeTypeReference(typeof(int));
                    f.InitExpression = CodeDomUtility.Serialize(cfg.GetIdOfSymbol(s));
                    result.Members.Add(f);
                }
            }
            f                = new CodeMemberField();
            f.Attributes     = MemberAttributes.Static;
            f.Name           = "_Symbols";
            f.Type           = new CodeTypeReference(typeof(string[]));
            f.InitExpression = CodeDomUtility.Serialize(syms.ToArray());
            result.Members.Add(f);

            f                = new CodeMemberField();
            f.Attributes     = MemberAttributes.Static;
            f.Name           = "_ParseTable";
            f.Type           = new CodeTypeReference(typeof(int[][][]));
            f.InitExpression = CodeDomUtility.Serialize(ipt);
            result.Members.Add(f);

            f                = new CodeMemberField();
            f.Attributes     = MemberAttributes.Static;
            f.Name           = "_InitCfg";
            f.Type           = new CodeTypeReference(typeof(int[]));
            f.InitExpression = CodeDomUtility.Serialize(new int[] { cfg.GetIdOfSymbol(cfg.StartSymbol), cfg.FillNonTerminals().Count });
            result.Members.Add(f);

            f                = new CodeMemberField();
            f.Attributes     = MemberAttributes.Static;
            f.Name           = "_NodeFlags";
            f.Type           = new CodeTypeReference(typeof(int[]));
            f.InitExpression = CodeDomUtility.Serialize(nodeFlags);
            result.Members.Add(f);

            f                = new CodeMemberField();
            f.Attributes     = MemberAttributes.Static;
            f.Name           = "_AttributeSets";
            f.Type           = new CodeTypeReference(attrSets.GetType());
            f.InitExpression = CodeDomUtility.Serialize(attrSets);
            result.Members.Add(f);

            var ctor = new CodeConstructor();

            ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IEnumerable <Token>), "tokenizer"));
            ctor.BaseConstructorArgs.AddRange(new CodeExpression[] {
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(result.Name), "_ParseTable"),
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(result.Name), "_InitCfg"),
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(result.Name), "_Symbols"),
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(result.Name), "_NodeFlags"),
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(result.Name), "_AttributeSets"),
                new CodeArgumentReferenceExpression("tokenizer")
            });
            ctor.Attributes = MemberAttributes.Public;
            result.Members.Add(ctor);
            return(result);
        }
Exemple #15
0
        static IList <CfgMessage> _CreateParserClass(CfgDocument cfg, string name, IProgress <CfgLL1Progress> progress, out CodeTypeDeclaration parserClass)
        {
            var result = new List <CfgMessage>();
            var sm     = new Dictionary <string, int>();
            var ii     = 0;
            var syms   = new List <string>();

            cfg.FillSymbols(syms);


            foreach (var sym in syms)
            {
                sm.Add(sym, ii);
                ++ii;
            }
            CfgLL1ParseTable pt;

            result.AddRange(cfg.TryToLL1ParseTable(progress, out pt));
            var hasErrors = false;

            foreach (var msg in result)
            {
                if (CfgErrorLevel.Error == msg.ErrorLevel)
                {
                    hasErrors = true;
                    break;
                }
            }
            if (!hasErrors)
            {
                var ipt       = pt.ToArray(syms);
                var nodeFlags = new int[syms.Count];
                for (var i = 0; i < nodeFlags.Length; ++i)
                {
                    var o = cfg.GetAttribute(syms[i], "hidden", false);
                    if (o is bool && (bool)o)
                    {
                        nodeFlags[i] |= 2;
                    }
                    o = cfg.GetAttribute(syms[i], "collapsed", false);
                    if (o is bool && (bool)o)
                    {
                        nodeFlags[i] |= 1;
                    }
                }
                var substitutions = new int[syms.Count];
                for (var i = 0; i < substitutions.Length; i++)
                {
                    var s = cfg.GetAttribute(syms[i], "substitute", null) as string;
                    if (!string.IsNullOrEmpty(s) && cfg.IsSymbol(s) && s != syms[i])
                    {
                        substitutions[i] = cfg.GetIdOfSymbol(s);
                    }
                    else
                    {
                        substitutions[i] = -1;
                    }
                }
                var attrSets = new KeyValuePair <string, object> [syms.Count][];
                for (ii = 0; ii < attrSets.Length; ii++)
                {
                    CfgAttributeList attrs;
                    if (cfg.AttributeSets.TryGetValue(syms[ii], out attrs))
                    {
                        attrSets[ii] = new KeyValuePair <string, object> [attrs.Count];
                        var j = 0;
                        foreach (var attr in attrs)
                        {
                            attrSets[ii][j] = new KeyValuePair <string, object>(attr.Name, attr.Value);
                            ++j;
                        }
                    }
                    else
                    {
                        attrSets[ii] = null;
                    }
                }


                parserClass            = new CodeTypeDeclaration();
                parserClass.Name       = name;
                parserClass.Attributes = MemberAttributes.FamilyOrAssembly;
                parserClass.BaseTypes.Add(typeof(LL1TableParser));
                CodeMemberField f;
                foreach (var s in syms)
                {
                    if (null != s)
                    {
                        f                = new CodeMemberField();
                        f.Attributes     = MemberAttributes.Const | MemberAttributes.Public;
                        f.Name           = s.Replace("#", "_").Replace("'", "_").Replace("<", "_").Replace(">", "_");
                        f.Type           = new CodeTypeReference(typeof(int));
                        f.InitExpression = CodeDomUtility.Serialize(cfg.GetIdOfSymbol(s));
                        parserClass.Members.Add(f);
                    }
                }
                f                = new CodeMemberField();
                f.Attributes     = MemberAttributes.Static;
                f.Name           = "_Symbols";
                f.Type           = new CodeTypeReference(typeof(string[]));
                f.InitExpression = CodeDomUtility.Serialize(syms.ToArray());
                parserClass.Members.Add(f);

                f                = new CodeMemberField();
                f.Attributes     = MemberAttributes.Static;
                f.Name           = "_ParseTable";
                f.Type           = new CodeTypeReference(typeof(int[][][]));
                f.InitExpression = CodeDomUtility.Serialize(ipt);
                parserClass.Members.Add(f);

                f                = new CodeMemberField();
                f.Attributes     = MemberAttributes.Static;
                f.Name           = "_InitCfg";
                f.Type           = new CodeTypeReference(typeof(int[]));
                f.InitExpression = CodeDomUtility.Serialize(new int[] { cfg.GetIdOfSymbol(cfg.StartSymbol), cfg.FillNonTerminals().Count });
                parserClass.Members.Add(f);

                f                = new CodeMemberField();
                f.Attributes     = MemberAttributes.Static;
                f.Name           = "_NodeFlags";
                f.Type           = new CodeTypeReference(typeof(int[]));
                f.InitExpression = CodeDomUtility.Serialize(nodeFlags);
                parserClass.Members.Add(f);

                f                = new CodeMemberField();
                f.Attributes     = MemberAttributes.Static;
                f.Name           = "_Substitutions";
                f.Type           = new CodeTypeReference(typeof(int[]));
                f.InitExpression = CodeDomUtility.Serialize(substitutions);
                parserClass.Members.Add(f);

                f                = new CodeMemberField();
                f.Attributes     = MemberAttributes.Static;
                f.Name           = "_AttributeSets";
                f.Type           = new CodeTypeReference(attrSets.GetType());
                f.InitExpression = CodeDomUtility.Serialize(attrSets);
                parserClass.Members.Add(f);

                var ctor = new CodeConstructor();
                ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IEnumerable <Token>), "tokenizer"));
                ctor.BaseConstructorArgs.AddRange(new CodeExpression[] {
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(parserClass.Name), "_ParseTable"),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(parserClass.Name), "_InitCfg"),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(parserClass.Name), "_Symbols"),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(parserClass.Name), "_NodeFlags"),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(parserClass.Name), "_Substitutions"),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(parserClass.Name), "_AttributeSets"),
                    new CodeArgumentReferenceExpression("tokenizer")
                });
                ctor.Attributes = MemberAttributes.Public;
                parserClass.Members.Add(ctor);
                ctor = new CodeConstructor();
                ctor.ChainedConstructorArgs.AddRange(new CodeExpression[] { new CodePrimitiveExpression(null) });
                ctor.Attributes = MemberAttributes.Public;
                parserClass.Members.Add(ctor);
            }
            else
            {
                parserClass = null;
            }
            return(result);
        }
        /// <summary>
        /// Converts simple primitives.
        /// </summary>
        /// <param name="pbfPrimitive"></param>
        /// <returns></returns>
        internal OsmSharp.Osm.OsmGeo Convert(KeyValuePair <PrimitiveBlock, object> pbfPrimitive)
        {
            if (pbfPrimitive.Value == null || pbfPrimitive.Key == null)
            {
                throw new ArgumentNullException("pbfPrimitive");
            }

            PrimitiveBlock block = pbfPrimitive.Key; // get the block properties this object comes from.

            if (pbfPrimitive.Value is OsmSharp.Osm.Data.PBF.Node)
            {
                var node       = (pbfPrimitive.Value as OsmSharp.Osm.Data.PBF.Node);
                var simpleNode = new OsmSharp.Osm.Node();
                simpleNode.ChangeSetId = node.info.changeset;
                simpleNode.Id          = node.id;
                simpleNode.Latitude    = .000000001 * ((double)block.lat_offset
                                                       + ((double)block.granularity * (double)node.lat));
                simpleNode.Longitude = .000000001 * ((double)block.lon_offset
                                                     + ((double)block.granularity * (double)node.lon));
                if (node.keys.Count > 0)
                {
                    simpleNode.Tags = new SimpleTagsCollection();
                    for (int tag_idx = 0; tag_idx < node.keys.Count; tag_idx++)
                    {
                        string key   = ASCIIEncoding.ASCII.GetString(block.stringtable.s[(int)node.keys[tag_idx]]);
                        string value = ASCIIEncoding.ASCII.GetString(block.stringtable.s[(int)node.vals[tag_idx]]);

                        if (!simpleNode.Tags.ContainsKey(key))
                        {
                            simpleNode.Tags.Add(new Tag()
                            {
                                Key = key, Value = value
                            });
                        }
                    }
                }
                simpleNode.TimeStamp = Utilities.FromUnixTime((long)node.info.timestamp *
                                                              (long)block.date_granularity);
                simpleNode.Visible  = true;
                simpleNode.Version  = (uint)node.info.version;
                simpleNode.UserId   = node.info.uid;
                simpleNode.UserName = ASCIIEncoding.ASCII.GetString(block.stringtable.s[node.info.user_sid]);
                simpleNode.Version  = (ulong)node.info.version;
                simpleNode.Visible  = true;

                return(simpleNode);
            }
            else if (pbfPrimitive.Value is OsmSharp.Osm.Data.PBF.Way)
            {
                var way = (pbfPrimitive.Value as OsmSharp.Osm.Data.PBF.Way);

                var simple_way = new OsmSharp.Osm.Way();
                simple_way.Id    = way.id;
                simple_way.Nodes = new List <long>(way.refs.Count);
                long node_id = 0;
                for (int node_idx = 0; node_idx < way.refs.Count; node_idx++)
                {
                    node_id = node_id + way.refs[node_idx];
                    simple_way.Nodes.Add(node_id);
                }
                if (way.keys.Count > 0)
                {
                    simple_way.Tags = new SimpleTagsCollection();
                    for (int tag_idx = 0; tag_idx < way.keys.Count; tag_idx++)
                    {
                        string key   = ASCIIEncoding.ASCII.GetString(block.stringtable.s[(int)way.keys[tag_idx]]);
                        string value = ASCIIEncoding.ASCII.GetString(block.stringtable.s[(int)way.vals[tag_idx]]);

                        if (!simple_way.Tags.ContainsKey(key))
                        {
                            simple_way.Tags.Add(new Tag(key, value));
                        }
                    }
                }
                if (way.info != null)
                { // add the metadata if any.
                    simple_way.ChangeSetId = way.info.changeset;
                    simple_way.TimeStamp   = Utilities.FromUnixTime((long)way.info.timestamp *
                                                                    (long)block.date_granularity);
                    simple_way.UserId   = way.info.uid;
                    simple_way.UserName = ASCIIEncoding.ASCII.GetString(block.stringtable.s[way.info.user_sid]);
                    simple_way.Version  = (ulong)way.info.version;
                }
                simple_way.Visible = true;

                return(simple_way);
            }
            else if (pbfPrimitive.Value is OsmSharp.Osm.Data.PBF.Relation)
            {
                var relation = (pbfPrimitive.Value as OsmSharp.Osm.Data.PBF.Relation);

                var simple_relation = new OsmSharp.Osm.Relation();
                simple_relation.Id = relation.id;
                if (relation.types.Count > 0)
                {
                    simple_relation.Members = new List <OsmSharp.Osm.RelationMember>();
                    long member_id = 0;
                    for (int member_idx = 0; member_idx < relation.types.Count; member_idx++)
                    {
                        member_id = member_id + relation.memids[member_idx];
                        string role = ASCIIEncoding.ASCII.GetString(
                            block.stringtable.s[relation.roles_sid[member_idx]]);
                        var member = new OsmSharp.Osm.RelationMember();
                        member.MemberId   = member_id;
                        member.MemberRole = role;
                        switch (relation.types[member_idx])
                        {
                        case Relation.MemberType.NODE:
                            member.MemberType = OsmSharp.Osm.OsmGeoType.Node;
                            break;

                        case Relation.MemberType.WAY:
                            member.MemberType = OsmSharp.Osm.OsmGeoType.Way;
                            break;

                        case Relation.MemberType.RELATION:
                            member.MemberType = OsmSharp.Osm.OsmGeoType.Relation;
                            break;
                        }

                        simple_relation.Members.Add(member);
                    }
                }
                if (relation.keys.Count > 0)
                {
                    simple_relation.Tags = new SimpleTagsCollection();
                    for (int tag_idx = 0; tag_idx < relation.keys.Count; tag_idx++)
                    {
                        string key   = ASCIIEncoding.ASCII.GetString(block.stringtable.s[(int)relation.keys[tag_idx]]);
                        string value = ASCIIEncoding.ASCII.GetString(block.stringtable.s[(int)relation.vals[tag_idx]]);

                        if (!simple_relation.Tags.ContainsKey(key))
                        {
                            simple_relation.Tags.Add(new Tag(key, value));
                        }
                    }
                }
                if (relation.info != null)
                { // read metadata if any.
                    simple_relation.ChangeSetId = relation.info.changeset;
                    simple_relation.TimeStamp   = Utilities.FromUnixTime((long)relation.info.timestamp *
                                                                         (long)block.date_granularity);
                    simple_relation.UserId   = relation.info.uid;
                    simple_relation.UserName = ASCIIEncoding.ASCII.GetString(block.stringtable.s[relation.info.user_sid]);
                    simple_relation.Version  = (ulong)relation.info.version;
                }
                simple_relation.Visible = true;

                return(simple_relation);
            }
            throw new Exception(string.Format("PBF primitive with type {0} not supported!",
                                              pbfPrimitive.GetType().ToString()));
        }
        public void GenericToDefinitionMatchesTypeOfDefinition()
        {
            var x = new KeyValuePair <int, string>();

            AssertEquals(typeof(KeyValuePair <,>), x.GetType().GetGenericTypeDefinition());
        }
Exemple #18
0
        /// <summary></summary>
        public static void Test()
        {
            XTrace.WriteLine("创建类型……");

            #region TypeX类型
            TypeX  type = TypeX.Create(typeof(FastTest));
            Object obj  = type.CreateInstance();
            Debug.Assert(obj != null, "创建实例出错!");

            obj = type.CreateInstance(123);
            Debug.Assert(obj != null, "创建实例出错!");

            //obj = type.CreateInstance("1234");
            //Debug.Assert(obj != null, "创建实例出错!");

            obj = type.CreateInstance(111, "aaa");
            Debug.Assert(obj != null, "创建实例出错!");

            XTrace.WriteLine("创建值类型实例");
            type = TypeX.Create(typeof(ConsoleKeyInfo));
            obj  = type.CreateInstance();
            Debug.Assert(obj != null, "创建值类型实例出错!");

            XTrace.WriteLine("创建数组类型实例");
            type = TypeX.Create(typeof(ConsoleKeyInfo[]));
            obj  = type.CreateInstance(5);
            Debug.Assert(obj != null, "创建数组类型实例出错!");
            #endregion

            #region 构造函数
            ConstructorInfoX ctr = ConstructorInfoX.Create(typeof(FastTest));
            obj = ctr.CreateInstance();
            Debug.Assert(obj != null, "创建实例出错!");

            ctr = ConstructorInfoX.Create(typeof(FastTest), new Type[] { typeof(Int32) });
            obj = ctr.CreateInstance(123);
            Debug.Assert(obj != null, "创建实例出错!");
            ctr = ConstructorInfoX.Create(typeof(FastTest), new Type[] { typeof(Int32), typeof(String) });
            obj = ctr.CreateInstance(111, "aaa");
            Debug.Assert(obj != null, "创建实例出错!");
            #endregion

            #region 字段
            FieldInfoX field = FieldInfoX.Create(typeof(FastTest), "_ID");
            (obj as FastTest).ID = 111;
            Int32 v = (Int32)field.GetValue(obj);
            Debug.Assert(v == 111, "字段取值出错!");
            field.SetValue(obj, 888);
            v = (Int32)field.GetValue(obj);
            Debug.Assert(v == 888, "字段赋值出错!");

            KeyValuePair <Int32, Int32> kv = new KeyValuePair <int, int>(123456, 222);
            field = FieldInfoX.Create(kv.GetType(), "Key");
            //field.SetValue(kv, 123456);
            v = (Int32)field.GetValue(kv);
            Debug.Assert(v == 123456, "字段取值出错!");

            field = FieldInfoX.Create(typeof(FastTest), "_Name");
            field.SetValue("动态赋值");
            String v2 = (String)field.GetValue();
            Debug.Assert(v2 == "动态赋值", "静态字段出错!");
            #endregion

            #region 属性
            PropertyInfoX p = typeof(FastTest).GetProperty("ID");

            v = (Int32)p.GetValue(obj);
            Debug.Assert(v == 888, "属性取值出错!");
            p.SetValue(obj, 999);
            v = (Int32)p.GetValue(obj);
            Debug.Assert(v == 999, "属性赋值出错!");

            p = PropertyInfoX.Create(typeof(FastTest), "Name");
            field.SetValue("属性动态赋值");
            v2 = (String)field.GetValue();
            Debug.Assert(v2 == "属性动态赋值", "静态字段出错!");
            #endregion

            #region 方法
            MethodInfoX method = MethodInfoX.Create(typeof(FastTest), "Test2");
            method.Invoke(obj);

            method = typeof(FastTest).GetMethod("GetFullName");
            Console.WriteLine(method.Invoke(null, 123, "abc"));
            #endregion
        }
Exemple #19
0
        /// <summary></summary>
        public static void Test()
        {
            XTrace.WriteLine("创建类型……");

            #region TypeX类型
            TypeX type = TypeX.Create(typeof(FastTest));
            Object obj = type.CreateInstance();
            Debug.Assert(obj != null, "创建实例出错!");

            obj = type.CreateInstance(123);
            Debug.Assert(obj != null, "创建实例出错!");

            //obj = type.CreateInstance("1234");
            //Debug.Assert(obj != null, "创建实例出错!");

            obj = type.CreateInstance(111, "aaa");
            Debug.Assert(obj != null, "创建实例出错!");

            XTrace.WriteLine("创建值类型实例");
            type = TypeX.Create(typeof(ConsoleKeyInfo));
            obj = type.CreateInstance();
            Debug.Assert(obj != null, "创建值类型实例出错!");

            XTrace.WriteLine("创建数组类型实例");
            type = TypeX.Create(typeof(ConsoleKeyInfo[]));
            obj = type.CreateInstance(5);
            Debug.Assert(obj != null, "创建数组类型实例出错!");
            #endregion

            #region 构造函数
            ConstructorInfoX ctr = ConstructorInfoX.Create(typeof(FastTest));
            obj = ctr.CreateInstance();
            Debug.Assert(obj != null, "创建实例出错!");

            ctr = ConstructorInfoX.Create(typeof(FastTest), new Type[] { typeof(Int32) });
            obj = ctr.CreateInstance(123);
            Debug.Assert(obj != null, "创建实例出错!");
            ctr = ConstructorInfoX.Create(typeof(FastTest), new Type[] { typeof(Int32), typeof(String) });
            obj = ctr.CreateInstance(111, "aaa");
            Debug.Assert(obj != null, "创建实例出错!");
            #endregion

            #region 字段
            FieldInfoX field = FieldInfoX.Create(typeof(FastTest), "_ID");
            (obj as FastTest).ID = 111;
            Int32 v = (Int32)field.GetValue(obj);
            Debug.Assert(v == 111, "字段取值出错!");
            field.SetValue(obj, 888);
            v = (Int32)field.GetValue(obj);
            Debug.Assert(v == 888, "字段赋值出错!");

            KeyValuePair<Int32, Int32> kv = new KeyValuePair<int, int>(123456, 222);
            field = FieldInfoX.Create(kv.GetType(), "Key");
            //field.SetValue(kv, 123456);
            v = (Int32)field.GetValue(kv);
            Debug.Assert(v == 123456, "字段取值出错!");

            field = FieldInfoX.Create(typeof(FastTest), "_Name");
            field.SetValue("动态赋值");
            String v2 = (String)field.GetValue();
            Debug.Assert(v2 == "动态赋值", "静态字段出错!");
            #endregion

            #region 属性
            PropertyInfoX p = typeof(FastTest).GetProperty("ID");

            v = (Int32)p.GetValue(obj);
            Debug.Assert(v == 888, "属性取值出错!");
            p.SetValue(obj, 999);
            v = (Int32)p.GetValue(obj);
            Debug.Assert(v == 999, "属性赋值出错!");

            p = PropertyInfoX.Create(typeof(FastTest), "Name");
            field.SetValue("属性动态赋值");
            v2 = (String)field.GetValue();
            Debug.Assert(v2 == "属性动态赋值", "静态字段出错!");
            #endregion

            #region 方法
            MethodInfoX method = MethodInfoX.Create(typeof(FastTest), "Test2");
            method.Invoke(obj);

            method = typeof(FastTest).GetMethod("GetFullName");
            Console.WriteLine(method.Invoke(null, 123, "abc"));
            #endregion
        }
Exemple #20
0
        public void KeyValuePairTiposBasicos()
        {
            KeyValuePair <long, string> pair         = new KeyValuePair <long, string>(125, "Gabriel");
            ElementoBinario             serializador = ElementoBinario.GetSerializador(pair.GetType());

            byte[] data = serializador.GetBytes(pair);
            KeyValuePair <long, string> pairDeserializada = (KeyValuePair <long, string>)serializador.GetObject(data);

            Assert.IsTrue(pair.Key.Equals(pairDeserializada.Key) && pair.Value.Equals(pairDeserializada.Value));
        }