Example #1
0
    /// <summary>
    /// Create a collection of items, 4 to be precisely
    /// </summary>
    public static void create()
    {
        int initialCapacity = 4;

        // The higher the concurrencyLevel, the higher the theoretical number of operations
        // that could be performed concurrently on the ConcurrentDictionary.  However, global
        // operations like resizing the dictionary take longer as the concurrencyLevel rises.
        // For the purposes of this example, we'll compromise at numCores * 2.
        int numProcs = Environment.ProcessorCount;
        int concurrencyLevel = numProcs * 2;

        // Construct the dictionary with the desired concurrencyLevel and initialCapacity
        Items = new ConcurrentDictionary<int, Item>(concurrencyLevel, initialCapacity);
        Items.TryAdd(0, new Item { Order = 0, Description = "Description of the first Item", Title = "first", Image = "img01.jpg" });
        Items.TryAdd(1, new Item { Order = 1, Description = "Description of the second Item", Title = "second", Image = "img02.jpg" });
        Items.TryAdd(2, new Item { Order = 2, Description = "Description of the third Item", Title = "third", Image = "img03.jpg" });
        Items.TryAdd(3, new Item { Order = 3, Description = "Description of the fourth Item", Title = "fourth", Image = "img04.jpg" });

        //An enumerator remains valid as long as the collection remains unchanged.
        //If changes are made to the collection, such as adding, modifying, or deleting elements,
        //the enumerator is irrecoverably invalidated and its behavior is undefined.
        //The enumerator does not have exclusive access to the collection; therefore,
        //enumerating through a collection is intrinsically not a thread-safe procedure.
        //Items = new List<Item>{  new Item { Order =0, Description ="Description of the first Item", Title ="first", Image ="img01.jpg"},
        //                         new Item { Order =1, Description ="Description of the second Item", Title ="second", Image ="img02.jpg"},
        //                         new Item { Order =2, Description ="Description of the third Item", Title ="third", Image ="img03.jpg"},
        //                         new Item { Order =3, Description ="Description of the fourth Item", Title ="fourth", Image ="img04.jpg"}};
    }
Example #2
0
        public ReturnImage GetImageWithDisplacement(FastBitmap currFrame, FastBitmap nextFrame, List<Point> edgePoints)
        {
            _nBytesPerPixel = currFrame.CCount;
            currFrame.LockBits();
            nextFrame.LockBits();
            byte[] currRgbValues = currFrame.Pixels;
            byte[] nextRgbValues = nextFrame.Pixels;
            ConcurrentDictionary<Point, Point> displacements = new ConcurrentDictionary<Point, Point>();

            Parallel.ForEach(edgePoints, (edgePoint) =>
            {
                int edgePointPos;
                List<Color> pointVicinity = GetPointVicinity(edgePoint, currRgbValues, currFrame.Width, currFrame.Height, currFrame.Stride, out edgePointPos);
                _brief = new BRIEF((POINT_WINDOW_SIDE + 1) * (POINT_WINDOW_SIDE + 1), edgePointPos);
                string vicinityDescriptor = _brief.GetImageDescriptor(pointVicinity);
                if (pointVicinity[edgePointPos] != Color.Black)
                {
                    Point nextFramePoint = FindPointDiscplacement(edgePoint, nextRgbValues, nextFrame.Width, nextFrame.Height, vicinityDescriptor, nextFrame.Stride, pointVicinity[edgePointPos]);
                    displacements.TryAdd(edgePoint, nextFramePoint);
                }
                else
                    displacements.TryAdd(edgePoint, edgePoint);
            });

            currFrame.UnlockBits();
            nextFrame.UnlockBits();

            Frame frame = GetFrameByChanell(currFrame, displacements);
            //frames.Add();
            ReturnImage image = new ReturnImage(frame, currFrame);
            return image;
        }
 static ProductsController()
 {
     database = new ConcurrentDictionary<int, Product>();
     database.TryAdd(1, new Product { Id = 1, Title = "Super lecker Pudding", Description = "Blaaa blaaa blubbb", Amount = 8 });
     database.TryAdd(2, new Product { Id = 2, Title = "Mjamm-mjamm Gurken", Description = "Yadda yadda yad", Amount = 149 });
     database.TryAdd(3, new Product { Id = 3, Title = "Mhhhh Salzstangen", Description = "Momm momm mom", Amount = 53 });
 }
        private SqlClientEncryptionAlgorithmFactoryList () {
            _encryptionAlgoFactoryList = new ConcurrentDictionary<string, SqlClientEncryptionAlgorithmFactory>(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/, capacity: 2);

            // Add wellknown algorithms
            _encryptionAlgoFactoryList.TryAdd(SqlAeadAes256CbcHmac256Algorithm.AlgorithmName, new SqlAeadAes256CbcHmac256Factory());
            _encryptionAlgoFactoryList.TryAdd(SqlAes256CbcAlgorithm.AlgorithmName, new SqlAes256CbcFactory());
        }
Example #5
0
 static CustomerService()
 {
     customers =  new ConcurrentDictionary<int,Customer>();
     customers.TryAdd(1, new Customer() { Id = 1, Name = "Customer1" });
     customers.TryAdd(2, new Customer() { Id = 2, Name = "Customer2" });
     customers.TryAdd(3, new Customer() { Id = 3, Name = "Customer3" });
 }
 static ArticlesController()
 {
     database = new ConcurrentDictionary<int, Article>();
     database.TryAdd(1, new Article { Id = 1, Name = "Super lecker Pudding", Description = "Blaaa blaaa blubbb"});
     database.TryAdd(2, new Article { Id = 2, Name = "Mjamm-mjamm Gurken", Description = "Yadda yadda yad"});
     database.TryAdd(3, new Article { Id = 3, Name = "Mhhhh Salzstangen", Description = "Momm momm mom" });
 }
        public void Encode()
        {
            LogManager.SetupLogManager();
            var log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod());
            log.Info("Start");

            //Dictionary<string, string> obj;

            //obj = new Dictionary<string, string> {{"a", "b"}};
            //var imObj = ImmutableDictionary.Create<string, string>().AddRange(obj);
            var imObj = new ConcurrentDictionary<string, string>();
            imObj.TryAdd("a","b");
            Assert.Equal(ParseQS.Encode(imObj), "a=b");

            //obj = new Dictionary<string, string> {{"a", "b"}, {"c", "d"}};
            //imObj = ImmutableDictionary.Create<string, string>().AddRange(obj);
            imObj = new ConcurrentDictionary<string, string>();
            imObj.TryAdd("a", "b");
            imObj.TryAdd("c", "d");
            Assert.Equal(ParseQS.Encode(imObj), "a=b&c=d");

            //obj = new Dictionary<string, string> {{"a", "b"}, {"c", "tobi rocks"}};
            //imObj = ImmutableDictionary.Create<string, string>().AddRange(obj);
            imObj = new ConcurrentDictionary<string, string>();
            imObj.TryAdd("a", "b");
            imObj.TryAdd("c", "tobi rocks");
            Assert.Equal(ParseQS.Encode(imObj), "a=b&c=tobi%20rocks");
        }
        public void Test()
        {
            var keyValues = new Dictionary<string, string>();
            using (var cluster = new Cluster())
            {
                using (var bucket = cluster.OpenBucket())
                {
                    for (int i = 0; i <10; i++)
                    {
                        var key = "MGETKEY" + i;
                        var value = "{\"val:\"MGETVALUE" + i +"\"}";
                        bucket.Upsert(key, value);
                        keyValues.Add(key, value);
                    }

                    foreach (var keyValue in keyValues)
                    {
                        Console.WriteLine(bucket.Get<dynamic>(keyValue.Key).Value);
                    }
                }
            }

            var operations = new ConcurrentDictionary<uint, IOperation>();
            foreach (var keyValue in keyValues)
            {
                var getk = new GetK<dynamic>(keyValue.Key, GetVBucket(), Converter, Transcoder);
                operations.TryAdd(getk.Opaque, getk);
            }
            var noop = new Noop(Converter);
            operations.TryAdd(noop.Opaque, noop);

            var results = IOStrategy.Execute<dynamic>(operations);
        }
        public void CycleIsCollidingInBounds()
        {
            var gameConfig = new GameConfiguration(new CycleConfiguration(), new MapConfiguration());
            var map = new Map(gameConfig.MapConfig);
            var startPosition = new Vector3(0, gameConfig.CycleConfig.Y_OFFSET, 0);
            var cycle = new Cycle(1, startPosition, new Vector3(1, 0, 0), Math.PI + Math.PI * .5, 0xff0000, map, gameConfig);
            var cycle2 = new Cycle(2, startPosition, new Vector3(1, 0, 0), Math.PI + Math.PI * .5, 0xff0000, map, gameConfig);
            var collisionChecker = new CollisionChecker(map);
            var startLocation = map.Utilities.ToMapLocation(startPosition);
            var cycles = new ConcurrentDictionary<long, Cycle>();
            cycles.TryAdd(cycle.ID, cycle);
            cycles.TryAdd(cycle2.ID, cycle2);
            map.RegisterCycles(cycles);

            map[startLocation] = 2;
            collisionChecker.ValidateCollision(cycle);

            Assert.True(cycle.Colliding);

            map.Clear();
            cycle.Colliding = false;
            map[startLocation] = -cycle.ID;
            collisionChecker.ValidateCollision(cycle);
            Assert.False(cycle.Colliding);

            map.Clear();
            cycle.Colliding = false;
            map[startLocation] = 0;
            collisionChecker.ValidateCollision(cycle);
            Assert.False(cycle.Colliding);
        }
        public static void Main()
        {
            var stock = new ConcurrentDictionary<string, int>();
            stock.TryAdd("jDays", 4);
            stock.TryAdd("technologyhour", 3);

            Console.WriteLine("No. of shirts in stock = {0}", stock.Count);

            var success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);
            success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);

            stock["buddhistgeeks"] = 5;

            //stock["pluralsight"]++; <-- not thread safe two instructions
            var psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
            Console.WriteLine("pluralsight new value = {0}", psStock);

            Console.WriteLine("stock[pluralsight] = {0}", stock.GetOrAdd("pluralsight", 0));

            int jDaysValue;
            success= stock.TryRemove("jDays", out jDaysValue);
            if (success) Console.WriteLine("Value removed was: " + jDaysValue);

            Console.WriteLine("\r\nEnumerating:");
            foreach (var keyValuePair in stock)
            {
                Console.WriteLine("{0}: {1}", keyValuePair.Key, keyValuePair.Value);
            }
        }
Example #11
0
        /// <summary>
        /// Store build outputs in the cache by reading them from the file system
        /// </summary>
        /// <param name="builder">Builder key (first part of the key)</param>
        /// <param name="fingerprint">Dependency fingerprint created when the builder was executed (second part of the key)</param>
        /// <param name="outputs">Target-relative path of the build outputs to be cached</param>
        /// <param name="targetRoot">File system abstraction of the root target directory</param>
        public void Store(BuildKey builder, IDependencyFingerprint fingerprint, IEnumerable<TargetRelativePath> outputs, IFileSystemDirectory targetRoot)
        {
            MemoryCacheItem item = GetOrCreate(builder);            

            var map = new ConcurrentDictionary<TargetRelativePath, byte[]>();

            Parallel.ForEach(outputs, outputPath =>
                {
                    if (targetRoot.Exists(outputPath))
                    {
                        using (var stream = targetRoot.ReadBinaryFile(outputPath))
                        {
                            var buf = new byte[stream.Length];
                            stream.Read(buf, 0, buf.Length);

                            map.TryAdd(outputPath, buf);
                        }
                    }
                    else
                    {
                        map.TryAdd(outputPath, null);
                    }
                });
            
            item.Update(fingerprint, map);
        }
        private static IReadOnlyDictionary<string, AnalyticsBondStaticData> BulkGetBondStaticDataFromCarbon(ICarbonClient client,
            IReadOnlyCollection<string> bondIds)
        {
            if (bondIds == null || bondIds.Count == 0) return new Dictionary<string, AnalyticsBondStaticData>();

            var dict = new ConcurrentDictionary<string, AnalyticsBondStaticData>();
            var ids = new List<string>();
            foreach (var id in bondIds)
            {
                AnalyticsBondStaticData data;

                if (BondStaticDataCache.TryGetValue(id, out data))
                {
                    dict.TryAdd(id, data);
                }
                else
                {
                    var carbonBond = client.GetCachedCarbonBond(id);
                    if (carbonBond == null)
                    {
                        ids.Add(id);
                    }
                    else
                    {
                        var bond = ConvertCarbonBondToAnalyticsBondStaticData(carbonBond);
                        if (bond != null)
                        {
                            dict.TryAdd(id, bond);
                            BondStaticDataCache.TryAdd(id, bond);
                            BondStaticDataCache.TryAdd(bond.Id, bond);
                        }
                        else
                        {
                            ids.Add(id);
                        }
                    }
                }
            }

            if (ids.Count == 0) return dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            var datas = client.BulkGetSecurityMetadataInternal(ids, "static-bond");

            if (datas == null || datas.Count == 0) return dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            Parallel.ForEach(datas, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
                data =>
                {
                    var bond = ConvertCarbonBondStaticToAnalyticBondStatic(client, data);
                    if (bond != null)
                    {
                        BondStaticDataCache.TryAdd(bond.Id, bond);
                        BondStaticDataCache.TryAdd(data.Identifier, bond);
                        dict.TryAdd(bond.Id, bond);
                    }
                });

            return dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }
Example #13
0
 public void AddEvent_should_fill_in_zero_events_if_key_points_to_an_out_of_bounds_index()
 {
     var eventStore = new ConcurrentDictionary<int, int>();
     eventStore.TryAdd(0, 1);
     eventStore.TryAdd(1, 2);
     _monitor.AddEvent(eventStore, 10);
     var expected = new[] {1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1};
     eventStore.Values.ShouldAllBeEquivalentTo(expected);
 }
Example #14
0
        private static TestData PopulateTestData(bool populateAll)
        {
            //Define Defaults
            var defineDefaults = new Mock<ISetupMonitorConfig>();
            defineDefaults.Setup(x => x.CreateDefaultReduceLevels(It.IsAny<MonitorConfig>(), It.IsAny<List<ReduceLevel>>(), It.IsAny<IDbConnection>())).Verifiable();

            //Cache
            var monitorInfoDictionary = new ConcurrentDictionary<string, MonitorInfo>();
            var monitorConfigsDictionary = new ConcurrentDictionary<string, MonitorConfig>();

            var reductionLevel = new ReduceLevel { Resolution = 1000 };
            var monitorConfig = new MonitorConfig { Name = "Test", ReduceLevels = new List<ReduceLevel> { reductionLevel } };
            var monitorInfo = new MonitorInfo { TablesCreated = false, MonitorRecords = new List<MonitorRecord<double>> { new MonitorRecord<double>(DateTime.Now, 5) }, MonitorConfig = monitorConfig };

            monitorInfoDictionary.TryAdd("Test", monitorInfo);
            monitorConfigsDictionary.TryAdd("Test", monitorConfig);

            reductionLevel = new ReduceLevel { Resolution = 1000 };
            monitorConfig = new MonitorConfig { Name = "Jester", ReduceLevels = new List<ReduceLevel> { reductionLevel } };
            monitorInfo = new MonitorInfo { TablesCreated = false, MonitorRecords = new List<MonitorRecord<double>> { new MonitorRecord<double>(DateTime.Now, 5) }, MonitorConfig = monitorConfig };

            monitorInfoDictionary.TryAdd("Jester", monitorInfo);
            monitorConfigsDictionary.TryAdd("Jester", monitorConfig);

            var cache = new Mock<IDataCache>();
            cache.SetupGet(x => x.MonitorInfo).Returns(monitorInfoDictionary);
            cache.SetupGet(x => x.MonitorConfigs).Returns(monitorConfigsDictionary);

            //Storage
            var storage = new Mock<IStorageCommands>();
            storage.Setup(x => x.Insert(It.IsAny<string>(), It.IsAny<IEnumerable<MonitorRecord<double>>>(), It.IsAny<IDbConnection>(), It.IsAny<IDbTransaction>())).Verifiable();

            //Logic
            var logic = new Mock<IRecordFlushUpdate>();
            logic.Setup(x => x.UpdateExisting(It.IsAny<string>(), It.IsAny<SortedDictionary<long, MonitorRecord<double>>>(), It.IsAny<IDbConnection>(), It.IsAny<IDbTransaction>())).Verifiable();

            //Db Provider
            var transaction = new Mock<IDbTransaction>();
            transaction.SetupGet(x => x.IsolationLevel).Returns(IsolationLevel.Serializable).Verifiable();
            transaction.Setup(x => x.Rollback()).Verifiable();
            transaction.Setup(x => x.Commit()).Verifiable();

            var connection = new Mock<IDbConnection>();
            connection.Setup(x => x.Open()).Verifiable();
            connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object).Verifiable();
            connection.Setup(x => x.BeginTransaction(It.IsAny<IsolationLevel>())).Returns(transaction.Object).Verifiable();

            var dbProviderFactory = new Mock<IStorageFactory>();
            dbProviderFactory.Setup(x => x.CreateConnection()).Returns(connection.Object).Verifiable();

            //Settings
            var settings = BuildSettings();

            return new TestData { Settings = settings, Cache = cache, DbProviderFactory = dbProviderFactory, Logic = logic, Storage = storage, Transaction = transaction, Connection = connection, DefineDefaults = defineDefaults };
        }
Example #15
0
        private static ConcurrentDictionary<string, MediaTypeHeaderValue> CreateMediaTypeMap()
        {
            var dictionary = new ConcurrentDictionary<string, MediaTypeHeaderValue>(StringComparer.OrdinalIgnoreCase);
            dictionary.TryAdd(".js", MediaTypeHeaderValue.Parse("application/javascript"));
            dictionary.TryAdd(".json", MediaTypeHeaderValue.Parse("application/json"));

            // Add media type for markdown
            dictionary.TryAdd(".md", MediaTypeHeaderValue.Parse("text/plain"));

            return dictionary;
        }
        public void TestInitialize()
        {
            _data = new ConcurrentDictionary<int, ISteig>();
            for (int i = 1; i <= 10; i++) {
                _data.TryAdd(i, new Steig(i, 123, 123, ERichtung.Rueck, i + 5, 1234, 34, "Bahnsteig " + i.ToString(), new Point()));
            }
            for (int i = 11; i <= 20; i++) {
                _data.TryAdd(i, new Steig(i, 2 + (i % 2), 987, ERichtung.Hin, i, i + i * 2, 23, "Bahnsteig " + i.ToString(), new Point()));
            }

            _mapper = new SteigMapper(_data);
        }
 static TypeScriptConvert()
 {
     Mapping = new ConcurrentDictionary<Type, string>();           
     Mapping.TryAdd(typeof(bool), Boolean);
     Mapping.TryAdd(typeof(void), Void);
     new[]
     {
         typeof (short), typeof (int), typeof (long), typeof (byte), typeof (double), typeof (sbyte),
         typeof (float), typeof (ushort), typeof (uint), typeof (ulong), typeof(decimal)
     }.ToList().ForEach(x => Mapping.TryAdd(x, Number));
     new[] { typeof(DateTime), typeof(DateTimeOffset) }.ToList().ForEach(x => Mapping.TryAdd(x, Date));
     new[] { typeof(string), typeof(Guid), typeof(TimeSpan), typeof(byte[]) }.ToList().ForEach(x => Mapping.TryAdd(x, String));
 }
 public static void Test_ConcurrentDictionary_03()
 {
     ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
     // Func<TKey, TValue, TValue> updateValueFactory : Fonction utilisée pour générer une nouvelle valeur pour une clé existante en fonction de la valeur existante de la clé
     dictionary.TryAdd(1, "toto1");
     dictionary.TryAdd(1, "toto2");
     dictionary.TryAdd(2, "tata");
     dictionary.TryAdd(3, "tutu");
     dictionary.TryAdd(4, "titi");
     foreach (KeyValuePair<int, string> value in dictionary)
     {
         Trace.WriteLine("{0} - \"{1}\"", value.Key, value.Value);
     }
 }
 public CharacterDatabase(int DatabaseUID)
 {
     ItemFiles = new ConcurrentDictionary<byte, IniFile>();
     WarehouseFiles = new ConcurrentDictionary<ushort, IniFile>();
     foreach (ushort MapID in whids)
     {
         if (!WarehouseFiles.TryAdd(MapID, new IniFile(Database.ServerDatabase.DatabaseLocation + "\\Warehouses\\" + DatabaseUID + "_" + MapID + ".ini")))
             throw new Exception("Failed to add warehouse id " + MapID + " of " + DatabaseUID);
     }
     if (!ItemFiles.TryAdd(0, new IniFile(Database.ServerDatabase.DatabaseLocation + "\\Inventories\\" + DatabaseUID + ".ini")))
         throw new Exception("Failed to add inventory of " + DatabaseUID);
     if (!ItemFiles.TryAdd(1, new IniFile(Database.ServerDatabase.DatabaseLocation + "\\Equipments\\" + DatabaseUID + ".ini")))
         throw new Exception("Failed to add equipment of " + DatabaseUID);
 }
        private CommandSender()
        {
            commands = new ConcurrentDictionary<string, string>();
            commands.TryAdd(CommandMetadata.Camera.Identifier, string.Empty);
            commands.TryAdd(CommandMetadata.Movement.LeftIdentifier, string.Empty);
            commands.TryAdd(CommandMetadata.Movement.RightIdentifier, string.Empty);
            commands.TryAdd(CommandMetadata.Pan.Identifier, string.Empty);
            commands.TryAdd(CommandMetadata.Tilt.Identifier, string.Empty);

            udpSender = new UDPSender(Properties.NetworkSettings.Default.RoverIPAddress, Properties.NetworkSettings.Default.CommandsPort);
            Thread t = new Thread(SendCommands);
            t.IsBackground = true;
            t.Start();
        }
Example #21
0
        private static void ConcurrentDictionaryOps()
        {
            // create new concurrent dictionary of key/value string/int
            var stock = new ConcurrentDictionary<string, int>();

            // perform TryAdd actions with the below pairs, output numerical value
            stock.TryAdd("jDays", 4);
            stock.TryAdd("technologyhour", 3);
            Console.WriteLine("No. of shirts in stock = {0}", stock.Count);

            // use success parameter to test if value was actually added to the dictionary
            bool success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);

            // second attempt will result in a 'false'
            success = stock.TryAdd("pluralsight", 6);
            Console.WriteLine("Added succeeded? " + success);

            stock["buddhistgeeks"] = 5;

            //// TryUpdate, takes in key, value, and previous value
            //success = stock.TryUpdate("pluralsight", 7, 6);
            //Console.WriteLine("pluralsight = {0}, did update work? {1}", stock["pluralsight"], success);

            // AddOrUpdate, repeatedly calls TryUpdate() until it succeeds
            int psStock = stock.AddOrUpdate("pluralsight", 1, (key, oldValue) => oldValue + 1);
            Console.WriteLine("New value is {0}", psStock);

            // Writing 'stock["pluralsight"]' to console can cause a race condition
            // due to accessing the dictionary (values can go out-of-date between method calls!)

            // GetOrAdd, not sure if value was in dictionary, add if it isn't with value paramter
            Console.WriteLine("stock[pluralsights] = {0}", stock.GetOrAdd("pluralssights", 0));

            // TryRemove jDays value from dict, write to console if success with int out parameter
            int jDaysValue;
            success = stock.TryRemove("jDays", out jDaysValue);
            if (success)
            {
                Console.WriteLine("Value removed was: {0}", jDaysValue);
            }

            Console.WriteLine("\r\nEnumerating:");
            foreach (var keyValPair in stock)
            {
                Console.WriteLine("{0}: {1}", keyValPair.Key, keyValPair.Value);
            }
        }
Example #22
0
        private void ProcessPrintJobNotification(NotificationResult nr, CancellationToken cancellationToken)
        {
            var inserted = nr.Inserted.GroupBy(c => new PrintJob()
            {
                Description = c.Description, JobID = c.JobID, PrintQueue = c.PrintQueue, ReportID = c.ReportID
            }, c => new{ c.ParameterName, c.ParameterValue });
            var deleted = nr.Deleted.GroupBy(c => new PrintJob()
            {
                Description = c.Description, JobID = c.JobID, PrintQueue = c.PrintQueue, ReportID = c.ReportID
            }, c => new { c.ParameterName, c.ParameterValue }).ToDictionary(c => c.Key, c => c.ToArray());

            foreach (var row in inserted)
            {
                PrintQueue queue;
                if (deleted.ContainsKey(row.Key) || !_queues.TryGetValue(row.Key.PrintQueue, out queue))
                {
                    continue;
                }
                _alreadyProcessed?.TryAdd(row.Key.JobID, row.Key.JobID);
                try
                {
                    ProcessJob(queue, row.Key.JobID, row.Key.ReportID, row.Key.Description,
                               row.AsEnumerable()
                               .Where(c => c.ParameterName != null)
                               .ToDictionary(c => c.ParameterName, c => c.ParameterValue));
                }
                catch (Exception e)
                {
                    _progress.Report(new MonitorMessage(string.Format(Strings.PollingQueueUnknownError, e.Message),
                                                        MonitorMessage.MonitorStates.Error));
                    Restart(cancellationToken).Wait(cancellationToken);
                }
            }
        }
        public static ConcurrentDictionary<int, int> GetAmicableNumbersParallelized(int n)
        {
            ConcurrentDictionary<int, int> amicableNumbers =
                new ConcurrentDictionary<int, int>();

            Parallel.For(1, n, (i) =>
            {
                Parallel.For(i, n, (j) =>
                {
                    if (i != j &&
                        i == GetEvenDivisors(j).Sum() &&
                        j == GetEvenDivisors(i).Sum())
                    {
                        amicableNumbers.TryAdd(i, j);
                        Console.WriteLine("Found {0} and {1} using Thread {2}.",
                            GetEvenDivisors(i).Sum(),
                            GetEvenDivisors(j).Sum(),
                            Thread.CurrentThread.ManagedThreadId);
                    }
                }
                );
            });

            return amicableNumbers;
        }
Example #24
0
        /// <inheritdoc />
        public async Task <Possible <CasEntries, Failure> > GetCacheEntryAsync(StrongFingerprint strong, UrgencyHint urgencyHint, Guid activityId)
        {
            var hashListResult = await ReadOnlyCacheSession.GetContentHashListAsync(
                new Context(Logger),
                new BuildXL.Cache.MemoizationStore.Interfaces.Sessions.StrongFingerprint(
                    strong.WeakFingerprint.ToMemoization(),
                    new Selector(strong.CasElement.ToMemoization(), strong.HashElement.RawHash.ToByteArray())),
                CancellationToken.None);

            if (hashListResult.Succeeded)
            {
                if (hashListResult.ContentHashListWithDeterminism.ContentHashList == null)
                {
                    return(new NoMatchingFingerprintFailure(strong));
                }

                SessionEntries?.TryAdd(strong, 1);

                return(hashListResult.ContentHashListWithDeterminism.FromMemoization());
            }
            else
            {
                return(new CacheFailure(hashListResult.ErrorMessage));
            }
        }
Example #25
0
        public SqlDataManager(
            Logger logger,
            GrainStateMap grainStateMap, 
            string connectionString, 
            string shardCredentials, 
            string mapName,
            BatchingOptions batchingOptions =null)
        {
            Logger = logger;
            Guard.NotNullOrEmpty(connectionString, "conectionString");
            Guard.NotNullOrEmpty(shardCredentials, "shardCredentials");
            Guard.NotNullOrEmpty(mapName, "mapName");

            // Try to get a reference to the Shard Map Manager via the Shard Map Manager database.  
            // If it doesn't already exist, then fail 
            var shardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(connectionString, ShardMapManagerLoadPolicy.Lazy);
            var shardMap = (RangeShardMap<int>)shardMapManager.GetShardMap(mapName);
            var shardBatchers = new ConcurrentDictionary<Range<int>, ShardBatcher>();
            foreach (var rangeMapping in shardMap.GetMappings())
            {
                Range<int> range = rangeMapping.Value;
                shardBatchers.TryAdd(range, new ShardBatcher(logger, grainStateMap, rangeMapping.Shard, shardCredentials, batchingOptions));
            }

            _shardBatchers = shardBatchers;
            _shardMap = shardMap;
        }
Example #26
0
        public void MainMethod()
        {
            Console.WriteLine("Concurrent Dictionary Run implementation");
            ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
            if(dictionary.TryAdd("k1",10))
            {
                Console.WriteLine("Added Key k1");
            }

            if(dictionary.TryUpdate("k1",19,10))
            {
                Console.WriteLine("Updated Key k1");
            }

            if (dictionary.TryUpdate("k1", 19, 10))
            {
                Console.WriteLine("Updated Key k1");
            }
            else
                Console.WriteLine("Failed to Update");

            dictionary["k1"] = 16;

            int r1 = dictionary.AddOrUpdate("k1", 2, (s, i) => i * 2);
            Console.WriteLine(r1);
            int r3 = dictionary.AddOrUpdate("k3", 2, (s, i) => i * 2);
            Console.WriteLine(r3);
            int r2 = dictionary.GetOrAdd("k2", 4);
            Console.WriteLine(r2);
        }
Example #27
0
 /// <summary>
 /// 初始化服务容器
 /// </summary>
 /// <param name="serviceName"> 服务约定名称 </param>
 /// <param name="serviceType"> 服务约定基类或接口类型 </param>
 /// <param name="typeComparer"> 比较2个类型服务的优先级 </param>
 /// <param name="logger"> 日志记录器 </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="serviceName" /> and <paramref name="serviceType" /> is all
 /// <see langword="null" />.
 /// </exception>
 /// <exception cref="OverflowException"> 匹配插件数量超过字典的最大容量 (<see cref="F:System.Int32.MaxValue" />)。 </exception>
 protected ServiceContainer(string serviceName, Type serviceType, IComparer<Type> typeComparer, TraceSource logger = null)
 {
     TypeComparer = typeComparer;
     _logger = logger ?? LogServices.Logger;
     _items = new ConcurrentDictionary<Type, ServiceItem>();
     _logger?.Write(TraceEventType.Start, $"开始扫描服务插件 serviceName={serviceName},serviceType={serviceType}");
     foreach (var p in MEF.PlugIns.GetPlugIns(serviceName, serviceType).OrderByDescending(p => p.Priority))
     {
         var value = p.GetValue(serviceType);
         if (value == null)
         {
             continue;
         }
         var type = GetServiceType(p, value);
         if (type == null)
         {
             continue;
         }
         var item = new ServiceItem(this, type, value, p);
         item.MakeSystem(); //默认为系统插件
         if (_items.TryAdd(type, item) == false)
         {
             _logger?.Write(TraceEventType.Verbose, $"服务插件({value.GetType().FullName})因优先级({p.Priority})过低被抛弃");
         }
         else
         {
             _logger?.Write(TraceEventType.Verbose, $"服务插件({value.GetType().FullName}),优先级({p.Priority})装载完成");
         }
     }
     _logger?.Write(TraceEventType.Stop, $"服务插件装载完成,有效服务 {Count} 个");
 }
        public IEnumerable<JobMetric> GetMetrics(IDictionary<Guid, IDictionary<Guid, int?>> packagesWithJobsAndLastBuildNumber)
        {
            using (var gateway = PackageConfigurationGatewayFactory())
            {
                var result = new ConcurrentDictionary<string, JobMetric>();
                foreach (var packagesWithJob in packagesWithJobsAndLastBuildNumber)
                {
                    var configuration = gateway.GetPackageConfiguration(packagesWithJob.Key);
                    if (configuration == null || string.IsNullOrEmpty(configuration.JenkinsServerUrl))
                        continue;
                    var jobs = gateway.GetJobs(packagesWithJob.Value.Keys)
                        .Join(packagesWithJob.Value, j => j.ExternalId, k => k.Key,
                            (j, k) => new {Job = j, BuildNumber = k.Value});

                    JenkinsRequest.ChangeBaseUrl(configuration.JenkinsServerUrl);
                    JenkinsRequest.ChangeBaseUrl(configuration.JenkinsServerUrl);
                    Parallel.ForEach(jobs, j =>
                    {
                        var metrics = JenkinsRequest.GetJobMetrics(j.Job.Name, j.BuildNumber, configuration.TimeZone);
                        if (metrics == null) return;

                        if (!result.TryAdd(j.Job.Name, metrics))
                        {
                            Logger.ErrorFormat("Jenkins Job measurements not stored. Job={0}, Id={1}",
                                j.Job.Name, j.Job.ExternalId);
                        }
                    });
                }
                return result.Values.ToArray();
            }
        }
        /// <summary>
        /// Returns the color count from the palette of the given image.
        /// </summary>
        /// <param name="image">
        /// The <see cref="System.Drawing.Image"/> to get the colors from.
        /// </param>
        /// <returns>
        /// The <see cref="int"/> representing the color count.
        /// </returns>
        public static int GetColorCount(Image image)
        {
            ConcurrentDictionary<Color, Color> colors = new ConcurrentDictionary<Color, Color>();
            int width = image.Width;
            int height = image.Height;

            using (FastBitmap fastBitmap = new FastBitmap(image))
            {
                Parallel.For(
                    0,
                    height,
                    y =>
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            Color color = fastBitmap.GetPixel(x, y);
                            colors.TryAdd(color, color);
                        }
                    });
            }

            int count = colors.Count;
            colors.Clear();
            return count;
        }
        public override ValueSerializer BuildSerializer(Serializer serializer, Type type,
            ConcurrentDictionary<Type, ValueSerializer> typeMapping)
        {
            var x = new ObjectSerializer(type);
            typeMapping.TryAdd(type, x);

            var elementType = GetEnumerableType(type);
            var arrType = elementType.MakeArrayType();
            var listModule = type.Assembly.GetType("Microsoft.FSharp.Collections.ListModule");
            var ofArray = listModule.GetMethod("OfArray");
            var ofArrayConcrete = ofArray.MakeGenericMethod(elementType);
            var ofArrayCompiled = CodeGenerator.CompileToDelegate(ofArrayConcrete, arrType);
            var toArray = listModule.GetMethod("ToArray");
            var toArrayConcrete = toArray.MakeGenericMethod(elementType);
            var toArrayCompiled = CodeGenerator.CompileToDelegate(toArrayConcrete, type);

            ValueWriter writer = (stream, o, session) =>
            {
                var arr = toArrayCompiled(o);
                var arrSerializer = serializer.GetSerializerByType(arrType);
                arrSerializer.WriteValue(stream,arr,session);
            };

            ValueReader reader = (stream, session) =>
            {               
                var arrSerializer = serializer.GetSerializerByType(arrType);
                var items = (Array)arrSerializer.ReadValue(stream, session);                          
                var res = ofArrayCompiled(items);
                return res;
            };
            x.Initialize(reader, writer);
            return x;
        }
Example #31
0
        public IEnumerable<JobMetric> GetMetrics(IDictionary<Guid, IDictionary<Guid, int?>> packagesWithJobsAndLastBuildNumber)
        {
            using (var gateway = PackageConfigurationGatewayFactory())
            {
                var result = new ConcurrentDictionary<string, JobMetric>();
                foreach (var packagesWithJob in packagesWithJobsAndLastBuildNumber)
                {
                    var configuration = gateway.GetPackageConfiguration(packagesWithJob.Key);
                    if (configuration == null || string.IsNullOrEmpty(configuration.GoServerUrl))
                        continue;
                    var pipelineNames = gateway.GetPipelines(packagesWithJob.Value.Keys);

                    GoRequest.ChangeBaseUrl(configuration.GoServerUrl);
                    Parallel.ForEach(pipelineNames, p =>
                    {
                        var stepTiming = GoRequest.GetPipelineTiming(p.Name);
                        if (stepTiming == null) return;

                        var jobMetric = Mapper.Map<StepTiming, JobMetric>(stepTiming);
                        if (!result.TryAdd(p.Name, jobMetric))
                        {
                            Logger.ErrorFormat("Pipeline measurements not stored. Pipeline={0}, Id={1}",
                                p.Name, p.ExternalId);
                        }
                    });
                }
                return result.Values.ToArray();
            }
        }
Example #32
0
 /// <summary>
 /// This is the Method executed before the Method Body
 /// Important: Name must match <see cref="OnBeforeMethod"/>
 /// </summary>
 // ReSharper disable once UnusedMember.Global Justification: Reflection
 public static void OnBeforeMethod(string documentationCommentId)
 {
     if (_telemetryClient == null)
     {
         Init();
     }
     _methodStartDateTimes?.TryAdd(documentationCommentId, DateTime.UtcNow);
 }
        public void GetResource_ExistsInResourceCache_DoesNotReadFromManifestResource()
        {
            string fileName      = "filename";
            string existingKey   = "ExistingKey";
            var    scsController = CreateInstance <GenericScsController>();
            ConcurrentDictionary <string, string> resourceCache = (ConcurrentDictionary <string, string>) typeof(ScsController).GetField("_resourceCache", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(scsController);

            resourceCache?.TryAdd(fileName, existingKey);

            string actual = scsController.GetResource(fileName);

            actual.Should().Be(existingKey);
            GetSubstitute <IMainfestResourceStreamService>().Received(0).GetManifestResourceText(Arg.Any <Type>(), Arg.Any <string>(), Arg.Any <Func <string> >());
        }
Example #34
0
        public static string GetAliasForType <T>(string tablealias = null)
        {
            if (!string.IsNullOrWhiteSpace(tablealias))
            {
                return(tablealias);
            }

            if (!Alias.TryGetValue(typeof(T), out var alias))
            {
                alias = CreateAliasForType <T>();
                Alias?.TryAdd(typeof(T), alias);
            }

            return(alias);
        }
        public JsonRpcServerBase(INodeAPI node, INodeTransactionAPI trans)
        {
            _node  = node;
            _trans = trans;

            if (_queue == null && NodeService.Dag != null)
            {
                _queue     = new ConcurrentQueue <TxInfoBase>();
                _haveBlock = new EventWaitHandle(false, EventResetMode.ManualReset);
                _instances = new ConcurrentDictionary <int, JsonRpcServerBase>();

                NodeService.Dag.OnNewBlock += NewBlockMonitor;

                _ = Task.Run(async() => {
                    while (true)
                    {
                        await _haveBlock.AsTaskAsync();
                        _haveBlock.Reset();

                        TxInfoBase info;
                        while (_queue.TryDequeue(out info))
                        {
                            foreach (var inst in _instances.Values)
                            {
                                try
                                {
                                    if (inst.GetIfInterested(info.to))
                                    {
                                        inst.Notify?.Invoke(this, new News {
                                            catalog = info.GetType().Name, content = info
                                        });
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }).ConfigureAwait(false);
            }

            _instances?.TryAdd(this.GetHashCode(), this);
        }
Example #36
0
        public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy?namingPolicy, JsonSerializerOptions serializerOptions)
        {
            _converterOptions    = converterOptions;
            _namingPolicy        = namingPolicy;
            _nameCacheForWriting = new ConcurrentDictionary <ulong, JsonEncodedText>();

            if (namingPolicy != null)
            {
                _nameCacheForReading = new ConcurrentDictionary <string, T>();
            }

#if NETCOREAPP
            string[] names  = Enum.GetNames <T>();
            T[]      values = Enum.GetValues <T>();
#else
            string[] names  = Enum.GetNames(TypeToConvert);
            Array    values = Enum.GetValues(TypeToConvert);
#endif
            Debug.Assert(names.Length == values.Length);

            JavaScriptEncoder?encoder = serializerOptions.Encoder;

            for (int i = 0; i < names.Length; i++)
            {
#if NETCOREAPP
                T value = values[i];
#else
                T value = (T)values.GetValue(i) !;
#endif
                ulong  key  = ConvertToUInt64(value);
                string name = names[i];

                string jsonName = FormatJsonName(name, namingPolicy);
                _nameCacheForWriting.TryAdd(key, JsonEncodedText.Encode(jsonName, encoder));
                _nameCacheForReading?.TryAdd(jsonName, value);
            }
        }
Example #37
0
        private Message HandleTokens(SessionKey session, List <string> tokens)
        {
#pragma warning disable IDE0018 // Inlinevariablendeklaration
            RPGGame newGame;
#pragma warning restore IDE0018 // Inlinevariablendeklaration
            string message = "";

            if (_games.TryGetValue(session.Key, out newGame))
            {
                if (tokens.Count == 0)
                {
                    message = newGame.RoomFeelings();
                }
                else
                {
                    var result = newGame.PlayerAction(tokens);
                    if (result == "")
                    {
                        _games.TryRemove(session.Key, out newGame);
                        message = "Das Spiel wurde beendet!";
                    }
                    else
                    {
                        message = result;
                    }
                }
            }
            else
            {
                var  expiredGames = _games.Where(g => g.Value.lastAction.Add(_timeToExpire) < DateTime.Now).OrderBy(g => g.Value.lastAction).ToList();
                bool hasFreeSlot  = true;
                if (_games.Count >= _maxGames)
                {
                    if (expiredGames.Count == 0)
                    {
                        message     = "Alle Spielräume sind derzeit belegt. Bitte später nochmals versuchen!";
                        hasFreeSlot = false;
                    }
                    else
                    {
                        foreach (var i in expiredGames)
                        {
#pragma warning disable IDE0018 // Inlinevariablendeklaration
                            RPGGame game;
#pragma warning restore IDE0018 // Inlinevariablendeklaration
                            _games.TryRemove(i.Key, out game);
                        }
                        hasFreeSlot = true;
                    }
                }

                if (hasFreeSlot)
                {
                    newGame = new RPGGame();
                    _games.TryAdd(session.Key, newGame);
                    message  = string.Format("Willkommen im RPGPlugin! Schreibe 'Hilfe', um verfügbare Befehle zu sehen. Mit 'Ende' wird das Spiel beendet. Mit 'Pause' wird das Spiel pausiert.", session.Key);
                    message += "<br/><br/>-----------------------<br/><br/>";
                    message += newGame.RoomFeelings();
                }
            }
            return(new RPGMessage(message));
        }
Example #38
0
 public void Register <T, T1>() where T : Command where T1 : IHandleCommand <T>
 {
     TypeRegistry.TryAdd(typeof(T), typeof(T1));
 }
Example #39
0
    IEnumerator BuildWorld()
    {
        m_building = true;

        // Playerposition based on Chunkposition
        int posx = (int)Mathf.Floor(GameStatus.GetInstance().GetWorldPos().x / CHUNKSIZE);
        int posz = (int)Mathf.Floor(GameStatus.GetInstance().GetWorldPos().z / CHUNKSIZE);


        // generates chunks in a radius around the Player
        for (int z = -RADIUS; z <= RADIUS; z++)
        {
            for (int x = -RADIUS; x <= RADIUS; x++)
            {
                for (int y = 0; y < COLUMNHEIGHT; y++)
                {
                    Vector3 chunkPosition = new Vector3((x + posx) * CHUNKSIZE,
                                                        y * CHUNKSIZE,
                                                        (posz + z) * CHUNKSIZE);
                    Chunk  c;
                    string name = BuildChunkName(chunkPosition);
                    // Chunk already in Dictionary?
                    if (CHUNKS.TryGetValue(name, out c))
                    {
                        break;
                    }
                    else // no match in Dictionary = new Chunk
                    {
                        c = new Chunk(chunkPosition, m_TextureAtlas);
                        c.m_Chunk.transform.parent = this.transform;
                        CHUNKS.TryAdd(c.m_Chunk.name, c);
                    }

                    yield return(null);
                }
            }
        }

        foreach (KeyValuePair <string, Chunk> c in CHUNKS)
        {
            if (c.Value.m_CurrentStatus == Chunk.EStatus.DRAW)
            {
                c.Value.DrawChunk();
            }

            c.Value.m_CurrentStatus = Chunk.EStatus.DONE;
            yield return(null);
        }

        foreach (KeyValuePair <string, Chunk> c in CHUNKS)
        {
            PropSeed(c.Value.m_Chunk, c.Value.m_ChunkData);
            c.Value.Save();
            yield return(null);
        }



        Instantiate(m_PortalBPrefab, new Vector3(GameStatus.GetInstance().GetWorldPos().x, 1, GameStatus.GetInstance().GetWorldPos().z), Quaternion.identity);
        Instantiate(m_PortalDungeonIn, new Vector3(GameStatus.GetInstance().GetWorldPos().x - 10, 1, GameStatus.GetInstance().GetWorldPos().z - 10), Quaternion.identity);
        yield return(null);

        m_surface = GetComponent <NavMeshSurface>();
        m_surface.BuildNavMesh();
        GameStatus.GetInstance().m_building       = false;
        GameStatus.GetInstance().m_OverworldBuilt = true;
        yield return(null);
    }
Example #40
0
        async void IBasicConsumer.HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange,
                                                     string routingKey,
                                                     IBasicProperties properties, byte[] body)
        {
            LogContext.Current = _context.LogContext;

            if (IsStopping && _receiveSettings.NoAck == false)
            {
                await WaitAndAbandonMessage(deliveryTag).ConfigureAwait(false);

                return;
            }

            var delivery = _tracker.BeginDelivery();

            var context = new RabbitMqReceiveContext(exchange, routingKey, _consumerTag, deliveryTag, body, redelivered, properties, _context, _receiveSettings,
                                                     _model, _model.ConnectionContext);

            var activity = LogContext.IfEnabled(OperationName.Transport.Receive)?.StartReceiveActivity(context);

            try
            {
                if (!_pending.TryAdd(deliveryTag, context))
                {
                    LogContext.Warning?.Log("Duplicate BasicDeliver: {DeliveryTag}", deliveryTag);
                }

                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.PreReceive(context).ConfigureAwait(false);
                }

                await _context.ReceivePipe.Send(context).ConfigureAwait(false);

                await context.ReceiveCompleted.ConfigureAwait(false);

                if (_receiveSettings.NoAck == false)
                {
                    _model.BasicAck(deliveryTag, false);
                }

                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.PostReceive(context).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                if (_context.ReceiveObservers.Count > 0)
                {
                    await _context.ReceiveObservers.ReceiveFault(context, ex).ConfigureAwait(false);
                }

                try
                {
                    if (_receiveSettings.NoAck == false)
                    {
                        _model.BasicNack(deliveryTag, false, true);
                    }
                }
                catch (Exception ackEx)
                {
                    LogContext.Error?.Log(ackEx, "Message NACK failed: {DeliveryTag}", deliveryTag);
                }
            }
            finally
            {
                activity?.Stop();

                delivery.Dispose();

                _pending.TryRemove(deliveryTag, out _);
                context.Dispose();
            }
        }
 public void AddSocket(WebSocket socket)
 {
     _sockets.TryAdd(CreateConnectionId(), socket);
 }
        private static ColorStore GetColorStore()
        {
            ConcurrentDictionary<Color, ConsoleColor> colorMap = new ConcurrentDictionary<Color, ConsoleColor>();
            ConcurrentDictionary<ConsoleColor, Color> consoleColorMap = new ConcurrentDictionary<ConsoleColor, Color>();

            consoleColorMap.TryAdd(ConsoleColor.Black, blackEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Blue, blueEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Cyan, cyanEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkBlue, darkBlueEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkCyan, darkCyanEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkGray, darkGrayEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkGreen, darkGreenEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkMagenta, darkMagentaEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkRed, darkRedEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.DarkYellow, darkYellowEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Gray, grayEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Green, greenEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Magenta, magentaEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Red, redEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.White, whiteEquivalent);
            consoleColorMap.TryAdd(ConsoleColor.Yellow, yellowEquivalent);

            return new ColorStore(colorMap, consoleColorMap);
        }
Example #43
0
 static KnownEnums()
 {
     EnumStringResolvers.TryAdd(typeof(ClusterStateMetric), (e) => GetStringValue((ClusterStateMetric)e));
     EnumStringResolvers.TryAdd(typeof(IndicesStatsMetric), (e) => GetStringValue((IndicesStatsMetric)e));
     EnumStringResolvers.TryAdd(typeof(NodesInfoMetric), (e) => GetStringValue((NodesInfoMetric)e));
     EnumStringResolvers.TryAdd(typeof(NodesStatsMetric), (e) => GetStringValue((NodesStatsMetric)e));
     EnumStringResolvers.TryAdd(typeof(NodesStatsIndexMetric), (e) => GetStringValue((NodesStatsIndexMetric)e));
     EnumStringResolvers.TryAdd(typeof(NodesUsageMetric), (e) => GetStringValue((NodesUsageMetric)e));
     EnumStringResolvers.TryAdd(typeof(DefaultOperator), (e) => GetStringValue((DefaultOperator)e));
     EnumStringResolvers.TryAdd(typeof(ExpandWildcards), (e) => GetStringValue((ExpandWildcards)e));
     EnumStringResolvers.TryAdd(typeof(SearchType), (e) => GetStringValue((SearchType)e));
     EnumStringResolvers.TryAdd(typeof(SuggestMode), (e) => GetStringValue((SuggestMode)e));
     EnumStringResolvers.TryAdd(typeof(Refresh), (e) => GetStringValue((Refresh)e));
     EnumStringResolvers.TryAdd(typeof(Bytes), (e) => GetStringValue((Bytes)e));
     EnumStringResolvers.TryAdd(typeof(Health), (e) => GetStringValue((Health)e));
     EnumStringResolvers.TryAdd(typeof(Size), (e) => GetStringValue((Size)e));
     EnumStringResolvers.TryAdd(typeof(Level), (e) => GetStringValue((Level)e));
     EnumStringResolvers.TryAdd(typeof(WaitForEvents), (e) => GetStringValue((WaitForEvents)e));
     EnumStringResolvers.TryAdd(typeof(WaitForStatus), (e) => GetStringValue((WaitForStatus)e));
     EnumStringResolvers.TryAdd(typeof(ClusterRerouteMetric), (e) => GetStringValue((ClusterRerouteMetric)e));
     EnumStringResolvers.TryAdd(typeof(VersionType), (e) => GetStringValue((VersionType)e));
     EnumStringResolvers.TryAdd(typeof(Conflicts), (e) => GetStringValue((Conflicts)e));
     EnumStringResolvers.TryAdd(typeof(OpType), (e) => GetStringValue((OpType)e));
     EnumStringResolvers.TryAdd(typeof(IndicesShardStoresStatus), (e) => GetStringValue((IndicesShardStoresStatus)e));
     EnumStringResolvers.TryAdd(typeof(ThreadType), (e) => GetStringValue((ThreadType)e));
     EnumStringResolvers.TryAdd(typeof(GroupBy), (e) => GetStringValue((GroupBy)e));
 }
Example #44
0
        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            // If strings are allowed, attempt to write it out as a string value
            if (_converterOptions.HasFlag(EnumConverterOptions.AllowStrings))
            {
                string original = value.ToString();
                if (_nameCache != null && _nameCache.TryGetValue(original, out string transformed))
                {
                    writer.WriteStringValue(transformed);
                    return;
                }

                if (IsValidIdentifier(original))
                {
                    if (!(ParseFromAttribute && TryGetCustomAttributeValue(original, out transformed)))
                    {
                        transformed = _namingPolicy.ConvertName(original);
                    }

                    writer.WriteStringValue(transformed);

                    _nameCache?.TryAdd(original, transformed);
                    return;
                }
            }

            if (!_converterOptions.HasFlag(EnumConverterOptions.AllowNumbers))
            {
                throw new JsonException();
            }

            switch (s_enumTypeCode)
            {
            case TypeCode.Int32:
                writer.WriteNumberValue(Unsafe.As <T, int>(ref value));
                break;

            case TypeCode.UInt32:
                writer.WriteNumberValue(Unsafe.As <T, uint>(ref value));
                break;

            case TypeCode.UInt64:
                writer.WriteNumberValue(Unsafe.As <T, ulong>(ref value));
                break;

            case TypeCode.Int64:
                writer.WriteNumberValue(Unsafe.As <T, long>(ref value));
                break;

            case TypeCode.Int16:
                writer.WriteNumberValue(Unsafe.As <T, short>(ref value));
                break;

            case TypeCode.UInt16:
                writer.WriteNumberValue(Unsafe.As <T, ushort>(ref value));
                break;

            case TypeCode.Byte:
                writer.WriteNumberValue(Unsafe.As <T, byte>(ref value));
                break;

            case TypeCode.SByte:
                writer.WriteNumberValue(Unsafe.As <T, sbyte>(ref value));
                break;

            default:
                throw new JsonException();
            }
        }
        /// <summary>
        /// 设置解密之后的连接字符串明文缓存
        /// </summary>
        /// <param name="key">连接字符串名称</param>
        /// <param name="connectionString">连接字符串明文</param>
        internal static void SetConnectionString(string key, string connectionString)
        {
            string dicKey = $"connStr_{key}";

            _connStrDic.TryAdd(dicKey, connectionString);
        }
Example #46
0
        internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory)
        {
            // When this method returns null it indicates that the connection
            // factory should not use pooling.

            // We don't support connection pooling on Win9x; it lacks too
            // many of the APIs we require.
            // PoolGroupOptions will only be null when we're not supposed to pool
            // connections.
            DbConnectionPool pool = null;

            if (null != _poolGroupOptions)
            {
                Debug.Assert(ADP.s_isWindowsNT, "should not be pooling on Win9x");

                DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity;
                if (_poolGroupOptions.PoolByIdentity)
                {
                    // if we're pooling by identity (because integrated security is
                    // being used for these connections) then we need to go out and
                    // search for the connectionPool that matches the current identity.

                    currentIdentity = DbConnectionPoolIdentity.GetCurrent();

                    // If the current token is restricted in some way, then we must
                    // not attempt to pool these connections.
                    if (currentIdentity.IsRestricted)
                    {
                        currentIdentity = null;
                    }
                }

                if (null != currentIdentity)
                {
                    if (!_poolCollection.TryGetValue(currentIdentity, out pool))
                    { // find the pool
                        lock (this)
                        {
                            // Did someone already add it to the list?
                            if (!_poolCollection.TryGetValue(currentIdentity, out pool))
                            {
                                DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
                                DbConnectionPool             newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);

                                if (MarkPoolGroupAsActive())
                                {
                                    // If we get here, we know for certain that we there isn't
                                    // a pool that matches the current identity, so we have to
                                    // add the optimistically created one
                                    newPool.Startup(); // must start pool before usage
                                    bool addResult = _poolCollection.TryAdd(currentIdentity, newPool);
                                    Debug.Assert(addResult, "No other pool with current identity should exist at this point");
                                    connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Increment();
                                    pool = newPool;
                                }
                                else
                                {
                                    // else pool entry has been disabled so don't create new pools
                                    Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled");

                                    // don't need to call connectionFactory.QueuePoolForRelease(newPool) because
                                    // pool callbacks were delayed and no risk of connections being created
                                    newPool.Shutdown();
                                }
                            }
                            else
                            {
                                // else found an existing pool to use instead
                                Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds");
                            }
                        }
                    }
                    // the found pool could be in any state
                }
            }

            if (null == pool)
            {
                lock (this)
                {
                    // keep the pool entry state active when not pooling
                    MarkPoolGroupAsActive();
                }
            }
            return(pool);
        }
Example #47
0
        internal bool Prune()
        {
            // must only call from DbConnectionFactory.PruneConnectionPoolGroups on background timer thread
            // must lock(DbConnectionFactory._connectionPoolGroups.SyncRoot) before calling ReadyToRemove
            //     to avoid conflict with DbConnectionFactory.CreateConnectionPoolGroup replacing pool entry
            lock (this)
            {
                if (_poolCollection.Count > 0)
                {
                    var newPoolCollection = new ConcurrentDictionary <DbConnectionPoolIdentity, DbConnectionPool>();

                    foreach (var entry in _poolCollection)
                    {
                        DbConnectionPool pool = entry.Value;
                        if (pool != null)
                        {
                            // TODO: SQLBU 422890
                            //  Pruning a pool while a connection is currently attempting to connect
                            //  will cause the pool to be prematurely abandoned. The only known effect so
                            //  far is that the errorWait throttling will be reset when this occurs.
                            //  We should be able to avoid this situation by not pruning the pool if
                            //  it's _waitCount is non-zero (i.e. no connections *in* the pool, but also
                            //  no connections attempting to be created for the pool).

                            // Actually prune the pool if there are no connections in the pool and no errors occurred.
                            // Empty pool during pruning indicates zero or low activity, but
                            //  an error state indicates the pool needs to stay around to
                            //  throttle new connection attempts.
                            if ((!pool.ErrorOccurred) && (0 == pool.Count))
                            {
                                // Order is important here.  First we remove the pool
                                // from the collection of pools so no one will try
                                // to use it while we're processing and finally we put the
                                // pool into a list of pools to be released when they
                                // are completely empty.
                                DbConnectionFactory connectionFactory = pool.ConnectionFactory;

                                connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Decrement();
                                connectionFactory.QueuePoolForRelease(pool, false);
                            }
                            else
                            {
                                newPoolCollection.TryAdd(entry.Key, entry.Value);
                            }
                        }
                    }
                    _poolCollection = newPoolCollection;
                }

                // must be pruning thread to change state and no connections
                // otherwise pruning thread risks making entry disabled soon after user calls ClearPool
                if (0 == _poolCollection.Count)
                {
                    if (PoolGroupStateActive == _state)
                    {
                        _state = PoolGroupStateIdle;
                        SqlClientEventSource.Log.TryTraceEvent("<prov.DbConnectionPoolGroup.ClearInternal|RES|INFO|CPOOL> {0}, Idle", ObjectID);
                    }
                    else if (PoolGroupStateIdle == _state)
                    {
                        _state = PoolGroupStateDisabled;
                        SqlClientEventSource.Log.TryTraceEvent("<prov.DbConnectionPoolGroup.ReadyToRemove|RES|INFO|CPOOL> {0}, Disabled", ObjectID);
                    }
                }

                return(PoolGroupStateDisabled == _state);
            }
        }
Example #48
0
 public static void AddName(WowGuid guid, string name)
 {
     NameDict.TryAdd(guid, name);
 }
Example #49
0
        public void Parallel_PutGetDelete_Random()
        {
            const int PUTTER_CNT = 2, PUTTER_OP_CNT = 2 * 10000;
            const int GETTER_CNT = 6, GETTER_OP_CNT = 2 * 30000;
            const int DELETER_CNT = 2, DELETER_OP_CNT = 2 * 10000;

            var data = new ConcurrentDictionary <PilePointer, string>();

            var getAccessViolations    = new ConcurrentDictionary <int, int>();
            var deleteAccessViolations = new ConcurrentDictionary <int, int>();

            using (var pile = new DefaultPile())
            {
                pile.Start();

                var ipile = pile as IPile;

                // putter tasks
                var putters = new Task[PUTTER_CNT];
                for (int it = 0; it < PUTTER_CNT; it++)
                {
                    var task = new Task(() =>
                    {
                        for (int i = 0; i < PUTTER_OP_CNT; i++)
                        {
                            var str = NFX.Parsing.NaturalTextGenerator.Generate();
                            var pp  = ipile.Put(str);
                            data.TryAdd(pp, str);
                        }
                    });

                    putters[it] = task;
                }

                // getter tasks
                var getters = new Task[GETTER_CNT];
                for (int it = 0; it < GETTER_CNT; it++)
                {
                    var task = new Task(() =>
                    {
                        for (int i = 0; i < GETTER_OP_CNT; i++)
                        {
                            if (data.Count == 0)
                            {
                                System.Threading.Thread.Yield();
                                continue;
                            }
                            var idx = ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, data.Count - 1);
                            var kvp = data.ElementAt(idx);
                            try
                            {
                                var str = ipile.Get(kvp.Key);
                                Assert.AreEqual(str, kvp.Value);
                            }
                            catch (PileAccessViolationException)
                            {
                                getAccessViolations.AddOrUpdate(System.Threading.Thread.CurrentThread.ManagedThreadId, 1, (mid, val) => val + 1);
                            }
                        }
                    });
                    getters[it] = task;
                }

                // deleter tasks
                var deleters = new Task[DELETER_CNT];
                for (int it = 0; it < DELETER_CNT; it++)
                {
                    var task = new Task(() =>
                    {
                        for (int i = 0; i < DELETER_OP_CNT; i++)
                        {
                            if (data.Count == 0)
                            {
                                System.Threading.Thread.Yield();
                                continue;
                            }
                            var idx = ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, data.Count - 1);
                            var kvp = data.ElementAt(idx);
                            try
                            {
                                ipile.Delete(kvp.Key);
                            }
                            catch (PileAccessViolationException)
                            {
                                deleteAccessViolations.AddOrUpdate(System.Threading.Thread.CurrentThread.ManagedThreadId, 1, (mid, val) => val + 1);
                            }
                        }
                    });
                    deleters[it] = task;
                }


                foreach (var task in putters)
                {
                    task.Start();
                }
                foreach (var task in getters)
                {
                    task.Start();
                }
                foreach (var task in deleters)
                {
                    task.Start();
                }


                Task.WaitAll(putters.Concat(getters).Concat(deleters).ToArray());

                foreach (var kvp in getAccessViolations)
                {
                    Console.WriteLine("Get thread '{0}' {1:n0} times accessed deleted pointer", kvp.Key, kvp.Value);
                }

                foreach (var kvp in deleteAccessViolations)
                {
                    Console.WriteLine("Del thread '{0}' {1:n0} times accessed deleted pointer", kvp.Key, kvp.Value);
                }
            }
        }
Example #50
0
 public MetaData()
 {
     //if (!Data.ContainsKey(0))
     Data.TryAdd(0, (byte)0);
 }
Example #51
0
 /// <summary>
 /// جهت پیدا کردن شماره تراکنش سمت پذیرنده پس از بازگشت از صفحه پرداخت
 /// بهتر است در دیتابیس ذخیره گردد
 /// </summary>
 /// <param name="reference"></param>
 /// <param name="token"></param>
 private void SaveReference(string token, string reference, int amount)
 {
     TokenReferences.TryAdd(token, reference + "|" + amount);
 }
Example #52
0
 public void AddTypeface(FontKey key, SKTypeface typeface)
 {
     _typefaces.TryAdd(key, typeface);
 }
        /// <summary>
        /// 获取实体表的主键
        /// 获取优先级为:
        /// 1.获取Key特性的字段
        /// 2.获取字段名为id的字段(忽略大小写)
        /// 3.获取字段为以id结尾的字段(忽略大小写)
        /// </summary>
        /// <param name="type">实体类型</param>
        /// <returns>数据库表的主键</returns>
        internal static string GetTablePrimaryKey(Type type)
        {
            string key    = type.FullName;
            string pkName = string.Empty;

            if (_tablePrimaryKeyDic.TryGetValue(key, out pkName))
            {
                if (!string.IsNullOrWhiteSpace(pkName))
                {
                    return(pkName);
                }
            }

            var pros = type.GetProperties();

            if (pros == null || pros.Length == 0)
            {
                throw new ArgumentException("No Fields found in this Entity", nameof(type));
            }
            //1.获取Key特性的字段
            foreach (var p in pros)
            {
                var pkAttrs = p.GetCustomAttributes(typeof(KeyAttribute), false);
                if (pkAttrs != null && pkAttrs.Length > 0)
                {
                    var realAttr = p.GetCustomAttributes(typeof(ColumnAttribute), false);
                    if (realAttr != null && realAttr.Length > 0)
                    {
                        pkName = ((ColumnAttribute)realAttr[0]).Name;
                    }
                    else
                    {
                        pkName = p.Name;
                    }
                    _tablePrimaryKeyDic.TryAdd(key, pkName);
                    return(pkName);
                }
            }
            //2.获取字段名为id的字段(忽略大小写)
            foreach (var p in pros)
            {
                if (p.Name.Equals("id", StringComparison.OrdinalIgnoreCase))
                {
                    var realAttr = p.GetCustomAttributes(typeof(ColumnAttribute), false);
                    if (realAttr != null && realAttr.Length > 0)
                    {
                        pkName = ((ColumnAttribute)realAttr[0]).Name;
                    }
                    else
                    {
                        pkName = p.Name;
                    }
                    _tablePrimaryKeyDic.TryAdd(key, pkName);
                    return(pkName);
                }
            }
            //3.获取字段为以id结尾的字段(忽略大小写)
            foreach (var p in pros)
            {
                if (p.Name.EndsWith("id", StringComparison.OrdinalIgnoreCase))
                {
                    var realAttr = p.GetCustomAttributes(typeof(ColumnAttribute), false);
                    if (realAttr != null && realAttr.Length > 0)
                    {
                        pkName = ((ColumnAttribute)realAttr[0]).Name;
                    }
                    else
                    {
                        pkName = p.Name;
                    }
                    _tablePrimaryKeyDic.TryAdd(key, pkName);
                    return(pkName);
                }
            }
            if (string.IsNullOrWhiteSpace(pkName))
            {
                throw new ArgumentException("No PrimaryKey found in this Entity", nameof(type));
            }
            return(pkName);
        }
Example #54
0
        private void EnsureInitialized()
        {
            if (_isInitialized)
            {
                return;
            }

            lock (InitializationSyncLock)
            {
                if (_isInitialized)
                {
                    return;
                }

                var extensions = HarvestExtensions();

                var loadedExtensions =
                    new ConcurrentDictionary <string, ExtensionEntry>();

                Parallel.ForEach(extensions, (extension) =>
                {
                    if (!extension.Exists)
                    {
                        return;
                    }

                    var entry = _extensionLoader.Load(extension);

                    if (entry.IsError && L.IsEnabled(LogLevel.Warning))
                    {
                        L.LogWarning("No loader found for extension \"{0}\". This might denote a dependency is missing or the extension doesn't have an assembly.", extension.Id);
                    }

                    loadedExtensions.TryAdd(extension.Id, entry);
                });

                var loadedFeatures =
                    new Dictionary <string, FeatureEntry>();

                foreach (var loadedExtension in loadedExtensions)
                {
                    var extension = loadedExtension.Value;

                    var extensionTypes = extension
                                         .ExportedTypes
                                         .Where(t => t.GetTypeInfo().IsClass&& !t.GetTypeInfo().IsAbstract);

                    foreach (var feature in extension.ExtensionInfo.Features)
                    {
                        var featureTypes = new HashSet <Type>();

                        // Search for all types from the extensions that are not assigned to a different
                        // feature.
                        foreach (var type in extensionTypes)
                        {
                            string sourceFeature = GetSourceFeatureNameForType(type, extension.ExtensionInfo.Id);

                            if (sourceFeature == feature.Id)
                            {
                                featureTypes.Add(type);
                                _typeFeatureProvider.TryAdd(type, feature);
                            }
                        }

                        // Search in other extensions for types that are assigned to this feature.
                        var otherExtensionInfos = extensions.Where(x => x.Id != extension.ExtensionInfo.Id);

                        foreach (var otherExtensionInfo in otherExtensionInfos)
                        {
                            var otherExtension = loadedExtensions[otherExtensionInfo.Id];
                            foreach (var type in otherExtension.ExportedTypes)
                            {
                                string sourceFeature = GetSourceFeatureNameForType(type, null);

                                if (sourceFeature == feature.Id)
                                {
                                    featureTypes.Add(type);
                                    _typeFeatureProvider.TryAdd(type, feature);
                                }
                            }
                        }

                        loadedFeatures.Add(feature.Id, new CompiledFeatureEntry(feature, featureTypes));
                    }
                }
                ;

                _extensions = loadedExtensions;
                // Could we get rid of _allOrderedFeatureInfos and just have _features?
                _features = loadedFeatures;
                _allOrderedFeatureInfos = Order(loadedFeatures.Values.Select(x => x.FeatureInfo));
                _isInitialized          = true;
            }
        }
Example #55
0
        private IEnumerable<NodeId> GetNodesToSchedule(
            HashSet<NodeId> nodesToSchedule,
            VisitationTracker transitiveDependencyNodeFilter,
            ForceSkipDependenciesMode forceSkipDepsMode,
            bool scheduleMetaPips,
            HashSet<NodeId> mustExecute,
            BuildSetCalculatorStats stats,
            ref int metaPipCount)
        {
            if (forceSkipDepsMode == ForceSkipDependenciesMode.Disabled)
            {
                ScheduleDependenciesUntilCleanAndMaterialized(nodesToSchedule, transitiveDependencyNodeFilter, stats);
            }
            else
            {
                int numExplicitlySelectedProcesses, numScheduledProcesses, numExecutedProcesses, numExecutedProcessesWithoutDirty = 0;
                Func<NodeId, bool> isProcess = (node) => GetPipType(node) == PipType.Process;

                using (m_counters.StartStopwatch(PipExecutorCounter.ForceSkipDependenciesScheduleDependenciesUntilInputsPresentDuration))
                {
                    numExplicitlySelectedProcesses = nodesToSchedule.Count(isProcess);

                    // Calculate how many process pips are in the transitive dependency closure of the filtered pips
                    foreach (var node in m_graph.Nodes)
                    {
                        if (transitiveDependencyNodeFilter.WasVisited(node) && isProcess(node))
                        {
                            numExecutedProcessesWithoutDirty++;
                        }
                    }

                    ScheduleDependenciesUntilRequiredInputsPresent(nodesToSchedule, transitiveDependencyNodeFilter, mustExecute, forceSkipDepsMode);

                    numScheduledProcesses = nodesToSchedule.Where(isProcess).Count();
                    numExecutedProcesses = mustExecute.Where(isProcess).Count();
                }

                Logger.Log.DirtyBuildStats(
                    m_loggingContext,
                    (long)m_counters.GetElapsedTime(PipExecutorCounter.ForceSkipDependenciesScheduleDependenciesUntilInputsPresentDuration).TotalMilliseconds,
                    forceSkipDepsMode == ForceSkipDependenciesMode.Module,
                    numExplicitlySelectedProcesses,
                    numScheduledProcesses,
                    numExecutedProcesses,
                    numExecutedProcessesWithoutDirty - numExecutedProcesses);
            }

            int scheduledMetaPipCount = 0;

            if (scheduleMetaPips)
            {
                using (m_counters.StartStopwatch(PipExecutorCounter.BuildSetCalculatorComputeAffectedMetaPips))
                {
                    // We compute the affected meta pips from the scheduled nodes. Simply traversing the graph from
                    // the scheduled nodes is expensive, so we split the process by first computing the meta-pip frontiers,
                    // i.e., the meta-pips that directly depend on a scheduled node. This computation can be done in parallel.
                    // Assumption: the dependents of meta pips are always meta pips.

                    // (1) Compute the meta-pips frontiers from the scheduled nodes.
                    VisitationTracker visitedNodes = new VisitationTracker(m_graph);
                    ConcurrentDictionary<NodeId, Unit> metaPipFrontier = new ConcurrentDictionary<NodeId, Unit>();

                    Parallel.ForEach(
                        nodesToSchedule,
                        node =>
                        {
                            foreach (var oe in m_graph.GetOutgoingEdges(node))
                            {
                                if (GetPipType(oe.OtherNode).IsMetaPip())
                                {
                                    metaPipFrontier.TryAdd(oe.OtherNode, Unit.Void);
                                }
                            }
                        });

                    // (2) Traverse the graph from the frontiers.
                    m_visitor.VisitTransitiveDependents(
                        metaPipFrontier.Keys,
                        visitedNodes,
                        node =>
                        {
                            nodesToSchedule.Add(node);
                            ++scheduledMetaPipCount;
                            return true;
                        });
                }

                metaPipCount = scheduledMetaPipCount;
            }

            return nodesToSchedule;
        }
        protected static PropertyHelper[] GetVisibleProperties(
            Type type,
            Func <PropertyInfo, PropertyHelper> createPropertyHelper,
            ConcurrentDictionary <Type, PropertyHelper[]> allPropertiesCache,
            ConcurrentDictionary <Type, PropertyHelper[]> visiblePropertiesCache)
        {
            PropertyHelper[] result;
            if (visiblePropertiesCache.TryGetValue(type, out result))
            {
                return(result);
            }

            // The simple and common case, this is normal POCO object - no need to allocate.
            var allPropertiesDefinedOnType = true;
            var allProperties = GetProperties(type, createPropertyHelper, allPropertiesCache);

            foreach (var propertyHelper in allProperties)
            {
                if (propertyHelper.Property.DeclaringType != type)
                {
                    allPropertiesDefinedOnType = false;
                    break;
                }
            }

            if (allPropertiesDefinedOnType)
            {
                result = allProperties;
                visiblePropertiesCache.TryAdd(type, result);
                return(result);
            }

            // There's some inherited properties here, so we need to check for hiding via 'new'.
            var filteredProperties = new List <PropertyHelper>(allProperties.Length);

            foreach (var propertyHelper in allProperties)
            {
                var declaringType = propertyHelper.Property.DeclaringType;
                if (declaringType == type)
                {
                    filteredProperties.Add(propertyHelper);
                    continue;
                }

                // If this property was declared on a base type then look for the definition closest to the
                // the type to see if we should include it.
                var ignoreProperty = false;

                // Walk up the hierarchy until we find the type that actally declares this
                // PropertyInfo.
                var currentTypeInfo   = type.GetTypeInfo();
                var declaringTypeInfo = declaringType.GetTypeInfo();
                while (currentTypeInfo != null && currentTypeInfo != declaringTypeInfo)
                {
                    // We've found a 'more proximal' public definition
                    var declaredProperty = currentTypeInfo.GetDeclaredProperty(propertyHelper.Name);
                    if (declaredProperty != null)
                    {
                        ignoreProperty = true;
                        break;
                    }

                    currentTypeInfo = currentTypeInfo.BaseType?.GetTypeInfo();
                }

                if (!ignoreProperty)
                {
                    filteredProperties.Add(propertyHelper);
                }
            }

            result = filteredProperties.ToArray();
            visiblePropertiesCache.TryAdd(type, result);
            return(result);
        }
Example #57
0
 /// <summary>
 /// 新加入客户端连接
 /// </summary>
 /// <param name="id">GUID</param>
 /// <param name="client">客户端类</param>
 public void Add(Guid id, TCPClient client)
 {
     _clientDic.TryAdd(id, client);
     client.Disconnected += Client_Disconnected;
     UpdateUI();
 }
Example #58
0
 public void Register <T>(Expression <Func <IResolver, object> > factory)
 {
     Registrations.TryAdd(typeof(T), factory);
 }
Example #59
0
        public static ScheduledTaskLogEntity ExecuteSync(ITaskEntity task, ScheduledTaskEntity?scheduledTask, IUserEntity?user)
        {
            IUserEntity entityIUser = (user ?? (IUserEntity?)scheduledTask?.User.RetrieveAndRemember()) !;

            var isolation = entityIUser.TryIsolation();

            if (isolation == null)
            {
                var ientity = task as IEntity;
                isolation = ientity?.TryIsolation();
            }

            using (IsolationEntity.Override(isolation))
            {
                ScheduledTaskLogEntity stl = new ScheduledTaskLogEntity
                {
                    Task            = task,
                    ScheduledTask   = scheduledTask,
                    StartTime       = TimeZoneManager.Now,
                    MachineName     = Environment.MachineName,
                    ApplicationName = Schema.Current.ApplicationName,
                    User            = entityIUser.ToLite(),
                };

                using (AuthLogic.Disable())
                {
                    using (Transaction tr = Transaction.ForceNew())
                    {
                        stl.Save();

                        tr.Commit();
                    }
                }

                try
                {
                    var ctx = new ScheduledTaskContext(stl);
                    RunningTasks.TryAdd(stl, ctx);

                    using (UserHolder.UserSession(entityIUser))
                    {
                        using (Transaction tr = Transaction.ForceNew())
                        {
                            stl.ProductEntity = ExecuteTask.Invoke(task, ctx);

                            using (AuthLogic.Disable())
                            {
                                stl.EndTime = TimeZoneManager.Now;
                                stl.Remarks = ctx.StringBuilder.ToString();
                                stl.Save();
                            }

                            tr.Commit();
                        }
                    }
                }
                catch (Exception ex)
                {
                    using (AuthLogic.Disable())
                    {
                        if (Transaction.InTestTransaction)
                        {
                            throw;
                        }

                        var exLog = ex.LogException().ToLite();

                        using (Transaction tr = Transaction.ForceNew())
                        {
                            stl.Exception = exLog;
                            stl.EndTime   = TimeZoneManager.Now;
                            stl.Save();

                            tr.Commit();
                        }
                    }
                    throw;
                }
                finally
                {
                    RunningTasks.TryRemove(stl, out var ctx);
                    OnFinally?.Invoke(stl);
                }

                return(stl);
            }
        }
Example #60
-9
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Создание объекта ConcurrentDictionary
            var dict = new ConcurrentDictionary<String, int>();

            // Попытка добавить элемент [k1;42]
            if (dict.TryAdd("k1", 42))
                Console.WriteLine("Added");

            // Обновление значения элемента [k1;42] на [k1;21]
            if (dict.TryUpdate("k1", 21, 42))
                Console.WriteLine("42 updated to 21");

            dict["k1"] = 42; // безоговорочная перезапись значения k1

            // Добавление или обновление элемента (если существует)
            int r1 = dict.AddOrUpdate("k1", 3, (s, i) => i * 2);

            // Получение значения k2 (если его не существует - добавление в коллекцию
            int r2 = dict.GetOrAdd("k2", 3);

            Console.WriteLine(r1);
            Console.WriteLine(r2);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }