Exemple #1
0
        /// <summary>
        /// Registers all <see cref="Packet"/> inheritors in the given <see cref="Assembly"/> with this <see cref="Connection"/>. Should this method be called manually, it must be called on both the server and client so that all <see cref="Packet"/> s in use are known to all parties (avoids incompatible states; exception thrown otherwise).
        /// <para> 使用此 <see cref="Connection"/> 注册给定 <see cref="Assembly"/> 中的所有 <see cref="Packet"/> 继承者。如果应该手动调用此方法,则必须在服务器和客户端上都调用此方法,以便各方都知道正在使用的所有 <see cref="Packet"/>(避免出现不兼容的状态;否则抛出异常)。 </para>
        /// </summary>
        /// <param name="assembly"> The <see cref="Assembly"/> to search in for inheritors of <see cref="Packet"/>. </param>

        /// <remarks>
        /// All packets in the network lib are included by default. A manual call is not essential, even if the used packets are not included, as the library will attempt to synchronise known <see cref="Packet"/> s between the server and client automatically.
        /// <para> 默认情况下包括网络库中的所有数据包。即使不包括使用的数据包,手动调用也不是必需的,因为库将尝试在服务器和客户端之间同步已知的 <see cref="Packet"/> </para>
        /// </remarks>

        internal void AddExternalPackets(Assembly assembly)
        {
            assembly.GetTypes().ToList().Where(c => c.IsSubclassOf(typeof(Packet))).ToList().ForEach(p =>
            {
                if (typeByte.ContainsKey(p))
                {
                    return;                          //Already in the dictionary.
                }
                ushort packetId = (ushort)Interlocked.Increment(ref currentTypeByteIndex);
                Attribute packetTypeAttribute = p.GetCustomAttribute(typeof(PacketTypeAttribute));
                //Apply the local ID if there exist any.
                if (packetTypeAttribute != null)
                {
                    packetId = ((PacketTypeAttribute)packetTypeAttribute).Id;
                }
                typeByte[p] = packetId;
            });

            //检索应用于指定成员的指定类型的自定义属性的集合。
            assembly.GetTypes().ToList().Where(c => c.GetCustomAttributes(typeof(PacketRequestAttribute)).Count() > 0).ToList().
            ForEach(c =>
            {
                PacketRequestAttribute requestAttribute = ((PacketRequestAttribute)c.GetCustomAttribute(typeof(PacketRequestAttribute)));
                // TryAdd will fail if another thread investigates the object. However, it turned out, that somehow the RequestType has been already added to the requestResponseMap. Hence, we can ignore the failure.
                if (!requestResponseMap.ContainsKey(requestAttribute.RequestType))
                {
                    requestResponseMap.Add(requestAttribute.RequestType, c);
                }
            });
        }
 public void RegisterTile(Vector3Int position, NavNode navNode)
 {
     if (!map.ContainsKey(position))
     {
         map.Add(position, navNode);
     }
 }
        public void TestContains()
        {
            Assert.IsTrue(_biDictionary.Contains(new KeyValuePair <int, double>(10, 5.0)));
            Assert.IsTrue(_biDictionary.Contains(new KeyValuePair <double, int>(5.0, 10)));

            Assert.IsTrue(_biDictionary.ContainsKey(10));
            Assert.IsTrue(_biDictionary.ContainsValue(5.0));

            Assert.IsTrue(_biDictionary.ContainsKey(5.0));
            Assert.IsTrue(_biDictionary.ContainsValue(10));
        }
        public void BiDictionaryTest_containsKey_simple()
        {
            var biDictionary = new BiDictionary <Vector2Int, Vector2Int>
            {
                { new Vector2Int(5, 5), new Vector2Int(4, 4) },
                { new Vector2Int(6, 6), new Vector2Int(3, 3) },
                { new Vector2Int(7, 7), new Vector2Int(2, 2) }
            };

            Assert.IsTrue(biDictionary.ContainsKey(new Vector2Int(5, 5)));
            Assert.IsFalse(biDictionary.ContainsKey(new Vector2Int(4, 4)));
        }
Exemple #5
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        bool DoAddEntry(DataStoreEntry entry)
        {
            entry.Initialize(_dataStoreFilesFolder);

            lock (_entriesAndSessions)
            {
                if (_entriesAndSessions.ContainsKey(entry))
                {
                    SystemMonitor.OperationWarning("Entry already added.");
                    return(false);
                }

                if (entry.Symbol.IsEmpty)
                {
                    SystemMonitor.Warning("Entry added before initialized.");
                    return(false);
                }

                // The sessionInformation reuses the entry Guid, so that it can be easily persisted further.
                DataSessionInfo entrySessionInfo = new DataSessionInfo(entry.Guid, "Data Store Session [" + entry.Symbol.Name + "]",
                                                                       entry.Symbol, DefaultSessionLotSize, entry.DecimalDigits);

                RuntimeDataSessionInformation session = new RuntimeDataSessionInformation(entrySessionInfo, entry.Period.Value);
                _entriesAndSessions.Add(entry, session);
            }

            return(true);
        }
        void RegisterClientId(int socketClientId, ClientId id, Type type, List <string> sourceTypeNames)
        {
            // Remove the index, that was valid for the remote bus, we use this as pure Id only.
            id.LocalMessageBusIndex = ClientId.InvalidMessageBusClientIndex;

            bool newlyAdded = false;

            lock (_syncRoot)
            {
                // Update all of the remote client state collections.
                newlyAdded = (_remoteClientNetId.ContainsKey(id) == false);

                _remoteClientNetId[id]              = socketClientId;
                _remoteClientsTypes[id]             = type;
                _remoteClientsSourcesTypesNames[id] = sourceTypeNames;

                if (_remoteClientsNetIds.ContainsKey(socketClientId) == false)
                {
                    _remoteClientsNetIds.Add(socketClientId, new ListUnique <ClientId>());
                }

                _remoteClientsNetIds[socketClientId].Add(id);
            }

            if (newlyAdded)
            {
                RaiseClientAddedEvent(id);
            }
        }
Exemple #7
0
 private static void Register(Type t)
 {
     if (RegisterCount > ushort.MaxValue)
     {
         throw new System.Exception(string.Format("Cannot register more than {0} types of data.", ushort.MaxValue + 1));
     }
     if (RegisteredData.ContainsKey(t))
     {
         return;
     }
     RegisteredData.Add(t, RegisterCount++);
 }
    public static void Main()
    {
        var biDictionary = new BiDictionary <int, string, int>();

        biDictionary.Add(3, "da", 3);
        biDictionary.Add(2, "da", 5);
        biDictionary.Add(1, "da", 4);
        biDictionary.Add(3, "da", 5);
        Console.WriteLine(biDictionary.ContainsKey("da"));
        Console.WriteLine(biDictionary.GetValuesByKey("da"));
        Console.WriteLine(biDictionary.GetValuesByKeys(3, "da"));
    }
Exemple #9
0
        public void BiDictionaryTest()
        {
            BiDictionary <int, string, double> test1 = new BiDictionary <int, string, double>()
            {
                { 1, "first", 1.0 },
                { 2, "second", 2.0 },
                { 3, "third", 3.0 }
            };

            test1.Add(4, "fourth", 4.0);

            Assert.AreEqual(test1.ByKey1[1], 1.0);
            Assert.AreEqual(test1.ByKey2["first"], 1.0);

            Assert.IsTrue(test1.ContainsKey(1));
            Assert.IsTrue(test1.ContainsKey("first"));
            Assert.IsTrue(test1.ContainsKey(2));
            Assert.IsTrue(test1.ContainsKey(3));
            Assert.IsTrue(test1.ContainsKey(4));

            Assert.IsTrue(test1.ContainsValue(4.0));
        }
Exemple #10
0
        public PackedValue Register(ObjectRef obj)
        {
            if (obj.IsNull)
            {
                return(0);
            }
            if (String.IsNullOrEmpty(obj.ModName) || obj.Mod == PrismApi.VanillaInfo)
            {
                return(unchecked ((PackedValue)GetVanillaID(obj))); // vanilla - no need to register
            }
            ModName mn = obj.ModName;
            ModID   mid;

            if (Mods.ContainsKey(mn))
            {
                mid = Mods.Forward[mn];
            }
            else
            {
                mid = (ModID)Mods.Count;
                Mods.Add(mn, mid);

                ModObjects.Add(mid, new BiDictionary <ObjName, ObjID>());
            }

            ObjName on = obj.Name;
            ObjID   oid;

            var mod = ModObjects[mid];

            if (mod.ContainsKey(on))
            {
                oid = mod[on];
            }
            else
            {
                oid = (ObjID)mod.Count;
                mod.Add(on, oid);
            }

#pragma warning disable 675
            return(unchecked ((PackedValue)oid | ((PackedValue)mid << 8 * sizeof(ObjID)) | IsModFlag));

#pragma warning restore 675
        }
        private void CloneCollectionsUpdate <T>(T entityCollection) where T : class
        {
            var type = entityCollection.GetType();

            if (!typeof(IEnumerable).IsAssignableFrom(type))
            {
                return;
            }

            var  collectionType = type.GetGenericTypeDefinition();
            Type genericType    = collectionType.MakeGenericType(type.GetGenericArguments());

            if (!typeof(IList).IsAssignableFrom(collectionType))
            {
                throw new NotSupportedException("Uncertain of what other collection types to handle.");
            }

            var repoEntityCollection = (IList)entityToRepoEntityMap[entityCollection];

            var unremovedRepoEntities = new List <object>();

            foreach (var item in (IEnumerable)entityCollection)
            {
                if (!entityToRepoEntityMap.ContainsKey(item))
                {
                    repoEntityCollection.Add(item.Clone(entityToRepoEntityMap));
                }
                unremovedRepoEntities.Add(entityToRepoEntityMap[item]);
            }

            var removeRepoEntities = new List <object>(((IEnumerable <object>)repoEntityCollection).Except(unremovedRepoEntities));

            foreach (var item in removeRepoEntities)
            {
                repoEntityCollection.Remove(item);
            }
        }
        /**
         * <summary>Creates the character code mapping for composite fonts.</summary>
         */
        private void Load_CreateEncoding(
            PdfDictionary font,
            PdfDictionary cidFont
            )
        {
            /*
             * NOTE: Composite fonts map text shown by content stream strings through a 2-level encoding
             * scheme:
             *  character code -> CID (character index) -> GID (glyph index)
             * This works for rendering purposes, but if we want our text data to be intrinsically meaningful,
             * we need a further mapping towards some standard character identification scheme (Unicode):
             *  Unicode <- character code -> CID -> GID
             * Such mapping may be provided by a known CID collection or (in case of custom encodings like
             * Identity-H) by an explicit ToUnicode CMap.
             * CID -> GID mapping is typically identity, that is CIDS correspond to GIDS, so we don't bother
             * about that. Our base encoding is Identity-H, that is character codes correspond to CIDs;
             * however, sometimes a font maps multiple Unicode codepoints to the same GID (for example, the
             * hyphen glyph may be associated to the hyphen (\u2010) and minus (\u002D) symbols), breaking
             * the possibility to recover their original Unicode values once represented as character codes
             * in content stream strings. In this case, we are forced to remap the exceeding codes and
             * generate an explicit CMap (TODO: I tried to emit a differential CMap using the usecmap
             * operator in order to import Identity-H as base encoding, but it failed in several engines
             * (including Acrobat, Ghostscript, Poppler, whilst it surprisingly worked with pdf.js), so we
             * have temporarily to stick with full CMaps).
             */

            // Encoding [PDF:1.7:5.6.1,5.6.4].
            PdfDirectObject encodingObject = PdfName.IdentityH;
            SortedDictionary <ByteArray, int> sortedCodes;

            {
                codes = new BiDictionary <ByteArray, int>(glyphIndexes.Count);
                int         lastRemappedCharCodeValue = 0;
                IList <int> removedGlyphIndexKeys     = null;
                foreach (KeyValuePair <int, int> glyphIndexEntry in glyphIndexes.ToList())
                {
                    int       glyphIndex = glyphIndexEntry.Value;
                    ByteArray charCode   = new ByteArray(new byte[]
                    {
                        (byte)((glyphIndex >> 8) & 0xFF),
                        (byte)(glyphIndex & 0xFF)
                    });

                    // Checking for multiple Unicode codepoints which map to the same glyph index...

                    /*
                     * NOTE: In case the same glyph index maps to multiple Unicode codepoints, we are forced to
                     * alter the identity encoding creating distinct cmap entries for the exceeding codepoints.
                     */
                    if (codes.ContainsKey(charCode))
                    {
                        if (glyphIndex == 0) // .notdef glyph already mapped.
                        {
                            if (removedGlyphIndexKeys == null)
                            {
                                removedGlyphIndexKeys = new List <int>();
                            }
                            removedGlyphIndexKeys.Add(glyphIndexEntry.Key);
                            continue;
                        }

                        // Assigning the new character code...

                        /*
                         * NOTE: As our base encoding is identity, we have to look for a value that doesn't
                         * collide with existing glyph indices.
                         */
                        while (glyphIndexes.ContainsValue(++lastRemappedCharCodeValue))
                        {
                            ;
                        }
                        charCode.Data[0] = (byte)((lastRemappedCharCodeValue >> 8) & 0xFF);
                        charCode.Data[1] = (byte)(lastRemappedCharCodeValue & 0xFF);
                    }
                    else if (glyphIndex == 0) // .notdef glyph.
                    {
                        DefaultCode = glyphIndexEntry.Key;
                    }

                    codes[charCode] = glyphIndexEntry.Key;
                }
                if (removedGlyphIndexKeys != null)
                {
                    foreach (int removedGlyphIndexKey in removedGlyphIndexKeys)
                    {
                        glyphIndexes.Remove(removedGlyphIndexKey);
                    }
                }
                sortedCodes = new SortedDictionary <ByteArray, int>(codes);
                if (lastRemappedCharCodeValue > 0) // Custom encoding.
                {
                    string         cmapName   = "Custom";
                    bytes::IBuffer cmapBuffer = CMapBuilder.Build(
                        CMapBuilder.EntryTypeEnum.CID,
                        cmapName,
                        sortedCodes,
                        delegate(KeyValuePair <ByteArray, int> codeEntry)
                        { return(glyphIndexes[codeEntry.Value]); }
                        );
                    encodingObject = File.Register(
                        new PdfStream(
                            new PdfDictionary(
                                new PdfName[]
                    {
                        PdfName.Type,
                        PdfName.CMapName,
                        PdfName.CIDSystemInfo
                    },
                                new PdfDirectObject[]
                    {
                        PdfName.CMap,
                        new PdfName(cmapName),
                        new PdfDictionary(
                            new PdfName[]
                        {
                            PdfName.Registry,
                            PdfName.Ordering,
                            PdfName.Supplement
                        },
                            new PdfDirectObject[]
                        {
                            PdfTextString.Get("Adobe"),
                            PdfTextString.Get("Identity"),
                            PdfInteger.Get(0)
                        }
                            )
                    }
                                ),
                            cmapBuffer
                            )
                        );
                }
            }
            font[PdfName.Encoding]       = encodingObject;   // Character-code-to-CID mapping.
            cidFont[PdfName.CIDToGIDMap] = PdfName.Identity; // CID-to-glyph-index mapping.

            // ToUnicode [PDF:1.6:5.9.2].
            PdfDirectObject toUnicodeObject = null;

            {
                bytes::IBuffer toUnicodeBuffer = CMapBuilder.Build(
                    CMapBuilder.EntryTypeEnum.BaseFont,
                    null,
                    sortedCodes,
                    delegate(KeyValuePair <ByteArray, int> codeEntry)
                    { return(codeEntry.Value); }
                    );
                toUnicodeObject = File.Register(new PdfStream(toUnicodeBuffer));
            }
            font[PdfName.ToUnicode] = toUnicodeObject; // Character-code-to-Unicode mapping.

            // Glyph widths.
            PdfArray widthsObject = new PdfArray();

            {
                int      lastGlyphIndex            = -10;
                PdfArray lastGlyphWidthRangeObject = null;
                foreach (int glyphIndex in glyphIndexes.Values.OrderBy(x => x).ToList())
                {
                    int width;
                    if (!glyphWidths.TryGetValue(glyphIndex, out width))
                    {
                        width = 0;
                    }
                    if (glyphIndex - lastGlyphIndex != 1)
                    {
                        widthsObject.Add(PdfInteger.Get(glyphIndex));
                        widthsObject.Add(lastGlyphWidthRangeObject = new PdfArray());
                    }
                    lastGlyphWidthRangeObject.Add(PdfInteger.Get(width));
                    lastGlyphIndex = glyphIndex;
                }
            }
            cidFont[PdfName.W] = widthsObject; // Glyph widths.
        }
 public void BiDictionaryContains_Test()
 {
     var dictionary = new BiDictionary<object, object>();
     dictionary.Add("Key", "Value");
     Assert.True(dictionary.ContainsKey("Key"));
 }