Example #1
0
        public void Queue_WithHighThreadCount_WorksCorrectly(int threads, int enqueues, int dequeues)
        {
            //The elements we insert are unique and sentinel value is -1
            int initialValue = -1;
            int currentValue = initialValue;
            ConcurrentDictionary<int, int> table = new ConcurrentDictionary<int, int>();
            Core.Queue.Queue<int> queue = new Core.Queue.Queue<int>(initialValue);

            ThreadBuilder
                .Empty()
                .AddThreads(() =>
                {
                    for (int i = 0; i < enqueues; i++)
                    {
                        int value = Interlocked.Increment(ref currentValue);
                        queue.Enqueue(value);
                    }
                }, threads)
                .AddThreads(() =>
                {
                    for (int i = 0; i < dequeues; i++)
                    {
                        int value = queue.Dequeue();
                        table.AddOrUpdate(value, x => 1, (k, v) => v + 1);
                    }
                }, threads)
                .Start();

            //The sentinel value can be returned more than once if queue is empty at the time of a pop
            int expectedPops = table.Keys.Count + (table.ContainsKey(initialValue) ? -1 : 0);
            int actualPops = table.Count(x => x.Key != initialValue && x.Value == 1);

            Assert.AreEqual(expectedPops, actualPops);
        }
Example #2
0
        public void List_WithHighThreadCount_WorksCorrectly(int threads, int adds, int removes)
        {
            //The elements we insert are unique and sentinel value is -1
            int initialValue = -1;
            int currentValue = initialValue;
            ConcurrentDictionary<int, int> table = new ConcurrentDictionary<int, int>();
            Core.List.List<int> list = new Core.List.List<int>(initialValue);
            Random random = new Random();

            ThreadBuilder
                .Empty()
                .AddThreads(() =>
                {
                    for (int i = 0; i < adds; i++)
                    {
                        int value = Interlocked.Increment(ref currentValue);
                        list.Add(value);
                    }
                }, threads)
                .AddThreads(() =>
                {
                    for (int i = 0; i < removes; i++)
                    {
                        int element = random.Next(currentValue);

                        if (table.ContainsKey(element))
                        {
                            list.Remove(element);
                            table.AddOrUpdate(element, x => 1, (k, v) => v + 1);
                        }
                    }
                }, threads)
                .Start();

            //The sentinel value can be returned more than once if queue is empty at the time of a dequeue
            int expectedAdds = table.Keys.Count + (table.ContainsKey(initialValue) ? -1 : 0);
            int actualRemoves = table.Count(x => x.Key != initialValue && x.Value == 1);

            Assert.AreEqual(expectedAdds, actualRemoves);
        }
Example #3
0
        /// <summary>
        /// Test results:
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine("**** Crypto Key Generator ****");

            int maxsize = 0;

            if (args.Length != 2)
            {
                Console.Write("Enter number of tries in loop:");
                maxsize = int.Parse(Console.ReadLine());

                Console.WriteLine();
                Console.Write("Enter desired length of key:");
                keyLength = int.Parse(Console.ReadLine());
            }
            else
            {
                maxsize   = int.Parse(args[0]);
                keyLength = int.Parse(args[1]);
            }

            int len = maxsize;

            Console.WriteLine("Running...");
            Console.WriteLine("Press [s] for status and <ESC> to stop");


            var timer = new Stopwatch();

            timer.Start();

            //do
            //{
            //    while (!Console.KeyAvailable && len > 0)
            //    {
            //        // Do something
            //        var code = CreateDibsOrderId();
            //        dict.AddOrUpdate(code, 1, (key, oldvalue) => oldvalue + 1);

            //        //Console.WriteLine("{0}", code);
            //        len--;
            //    }

            //    if (len == 0)
            //    {
            //        break;
            //    }

            //    var keypress = Console.ReadKey(true).Key;

            //    if (keypress == ConsoleKey.S)
            //    {
            //        // status
            //        Console.WriteLine("status: {0}/{1} processed", dict.Count, maxsize);
            //    }
            //    else if (keypress == ConsoleKey.Escape)
            //    {
            //        break;
            //    }

            //} while (len > 0);

            Parallel.For(1, maxsize, f =>
            {
                var code = CreateDibsOrderId(keyLength);

                if (maxsize < 10000)
                {
                    Console.WriteLine("{0}: {1}", Thread.CurrentThread.ManagedThreadId, code);
                }
                Dict.AddOrUpdate(code, 1, (key, oldvalue) => oldvalue + 1);
            });

            timer.Stop();

            Console.WriteLine("Execution time {0} ms.", timer.ElapsedMilliseconds);
            Console.WriteLine("dict contains {0} values", Dict.Count);
            Console.WriteLine("unique values: {0}", Dict.Count(x => x.Value == 1));
            Console.WriteLine("dupes: {0}", Dict.Count(x => x.Value > 1));

            Console.WriteLine("Maximun no of combinations: {0:n0}", Math.Pow(36, keyLength));
        }
Example #4
0
            /// <summary>Adds <paramref name="pid" /> to the set of active processes</summary>
            internal void AddPid(int pid)
            {
                bool added = m_activeProcesses.TryAdd(pid, 1);

                LogDebug($"AddPid({pid}) :: added: {added}; size: {m_activeProcesses.Count()}");
            }
Example #5
0
        private void button5_Click(object sender, EventArgs e)
        {
            //var time = 40;
            //StringBuilder sb = new StringBuilder();

            //var iter = 1650;
            //while (iter < 1750) {
            //    iter++;
            //    if (points.All(p => p.GetColor(iter * 40) == Color.FromArgb(255,255,255,255))) {
            //        sb.Append(iter);
            //        sb.Append(",");
            //    }
            //    time += 40;
            //}
            //textBox1.Text = sb.ToString();
            sentence.Clear();


            var iter = 0;

            ThreadPool.SetMaxThreads(32, 10);

            //StringBuilder code = new StringBuilder();
            for (iter = 0; iter < 50000; iter++)
            {
                /*Thread testThread = new Thread(new ThreadStart(() => {
                 *  StringBuilder code = new StringBuilder();
                 *  for (var num = 0; num < points.Count(); num++) {
                 *      code.Append(points[num].GetColor(iter * 40) == Color.FromArgb(255, 255, 255, 255) ? "1" : "0");
                 *  }
                 *  var codeNum = 0;
                 *  if (codes.ContainsValue(code.ToString())) codeNum = codes.Where(c => c.Value == code.ToString()).First().Key;
                 *  else {
                 *      codeNum = codes.Count();
                 *      codes.Add(codes.Count(), code.ToString());
                 *  }
                 *  if (codes.ContainsValue(code.ToString())) codeNum = codes.Where(c => c.Value == code.ToString()).First().Key;
                 *  else {
                 *      codeNum = codes.Count();
                 *      codes.Add(codes.Count(), code.ToString());
                 *  }
                 *  sentence.Add(new Tuple<int, int, string>(iter, codeNum, "_"));
                 * }));*/

                /*WaitCallback callback = new WaitCallback((object obj) => {
                 *  Console.WriteLine("Creating thread");
                 *  runningThreads++;
                 *  StringBuilder code = new StringBuilder();
                 *  for (var num = 0; num < points.Count(); num++) {
                 *      code.Append(points[num].GetColor(iter * 40) == Color.FromArgb(255, 255, 255, 255) ? "1" : "0");
                 *  }
                 *  var codeNum = 0;
                 *  if (codes.ContainsKey(code.ToString())) codeNum = codes[code.ToString()];
                 *  else {
                 *      codeNum = codes.Count();
                 *      codes.TryAdd(code.ToString(), codes.Count());
                 *  }
                 *  lock (sentence) {
                 *      sentence.Add(new Tuple<int, int, string>(iter, codeNum, "_"));
                 *  }
                 *  runningThreads--;
                 *  Console.WriteLine("Closing thread");
                 * });
                 *
                 * //callback.*/

                ThreadPool.QueueUserWorkItem((object obj) => {
                    StringBuilder code = new StringBuilder();
                    for (var num = 0; num < points.Count(); num++)
                    {
                        code.Append(points[num].GetColor((int)(((object[])obj)[0]) * 40) == Color.FromArgb(255, 255, 255, 255) ? "1" : "0");
                    }

                    Console.WriteLine(code.ToString());

                    var codeNum = 0;

                    if (codes.ContainsKey(code.ToString()))
                    {
                        codeNum = codes[code.ToString()];
                    }
                    else
                    {
                        codeNum = codes.Count();
                        lock (codes) {
                            codes.TryAdd(code.ToString(), codes.Count());
                        }
                    }

                    lock (sentence) {
                        sentence.Add((int)(((object[])obj)[0]), new Tuple <int, int, string>((int)(((object[])obj)[0]), codeNum, "_"));
                    }

                    Console.WriteLine("Closeing Thread: " + (int)(((object[])obj)[0]));
                }, new object[1] {
                    iter
                });

                //testThread.Start();

                //code = new StringBuilder();

                //for (var num = 0; num < points.Count(); num++) {
                //    code.Append(points[num].GetColor(iter * 40) == Color.FromArgb(255, 255, 255, 255) ? "1" : "0");
                //}

                //var codeNum = 0;

                //if (codes.ContainsValue(code.ToString())) codeNum = codes.Where(c => c.Value == code.ToString()).First().Key;
                //else {
                //    codeNum = codes.Count();
                //    codes.Add(codes.Count(), code.ToString());
                //}



                //sentence.Add(new Tuple<int, int, string>(iter, codeNum, "_"));
            }

            bool working                  = true;
            int  workerThreads            = 0;
            int  completionPortThreads    = 0;
            int  maxWorkerThreads         = 0;
            int  maxCompletionPortThreads = 0;

            ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads);

            while (working)
            {
                ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);

                working = workerThreads != maxWorkerThreads;

                Thread.Sleep(100);
            }

            StringBuilder final = new StringBuilder();

            foreach (KeyValuePair <int, Tuple <int, int, string> > tuple in sentence)
            {
                final.Append(tuple.Value.Item1).Append(",").Append(tuple.Value.Item2).Append(",").Append(tuple.Value.Item3).AppendLine();
            }

            File.WriteAllText("output.txt", final.ToString());

            final.Clear();

            SortedList <int, string> codesSorted = new SortedList <int, string>();

            foreach (string key in codes.Keys)
            {
                codesSorted.Add(codes[key], key);
            }

            Console.WriteLine("Length of sorted list: " + codesSorted.Count);

            foreach (KeyValuePair <int, string> value in codesSorted)
            {
                final.AppendLine($"{value.Key},{value.Value}");
            }

            File.WriteAllText("codes.txt", final.ToString());
        }
Example #6
0
 public override bool HasMoreEvents()
 {
     return(ReplayWorkers.Count(t => t.Value.HasCommands) > 0);
 }
Example #7
0
        private async Task RunPeerUpdateLoop()
        {
            int loopCount = 0;

            while (true)
            {
                try
                {
                    if (loopCount++ % 100 == 0)
                    {
                        if (_logger.IsTrace)
                        {
                            _logger.Trace($"Running peer update loop {loopCount - 1} - active: {_activePeers.Count} | candidates : {_candidatePeers.Count}");
                        }
                    }

                    try
                    {
                        CleanupCandidatePeers();
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsDebug)
                        {
                            _logger.Error("Candidate peers cleanup failed", e);
                        }
                    }

                    _peerUpdateRequested.Wait(_cancellationTokenSource.Token);
                    _peerUpdateRequested.Reset();

                    if (!_isStarted)
                    {
                        continue;
                    }

                    int availableActiveCount = _networkConfig.ActivePeersMaxCount + _staticNodes.Count -
                                               _activePeers.Count;
                    if (availableActiveCount == 0)
                    {
                        continue;
                    }

                    Interlocked.Exchange(ref tryCount, 0);
                    Interlocked.Exchange(ref newActiveNodes, 0);
                    Interlocked.Exchange(ref failedInitialConnect, 0);
                    Interlocked.Exchange(ref connectionRounds, 0);

                    SelectAndRankCandidates();
                    IReadOnlyCollection <Peer> remainingCandidates = _currentSelection.Candidates;
                    if (!remainingCandidates.Any())
                    {
                        continue;
                    }

                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        break;
                    }

                    while (true)
                    {
                        if (_cancellationTokenSource.IsCancellationRequested)
                        {
                            break;
                        }

                        availableActiveCount = _networkConfig.ActivePeersMaxCount + _staticNodes.Count -
                                               _activePeers.Count;

                        int nodesToTry = Math.Min(remainingCandidates.Count, availableActiveCount);
                        if (nodesToTry == 0)
                        {
                            break;
                        }

                        IEnumerable <Peer> candidatesToTry = remainingCandidates.Take(nodesToTry)
                                                             .Distinct(_distinctPeerComparer);
                        remainingCandidates = remainingCandidates.Skip(nodesToTry).ToList();

                        var workerBlock = new ActionBlock <Peer>(
                            SetupPeerConnection,
                            new ExecutionDataflowBlockOptions
                        {
                            MaxDegreeOfParallelism = _parallelism,
                            CancellationToken      = _cancellationTokenSource.Token
                        });

                        foreach (var candidateToTry in candidatesToTry)
                        {
                            await workerBlock.SendAsync(candidateToTry);
                        }

                        workerBlock.Complete();

                        // Wait for all messages to propagate through the network.
                        workerBlock.Completion.Wait();

                        Interlocked.Increment(ref connectionRounds);
                    }

                    if (_logger.IsDebug)
                    {
                        int activePeersCount = _activePeers.Count;
                        if (activePeersCount != _prevActivePeersCount)
                        {
                            string countersLog = string.Join(", ", _currentSelection.Counters.Select(x => $"{x.Key.ToString()}: {x.Value}"));
                            _logger.Debug($"RunPeerUpdate | {countersLog}, Incompatible: {GetIncompatibleDesc(_currentSelection.Incompatible)}, EligibleCandidates: {_currentSelection.Candidates.Count()}, " +
                                          $"Tried: {tryCount}, Rounds: {connectionRounds}, Failed initial connect: {failedInitialConnect}, Established initial connect: {newActiveNodes}, " +
                                          $"Current candidate peers: {_candidatePeers.Count}, Current active peers: {_activePeers.Count} " +
                                          $"[InOut: {_activePeers.Count(x => x.Value.OutSession != null && x.Value.InSession != null)} | " +
                                          $"[Out: {_activePeers.Count(x => x.Value.OutSession != null)} | " +
                                          $"In: {_activePeers.Count(x => x.Value.InSession != null)}]");
                        }

                        _prevActivePeersCount = activePeersCount;
                    }

                    if (_logger.IsTrace)
                    {
                        if (_logCounter % 5 == 0)
                        {
                            string nl = Environment.NewLine;
                            _logger.Trace($"{nl}{nl}All active peers: {nl} {string.Join(nl, _activePeers.Values.Select(x => $"{x.Node:s} | P2P: {_stats.GetOrAdd(x.Node).DidEventHappen(NodeStatsEventType.P2PInitialized)} | Eth62: {_stats.GetOrAdd(x.Node).DidEventHappen(NodeStatsEventType.Eth62Initialized)} | {_stats.GetOrAdd(x.Node).P2PNodeDetails?.ClientId} | {_stats.GetOrAdd(x.Node).ToString()}"))} {nl}{nl}");
                        }

                        _logCounter++;
                    }

                    if (_activePeers.Count != _networkConfig.ActivePeersMaxCount + _staticNodes.Count)
                    {
                        _peerUpdateRequested.Set();
                    }
                }
                catch (AggregateException e) when(e.InnerExceptions.Any(inner => inner is OperationCanceledException))
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Peer update loop canceled.");
                    }
                    break;
                }
                catch (OperationCanceledException)
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Peer update loop canceled");
                    }
                    break;
                }
                catch (Exception e)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error("Peer update loop failure", e);
                    }
                    break;
                }
            }
        }
Example #8
0
 /// <summary>
 /// Returns the number of TreasureWielded currently cached.
 /// </summary>
 public int GetWieldedTreasureCacheCount()
 {
     return(cachedWieldedTreasure.Count(r => r.Value != null));
 }
		private Dictionary<string, bool> GetLocalUtf8BomSignatures(IEnumerable<string> textFiles)
		{
			var bag = new ConcurrentDictionary<string, bool>();

			Console.WriteLine("Checking if local files are using UTF-8 signatures...");
			Parallel.ForEach(
				textFiles,
				file =>
				{
					var filePath = Path.Combine(Args.ProjectPath, file);
					bag[file] = IsUsingUtf8BomSignature(filePath);
				});

			Console.WriteLine("Checked {0} local files, {1} are using UTF-8 signatures.", bag.Count, bag.Count(i => i.Value));
			return bag.ToDictionary(i => i.Key, i => i.Value);
		}
Example #10
0
 public static int GetOnlineUsersCount()
 {
     return(_onlineUsers.Count(p => p.Value));
 }
 public int ConnectedUsersCount(string roomId)
 {
     return(_connections.Count(x => x.Value.RoomID == roomId));
 }
Example #12
0
        public ConcurrentDictionary <string, PackageResult> install_run(ChocolateyConfiguration config)
        {
            this.Log().Info(@"Installing the following packages:");
            this.Log().Info(ChocolateyLoggers.Important, @"{0}".format_with(config.PackageNames));
            this.Log().Info(@"By installing you accept licenses for the packages.");

            var packageInstalls = new ConcurrentDictionary <string, PackageResult>();

            foreach (var packageConfig in set_config_from_package_names_and_packages_config(config, packageInstalls).or_empty_list_if_null())
            {
                Action <PackageResult> action = null;
                if (packageConfig.SourceType == SourceType.normal)
                {
                    action = (packageResult) => handle_package_result(packageResult, packageConfig, CommandNameType.install);
                }
                var results = perform_source_runner_function(packageConfig, r => r.install_run(packageConfig, action));

                foreach (var result in results)
                {
                    packageInstalls.GetOrAdd(result.Key, result.Value);
                }
            }

            var installFailures = packageInstalls.Count(p => !p.Value.Success);
            var installWarnings = packageInstalls.Count(p => p.Value.Warning);

            this.Log().Warn(() => @"{0}{1} installed {2}/{3} package(s). {4} package(s) failed.{5}{0} See the log for details ({6}).".format_with(
                                Environment.NewLine,
                                ApplicationParameters.Name,
                                packageInstalls.Count(p => p.Value.Success && !p.Value.Inconclusive),
                                packageInstalls.Count,
                                installFailures,
                                installWarnings == 0 ? string.Empty : "{0} {1} package(s) had warnings.".format_with(Environment.NewLine, installWarnings),
                                _fileSystem.combine_paths(ApplicationParameters.LoggingLocation, ApplicationParameters.LoggingFile)
                                ));

            if (installWarnings != 0)
            {
                this.Log().Warn(ChocolateyLoggers.Important, "Warnings:");
                foreach (var warning in packageInstalls.Where(p => p.Value.Warning).or_empty_list_if_null())
                {
                    this.Log().Warn(ChocolateyLoggers.Important, " - {0}".format_with(warning.Value.Name));
                }
            }

            if (installFailures != 0)
            {
                this.Log().Error("Failures:");
                foreach (var failure in packageInstalls.Where(p => !p.Value.Success).or_empty_list_if_null())
                {
                    this.Log().Error(" - {0}".format_with(failure.Value.Name));
                }
            }

            if (installFailures != 0 && Environment.ExitCode == 0)
            {
                Environment.ExitCode = 1;
            }

            return(packageInstalls);
        }
Example #13
0
 public int Count()
 {
     return(_data.Count());
 }
Example #14
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Start"></param>
        /// <param name="Stop">We just truncate VA's at 48 bit's</param>
        /// <returns>count of new detections since last Run</returns>
        public long Run(long Start=0, long Stop = 0xFFFFffffFFFF)
        {
            DetectedFragments = new ConcurrentDictionary<long, VAScanType>();
            
            // convert index to an address 
            // then add start to it
            long i = Start;
            var block = new long[0x200]; // 0x200 * 8 = 4k
            while (i < Stop)
            {
                foreach (var scanner in CheckMethods)
                {
                    HARDWARE_ADDRESS_ENTRY locPhys = HARDWARE_ADDRESS_ENTRY.MinAddr;
                    if (DPContext.vmcs != null)
                        //locPhys = MemoryBank[j].VirtualToPhysical(DPContext.vmcs.EPTP, DPContext.CR3Value, i);
                        locPhys = BackingBlocks.VirtualToPhysical(DPContext.vmcs.EPTP, DPContext.CR3Value, i);
                    else
                        //locPhys = MemoryBank[j].VirtualToPhysical(DPContext.CR3Value, i);
                        locPhys = BackingBlocks.VirtualToPhysical(DPContext.CR3Value, i);

                    var Curr = i;
                    i += 0x1000;

                    if (HARDWARE_ADDRESS_ENTRY.IsBadEntry(locPhys))
                        continue;

                    bool GotData = false;
                    BackingBlocks.GetPageForPhysAddr(locPhys, ref block, ref GotData);
                    if (!GotData)
                        continue;

                    var scan_detect = scanner(Curr, block);
                    if (scan_detect != VAScanType.UNDETERMINED)
                    {
                        DetectedFragments.TryAdd(Curr, scan_detect);
                        if (Vtero.VerboseOutput)
                            Console.WriteLine($"Detected PE @ VA {Curr:X}");
                    }
                }
            }

            return DetectedFragments.Count();
        }
 public int GetSocketClientCount()
 {
     return(_sockets.Count());
 }
Example #16
0
        /// <summary>
        /// 启动 XNCF 模块引擎,包括初始化扫描和注册等过程
        /// </summary>
        /// <returns></returns>
        public static string StartEngine(this IServiceCollection services, IConfiguration configuration)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"[{SystemTime.Now}] 开始初始化扫描 XncfModules");
            var scanTypesCount = 0;
            var hideTypeCount  = 0;
            ConcurrentDictionary <Type, ScanTypeKind> types = new ConcurrentDictionary <Type, ScanTypeKind>();

            //所有 XNCF 模块,包括被忽略的。
            //var cache = CacheStrategyFactory.GetObjectCacheStrategyInstance();
            //using (cache.BeginCacheLock("Senparc.Ncf.XncfBase.Register", "Scan")) //在注册阶段还未完成缓存配置
            {
                try
                {
                    //遍历所有程序集
                    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        scanTypesCount++;
                        var aTypes = a.GetTypes();
                        foreach (var t in aTypes)
                        {
                            if (t.IsAbstract)
                            {
                                continue;
                            }

                            if (t.GetInterfaces().Contains(typeof(IXncfRegister)))
                            {
                                types[t] = ScanTypeKind.IXncfRegister;
                            }
                            else if (t.GetInterfaces().Contains(typeof(IXncfFunction)))
                            {
                                types[t] = ScanTypeKind.IXncfFunction; /* 暂时不收录处理 */
                            }
                            else if (t.GetCustomAttributes(true).FirstOrDefault(z => z is XncfAutoConfigurationMappingAttribute) != null
                                     /*&& t.GetInterfaces().Contains(typeof(IEntityTypeConfiguration<>))*/)
                            {
                                types[t] = ScanTypeKind.XncfAutoConfigurationMappingAttribute;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"扫描程集异常退出,可能无法获得完整程序集信息:{ex.Message}");
                }

                sb.AppendLine($"[{SystemTime.Now}] 满足条件对象:{types.Count()}");

                //先注册 XncfRegister
                {
                    //筛选
                    var allTypes = types.Where(z => z.Value == ScanTypeKind.IXncfRegister /* && z.Key.GetInterfaces().Contains(typeof(IXncfRegister))*/)
                                   .Select(z => z.Key);
                    //按照优先级进行排序
                    var orderedTypes = allTypes.OrderByDescending(z =>
                    {
                        var orderAttribute = z.GetCustomAttributes(true).FirstOrDefault(attr => attr is XncfOrderAttribute) as XncfOrderAttribute;
                        if (orderAttribute != null)
                        {
                            return(orderAttribute.Order);
                        }
                        return(0);
                    });


                    foreach (var type in orderedTypes)
                    {
                        sb.AppendLine($"[{SystemTime.Now}] 扫描到 IXncfRegister:{type.FullName}");

                        var register = type.Assembly.CreateInstance(type.FullName) as IXncfRegister;

                        if (!RegisterList.Contains(register))
                        {
                            if (RegisterList.Exists(z => z.Uid.Equals(register.Uid, StringComparison.OrdinalIgnoreCase)))
                            {
                                throw new XncfFunctionException("已经存在相同 Uid 的模块:" + register.Uid);
                            }

                            if (register.IgnoreInstall)
                            {
                                hideTypeCount++;
                            }
                            RegisterList.Add(register); //只有允许安装的才进行注册,否则执行完即结束
                            services.AddScoped(type);   //DI 中注册
                            foreach (var functionType in register.Functions)
                            {
                                services.AddScoped(functionType);//DI 中注册
                            }
                        }
                    }

                    #region 暂时不收录 IXncfFunction

                    /* 暂时不收录 */
                    ////再扫描具体方法
                    //foreach (var type in types.Where(z => z != null && z.GetInterfaces().Contains(typeof(IXncfFunction))))
                    //{
                    //    sb.AppendLine($"[{SystemTime.Now}] 扫描到 IXncfFunction:{type.FullName}");

                    //    if (!ModuleFunctionCollection.ContainsKey(type))
                    //    {
                    //        throw new NCFExceptionBase($"{type.FullName} 未能提供正确的注册方法!");
                    //    }

                    //    var function = type as IXncfFunction;
                    //    ModuleFunctionCollection[type].Add(function);
                    //}

                    #endregion
                }

                //处理 XncfAutoConfigurationMappingAttribute
                {
                    var allTypes = types.Where(z => z.Value == ScanTypeKind.XncfAutoConfigurationMappingAttribute).Select(z => z.Key);
                    foreach (var type in allTypes)
                    {
                        var obj = type.Assembly.CreateInstance(type.FullName);
                        XncfAutoConfigurationMappingList.Add(obj /*as IEntityTypeConfiguration<EntityBase>*/);
                    }
                }
            }

            var scanResult = "初始化扫描结束,共扫描 {scanTypesCount} 个程序集";
            if (hideTypeCount > 0)
            {
                scanResult += $"。其中 {hideTypeCount} 个程序集为非安装程序集,不会被缓存";
            }
            sb.AppendLine($"[{SystemTime.Now}] {scanResult}");


            //Repository & Service
            services.AddScoped(typeof(Senparc.Ncf.Repository.IRepositoryBase <>), typeof(Senparc.Ncf.Repository.RepositoryBase <>));
            services.AddScoped(typeof(ServiceBase <>));
            services.AddScoped(typeof(IServiceBase <>), typeof(ServiceBase <>));

            //ConfigurationMapping
            services.AddScoped(typeof(ConfigurationMappingBase <>));
            services.AddScoped(typeof(ConfigurationMappingWithIdBase <,>));

            //微模块进行 Service 注册
            foreach (var xncfRegister in RegisterList)
            {
                xncfRegister.AddXncfModule(services, configuration);
            }
            sb.AppendLine($"[{SystemTime.Now}] 完成模块 services.AddXncfModule():共扫描 {scanTypesCount} 个程序集");

            //支持 AutoMapper
            //引入当前系统
            services.AddAutoMapper(z => z.AddProfile <Core.AutoMapper.SystemProfile>());
            //引入所有模块
            services.AddAutoMapper(z => z.AddProfile <AutoMapper.XncfModuleProfile>());

            return(sb.ToString());
        }
Example #17
0
        /// <summary>
        /// A simple memory mapped scan over the input provided in the constructor
        /// </summary>
        /// <param name="ExitAfter">Optionally stop checking or exit early after this many candidates.  0 does not exit early.</param>
        /// <returns></returns>
        public int Analyze(int ExitAfter = 0)
        {
            CurrWindowBase = 0;
            mapSize        = (64 * 1024 * 1024);

            if (File.Exists(Filename))
            {
                using (var fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var mapName = Path.GetFileNameWithoutExtension(Filename) + DateTime.Now.ToBinary().ToString("X16");
                    using (var mmap =
                               MemoryMappedFile.CreateFromFile(fs,
                                                               mapName,
                                                               0,
                                                               MemoryMappedFileAccess.Read,
                                                               null,
                                                               HandleInheritability.Inheritable,
                                                               false))
                    {
                        if (FileSize == 0)
                        {
                            FileSize = new FileInfo(Filename).Length;
                        }

                        while (CurrWindowBase < FileSize)
                        {
                            using (var reader = mmap.CreateViewAccessor(CurrWindowBase, mapSize, MemoryMappedFileAccess.Read))
                            {
                                CurrMapBase = 0;
                                reader.ReadArray(CurrMapBase, buffers[filled], 0, 512);

                                while (CurrMapBase < mapSize)
                                {
                                    var offset = CurrWindowBase + CurrMapBase;

                                    // next page, may be faster with larger chunks but it's simple to view 1 page at a time
                                    CurrMapBase += 4096;

                                    block   = buffers[filled];
                                    filled ^= 1;

#pragma warning disable HeapAnalyzerImplicitParamsRule // Array allocation for params parameter
                                    Parallel.Invoke(() =>
                                                    Parallel.ForEach <Func <long, bool> >(CheckMethods, (check) => {
                                        check(offset);
                                    }), () => {
                                        if (CurrMapBase < mapSize)
                                        {
                                            UnsafeHelp.ReadBytes(reader, CurrMapBase, ref buffers[filled]);
                                        }
                                    }
                                                    );
                                    if (ExitAfter > 0 && ExitAfter == DetectedProcesses.Count())
                                    {
                                        return(DetectedProcesses.Count());
                                    }

                                    var progress = Convert.ToInt32((Convert.ToDouble(CurrWindowBase) / Convert.ToDouble(FileSize) * 100.0) + 0.5);
                                    if (progress != ProgressBarz.Progress)
                                    {
                                        ProgressBarz.RenderConsoleProgress(progress);
                                    }
                                }
                            } // close current window

                            CurrWindowBase += CurrMapBase;

                            if (CurrWindowBase + mapSize > FileSize)
                            {
                                mapSize = FileSize - CurrWindowBase;
                            }
                        }
                    }
                } // close map
            }     // close stream
            return(DetectedProcesses.Count());
        }
        public ActionResult GetDepositInvoice(string amount, string memo, string anon, string use, int?useId, int?useAction)
        {
            Response.AddHeader("X-Frame-Options", "DENY");
            bool isAnon = !(anon == null || anon != "1");

            if (!isAnon && !User.Identity.IsAuthenticated)
            {
                // This is a user-related invoice, and no user is logged in.
                return(RedirectToAction("Login", "Account", new { returnUrl = Request.Url.ToString() }));
            }

            string userId;

            if (isAnon)
            {
                userId = null;
            }
            else
            {
                userId = User.Identity.GetUserId();
            }

            if (string.IsNullOrEmpty(memo))
            {
                memo = "Zapread.com";
            }

            if (Convert.ToInt64(amount, CultureInfo.InvariantCulture) > 50000)
            {
                return(Json(new { success = false, message = "Deposits temporarily limited to 50000 satoshi" }));
            }

            LndRpcClient lndClient = GetLndClient();

            var inv = lndClient.AddInvoice(Convert.ToInt64(amount, CultureInfo.InvariantCulture), memo: memo.SanitizeXSS(), expiry: "3600");

            LnRequestInvoiceResponse resp = new LnRequestInvoiceResponse()
            {
                Invoice = inv.payment_request,
                Result  = "success",
                success = true,
            };

            //Create transaction record (not settled)
            using (ZapContext db = new ZapContext())
            {
                // TODO: ensure user exists?
                User user = null;
                if (userId != null)
                {
                    user = db.Users.Where(u => u.AppId == userId).First();
                }
                TransactionUse       usedFor       = TransactionUse.Undefined;
                TransactionUseAction usedForAction = TransactionUseAction.Undefined;
                int usedForId = useId != null ? useId.Value : -1;
                if (use == "tip")
                {
                    usedFor = TransactionUse.Tip;
                }
                else if (use == "votePost")
                {
                    usedFor = TransactionUse.VotePost;
                }
                else if (use == "voteComment")
                {
                    usedFor = TransactionUse.VoteComment;
                }
                else if (use == "userDeposit")
                {
                    usedFor   = TransactionUse.UserDeposit;
                    usedForId = userId != null ? user.Id : -1;
                }

                if (useAction != null)
                {
                    if (useAction.Value == 0)
                    {
                        usedForAction = TransactionUseAction.VoteDown;
                    }
                    else if (useAction.Value == 1)
                    {
                        usedForAction = TransactionUseAction.VoteUp;
                    }
                }

                var rhash_bytes = Convert.FromBase64String(inv.r_hash);
                var rhash_hex   = HexEncoder.EncodeData(rhash_bytes);

                //create a new transaction record in database
                LNTransaction t = new LNTransaction()
                {
                    User             = user,
                    IsSettled        = false,
                    IsSpent          = false,
                    Memo             = memo.SanitizeXSS(),
                    Amount           = Convert.ToInt64(amount, CultureInfo.InvariantCulture),
                    HashStr          = inv.r_hash, // B64 encoded
                    PreimageHash     = rhash_hex,
                    IsDeposit        = true,
                    TimestampCreated = DateTime.Now,
                    PaymentRequest   = inv.payment_request,
                    UsedFor          = usedFor,
                    UsedForId        = usedForId,
                    UsedForAction    = usedForAction,
                };
                db.LightningTransactions.Add(t);
                db.SaveChanges();
                resp.Id = t.Id;
            }

            if (true) // debugging
            {
                // If a listener is not already running, this should start
                // Check if there is one already online.
                var numListeners = lndTransactionListeners.Count(kvp => kvp.Value.IsLive);

                // If we don't have one running - start it and subscribe
                if (numListeners < 1)
                {
                    var listener = lndClient.GetListener();
                    lndTransactionListeners.TryAdd(listener.ListenerId, listener);           // keep alive while we wait for payment
                    listener.InvoicePaid +=
                        async(invoice) => await NotifyClientsInvoicePaid(invoice)
                        .ConfigureAwait(true);                                               // handle payment message

                    listener.StreamLost += OnListenerLost;                                   // stream lost
                    var a = new Task(() => listener.Start());                                // listen for payment
                    a.Start();
                }
            }
            return(Json(resp));
        }
        public void GetPageHtml(ConcurrentDictionary<int, HtmlNode> vehiclePageLinks, ConcurrentDictionary<string, HtmlDocument> vehicleWikiPagesContent)
        {
            foreach (var vehiclePageLink in vehiclePageLinks)
            {
                // Remove the current node so that the other threads don't reprocess it
                HtmlNode tempNode;
                vehiclePageLinks.TryRemove(vehiclePageLink.Key, out tempNode);

                // Fetch page information
                HtmlNode linkNode = vehiclePageLink.Value;
                string wikiRelativeUrl = linkNode.Attributes.Single(l => l.Name == "href").Value;
                string vehicleWikiEntryFullUrl = new Uri(new Uri(ConfigurationManager.AppSettings["BaseWikiUrl"]), wikiRelativeUrl).ToString();
                string vehicleName = linkNode.InnerText;

                // Write out the vehicle name and url
                _consoleManager.WriteBlankLine();
                _consoleManager.WriteTextLine($"Processing... {vehicleName}");
                _consoleManager.WriteTextLine($"Vehicle: {vehicleName}, Url: {vehicleWikiEntryFullUrl}");

                // Visit page and extract data
                HtmlWeb vehicleWebGet = new HtmlWeb();
                HtmlDocument vehicleWikiPage = vehicleWebGet.Load(vehicleWikiEntryFullUrl);

                // Add page to new dictionary used to extract further data
                vehicleWikiPagesContent.TryAdd(vehicleName, vehicleWikiPage);

                _consoleManager.WriteTextLine(vehicleWikiPagesContent.Count().ToString());
            }
        }
Example #20
0
        public ActionResult GetJarDepositInvoice(string amount, string memo)
        {
            string ip = GetClientIpAddress(Request);;

            if (memo == null || memo == "")
            {
                memo = "Coinpanic Community Jar";
            }

            bool useTestnet = GetUseTestnet();
            var  lndClient  = new LndRpcClient(
                host: System.Configuration.ConfigurationManager.AppSettings[useTestnet ? "LnTestnetHost" : "LnMainnetHost"],
                macaroonAdmin: System.Configuration.ConfigurationManager.AppSettings[useTestnet ? "LnTestnetMacaroonAdmin" : "LnMainnetMacaroonAdmin"],
                macaroonRead: System.Configuration.ConfigurationManager.AppSettings[useTestnet ? "LnTestnetMacaroonRead" : "LnMainnetMacaroonRead"],
                macaroonInvoice: System.Configuration.ConfigurationManager.AppSettings[useTestnet ? "LnTestnetMacaroonInvoice" : "LnMainnetMacaroonInvoice"]);

            var inv = lndClient.AddInvoice(Convert.ToInt64(amount), memo: memo, expiry: "432000");

            LnRequestInvoiceResponse resp = new LnRequestInvoiceResponse()
            {
                Invoice = inv.payment_request,
                Result  = "success",
            };

            string userId = "";

            //Check if user is returning
            if (HttpContext.Request.Cookies["CoinpanicCommunityJarUser"] != null)
            {
                var cookie = HttpContext.Request.Cookies.Get("CoinpanicCommunityJarUser");
                cookie.Expires = DateTime.Now.AddDays(7);   //update
                HttpContext.Response.Cookies.Remove("CoinpanicCommunityJarUser");
                HttpContext.Response.SetCookie(cookie);
                userId = cookie.Value;
            }
            else
            {
                HttpCookie cookie = new HttpCookie("CoinpanicCommunityJarUser");
                cookie.Value   = Guid.NewGuid().ToString();
                cookie.Expires = DateTime.Now.AddDays(7);
                HttpContext.Response.Cookies.Remove("CoinpanicCommunityJarUser");
                HttpContext.Response.SetCookie(cookie);
                userId = cookie.Value;
            }

            //Create transaction record (not settled)
            using (CoinpanicContext db = new CoinpanicContext())
            {
                var jar = db.LnCommunityJars.Where(j => j.IsTestnet == useTestnet).First();

                //is this a previous user?
                LnCJUser user;
                user = GetUserFromDb(userId, db, jar, ip);

                //create a new transaction
                LnTransaction t = new LnTransaction()
                {
                    UserId    = user.LnCJUserId,
                    IsSettled = false,
                    Memo      = memo,
                    Value     = Convert.ToInt64(amount),
                    IsTestnet = GetUseTestnet(),
                    HashStr   = inv.r_hash,
                    IsDeposit = true,
                    //TimestampSettled = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc) + TimeSpan.FromSeconds(Convert.ToInt64(invoice.settle_date)),
                    TimestampCreated  = DateTime.Now,
                    PaymentRequest    = inv.payment_request,
                    DestinationPubKey = System.Configuration.ConfigurationManager.AppSettings["LnPubkey"],
                };
                db.LnTransactions.Add(t);
                db.SaveChanges();
            }

            // If a listener is not already running, this should start

            // Check if there is one already online.
            var numListeners = lndTransactionListeners.Count(kvp => kvp.Value.IsLive);

            // If we don't have one running - start it and subscribe
            if (numListeners < 1)
            {
                var listener = lndClient.GetListener();
                lndTransactionListeners.TryAdd(listener.ListenerId, listener); //keep alive while we wait for payment
                listener.InvoicePaid += NotifyClientsInvoicePaid;              //handle payment message
                listener.StreamLost  += OnListenerLost;                        //stream lost
                var a = new Task(() => listener.Start());                      //listen for payment
                a.Start();
            }
            return(Json(resp));
        }
Example #21
0
 /// <summary>
 /// Returns the number of TreasureMaterialColor currently cached.
 /// </summary>
 public int GetTreasureMaterialColorCacheCount()
 {
     return(cachedTreasureMaterialColor.Count(r => r.Value != null));
 }
 public long GetRunningCount()
 {
     return(_subscriptionConnectionStates.Count(x => x.Value.Connection != null));
 }
Example #23
0
        public Task <int> GetDocumentCount(string documentType)
        {
            var count = Documents.Count(d => d.Key.StartsWith(documentType));

            return(Task.FromResult(count));
        }
Example #24
0
 /// <summary>
 /// Returns the number of TreasureMaterialBase currently cached.
 /// </summary>
 public int GetTreasureMaterialGroupCacheCount()
 {
     return(cachedTreasureMaterialGroups.Count(r => r.Value != null));
 }
Example #25
0
        private void InitRealms()
        {
            this.realms = loadRealms();

            var flat =
                from realm in realms
                from rgroup in realm.groups
                from location in rgroup.Locations
                from person in location.People
                select new Tuple<IndexKey, Person>(
                        new IndexKey(realm.RealmName, rgroup.GroupName, location.LocationName, person.Name),
                        person);

            log.InfoFormat("flat {0}", flat.Count());

            this.peopleIndex = new ConcurrentDictionary<IndexKey,Person>(flat.ToDictionary(
                (realmKey) => realmKey.Item1,
                (realmValue) => realmValue.Item2));
            log.InfoFormat("index {0}", peopleIndex.Count());
            foreach (var item in peopleIndex)
            {
                log.InfoFormat("index {0} {1}", item.Key, item.Value.Name);
            }
        }
Example #26
0
 /// <summary>
 /// Returns the number of weenies currently cached.
 /// </summary>
 public int GetWeenieCacheCount()
 {
     return(weenieCache.Count(r => r.Value != null));
 }
Example #27
0
 public bool IsEmpty()
 {
     return(_Clients.Count() == 0);
 }
Example #28
0
 /// <summary>
 /// Returns the number of LandblockInstances currently cached.
 /// </summary>
 public int GetLandblockInstancesCacheCount()
 {
     return(cachedLandblockInstances.Count(r => r.Value != null));
 }
 /// <summary>
 ///    Get Task Count
 /// </summary>
 /// <returns></returns>
 public int Count()
 {
     return(TasksContainer.Count());
 }
Example #30
0
 /// <summary>
 /// Returns the number of PointsOfInterest currently cached.
 /// </summary>
 public int GetPointsOfInterestCacheCount()
 {
     return(cachedPointsOfInterest.Count(r => r.Value != null));
 }
Example #31
0
 private int GetRunningJobsCount() => _jobs.Count(x => x.Value.Status == JobStatus.InProgress);
Example #32
0
 /// <summary>
 /// Returns the number of Spells currently cached.
 /// </summary>
 public int GetSpellCacheCount()
 {
     return(spellCache.Count(r => r.Value != null));
 }
Example #33
0
        //client method sends data from server program to client program
        private void ClientMethod(Client client)
        {
            Packet packet;

            try
            {
                //while client is reading data
                while ((packet = client.Read()) != null)
                {
                    switch (packet.mPacketType)
                    {
                    //send message to everyone
                    case PacketType.chatMessage:
                        ChatMessagePacket chatMessagePacket = (ChatMessagePacket)packet;
                        foreach (Client onlineClient in clients.Values)
                        {
                            onlineClient.Send(packet);
                        }
                        break;

                    //send disconnect message to everyone
                    case PacketType.disconnectMessage:
                        DisconnectMessagePacket disconnectPacket = (DisconnectMessagePacket)packet;
                        foreach (Client onlineClient in clients.Values)
                        {
                            onlineClient.Send(packet);
                        }
                        break;

                    //send connect message
                    case PacketType.connectMessage:
                        ConnectMessagePacket connectMessage = (ConnectMessagePacket)packet;
                        foreach (Client onlineClient in clients.Values)
                        {
                            onlineClient.Send(packet);
                        }
                        break;

                    //send private message to one user
                    case PacketType.privateMessage:
                        PrivateMessagePacket privateMessage = (PrivateMessagePacket)packet;
                        for (int i = 0; i < clients.Count(); i++)
                        {
                            if (i == privateMessage.mReceiver)
                            {
                                clients[i].Send(packet);
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            //if try catch fails send error message
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
            }
            //close client and remove from concurrent bag
            finally
            {
                for (int i = 0; i < clients.Count(); i++)
                {
                    //clients[i].Close();
                    clients.TryRemove(i, out client);
                }
            }
        }
Example #34
0
 /// <summary>
 /// Returns the number of Events currently cached.
 /// </summary>
 public int GetEventsCacheCount()
 {
     return(cachedEvents.Count(r => r.Value != null));
 }
Example #35
0
 /// <summary>
 /// Returns the number of Encounters currently cached.
 /// </summary>
 public int GetEncounterCacheCount()
 {
     return(cachedEncounters.Count(r => r.Value != null));
 }
Example #36
0
 /// <summary>
 /// Returns the number of TreasureDeath currently cached.
 /// </summary>
 public int GetDeathTreasureCacheCount()
 {
     return(cachedDeathTreasure.Count(r => r.Value != null));
 }
		private Dictionary<string, bool> GetLocalOnlyAnsiCharacters(Dictionary<string, int> tfsEncodings)
		{
			var bag = new ConcurrentDictionary<string, bool>();

			Console.WriteLine("Checking if local files are using non-ANSI characters...");
			Parallel.ForEach(
				tfsEncodings,
				item =>
				{
					var filePath = Path.Combine(Args.ProjectPath, item.Key);
					bag[item.Key] = IsUsingOnlyAnsiCharacters(filePath, item.Value);
				});

			Console.WriteLine("Checked {0} local files, {1} are using non-ANSI characters.", bag.Count, bag.Count(i => !i.Value));
			return bag.ToDictionary(i => i.Key, i => i.Value);
		}
        private static ConcurrentDictionary<string, AppProcess> SetupAppProcesses(ProcessControlConfiguration serverConfig)
        {
            var appServers = new ConcurrentDictionary<string, AppProcess>();

            foreach (var val in serverConfig.ProcessInstances)
            {
                AppProcess module = SetupAppProcess(val);
                if (module != null)
                {
                    string guid = module.ProcessGuid;

                    appServers.TryAdd(guid, module);
                }
            }

            logger.DebugFormat("Setup [{0}] worker processes.", appServers.Count());

            return appServers;
        }