public SpeechService()
        {
            this.textToSpeech = new TextToSpeech(Application.Context, this);
            this.textToSpeech.SetOnUtteranceProgressListener(this);

            this.inFlightSpeech = new ConcurrentDictionary<int, AsyncSubject<Unit>>();
        }
        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;
        }
        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 #4
0
 static void test3()
 {
     ConcurrentDictionary<string, string> list = new ConcurrentDictionary<string, string>();
     list["a"]="a";
     list["b"] = "b";
     Console.WriteLine(list.Count);
 }
        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);
            }
        }
 public FileSystemRefreshableWatcher(IFileSystemWatcher watcher) : base(watcher)
 {
     _refreshTokenSource = new CancellationTokenSource();
     _waitingThreadsEvents = new ConcurrentDictionary<Thread, ManualResetEventSlim>();
     IsRefreshing = false;
     _refreshLock = new object();
 }
        public LightningEnvironment(string directory, EnvironmentOpenFlags openFlags)
        {
            if (String.IsNullOrWhiteSpace(directory))
                throw new ArgumentException("Invalid directory name");

            IntPtr handle = default(IntPtr);
            Native.Execute(() => Native.mdb_env_create(out handle));

            _shouldDispose = true;
            
            _handle = handle;

            this.Directory = directory;
            _openFlags = openFlags;

            _mapSize = DefaultMapSize;
            _maxDbs = DefaultMaxDatabases;

            _openedDatabases = new ConcurrentDictionary<string, LightningDatabase>();
            _databasesForReuse = new HashSet<uint>();

            ConverterStore = new ConverterStore();
            var defaultConverters = new DefaultConverters();
            defaultConverters.RegisterDefault(this);
        }
Example #8
0
 public ClusterMembership(ClusterMembershipConfiguration config,  ILogger logger)
 {
     lastPingTime = DateTime.UtcNow;
     this.config = config;
     this.logger = logger;
     clusterMembers = new ConcurrentDictionary<SocketEndpoint, ClusterMemberMeta>();
 }
 /// <summary>Static constructor.</summary>
 static QueryCacheManager()
 {
     Cache = new MemoryCache(new MemoryCacheOptions());
     DefaultMemoryCacheEntryOptions = new MemoryCacheEntryOptions();
     CachePrefix = "Z.EntityFramework.Plus.QueryCacheManager;";
     CacheTags = new ConcurrentDictionary<string, List<string>>();
 }
 public SocketEventClient(string id, string url)
 {
     this.ClientId = id;
     this.Url = url;
     this.eventStore = new ConcurrentDictionary<string, dynamic>();
     this.locker = new Semaphore(1, 1);
 }
        /// <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 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();
            }
        }
Example #13
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 #14
0
 public WorkContext()
 {
     DoNotTouchAgainIfMissingReferences = new ConcurrentDictionary<int, ConcurrentSet<string>>();
        CurrentlyRunningQueries = new ConcurrentDictionary<string, ConcurrentSet<ExecutingQueryInfo>>(StringComparer.OrdinalIgnoreCase);
        MetricsCounters = new MetricsCountersManager();
     InstallGauges();
 }
Example #15
0
        public Consumer(string groupName, ConsumerSetting setting)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException("groupName");
            }
            GroupName = groupName;
            Setting = setting ?? new ConsumerSetting();

            _lockObject = new object();
            _subscriptionTopics = new Dictionary<string, HashSet<string>>();
            _topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
            _pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
            _remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
            _adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            _remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));

            if (Setting.MessageHandleMode == MessageHandleMode.Sequential)
            {
                _consumingMessageQueue = new BlockingCollection<ConsumingMessage>();
                _consumeMessageWorker = new Worker("ConsumeMessage", () => HandleMessage(_consumingMessageQueue.Take()));
            }
            _messageRetryQueue = new BlockingCollection<ConsumingMessage>();
        }
Example #16
0
        static FooDb()
        {
            var data = Enumerable.Range(1, 10)
                                 .Select(i => new Foo { Id = i, Name = string.Format("Foo {0}", i) });

            foos = new ConcurrentDictionary<int, Foo>(data.ToDictionary(f => f.Id, f => f));
        }
            public void ShouldBeAbleToPullExistingInfoFromCache()
            {
                var monitorConfig = new MonitorConfig { Name = "Test" };
                var reduceLevels = new List<ReduceLevel>();

                var connection = new Mock<IDbConnection>();
                var connectionInstance = connection.Object;

                var storageCommands = new Mock<IStorageCommands>();
                storageCommands.Setup(x => x.CreateConfigAndReduceLevels(monitorConfig, reduceLevels, connectionInstance));

                var setupSystemTables = new Mock<ISetupSystemTables>();
                setupSystemTables.Setup(x => x.ValidateAndCreateDataTables(connectionInstance)).Verifiable();

                var monitorConfigsDictionary = new ConcurrentDictionary<string, MonitorConfig>();

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

                var storageFactory = new Mock<IStorageFactory>();
                storageFactory.Setup(x => x.CreateConnection()).Returns(connectionInstance).Verifiable();

                var settings = BuildSettings();

                var defaults = new SetupMonitorConfig(storageCommands.Object, setupSystemTables.Object, cache.Object, storageFactory.Object, settings.Object);
                defaults.CreateDefaultReduceLevels(monitorConfig, reduceLevels);

                Assert.Equal(1, monitorConfigsDictionary.Count);
                Assert.True(monitorConfigsDictionary.ContainsKey("Test"));

                storageCommands.VerifyAll();
                setupSystemTables.VerifyAll();
                storageFactory.VerifyAll();
                cache.VerifyAll();
            }
        private HttpConfiguration(HttpConfiguration configuration, HttpControllerSettings settings)
        {
            _routes = configuration.Routes;
            _filters = configuration.Filters;
            _messageHandlers = configuration.MessageHandlers;
            _properties = configuration.Properties;
            _dependencyResolver = configuration.DependencyResolver;
            IncludeErrorDetailPolicy = configuration.IncludeErrorDetailPolicy;

            // per-controller settings
            Services = settings.IsServiceCollectionInitialized ? settings.Services : configuration.Services;
            _formatters = settings.IsFormatterCollectionInitialized ? settings.Formatters : configuration.Formatters;
            ParameterBindingRules = settings.IsParameterBindingRuleCollectionInitialized ? settings.ParameterBindingRules : configuration.ParameterBindingRules;

            // Use the original configuration's initializer so that its Initialize()
            // will perform the same logic on this clone as on the original.
            Initializer = configuration.Initializer;

            // create a new validator cache if the validator providers have changed
            if (settings.IsServiceCollectionInitialized &&
                !settings.Services.GetModelValidatorProviders().SequenceEqual(configuration.Services.GetModelValidatorProviders()))
            {
                ModelValidatorCache validatorCache = new ModelValidatorCache(new Lazy<IEnumerable<ModelValidatorProvider>>(() => Services.GetModelValidatorProviders()));
                RegisterForDispose(validatorCache);
                settings.Services.Replace(typeof(IModelValidatorCache), validatorCache);
            }
        }
Example #19
0
 public ServerConfig(IEnumerable<Tuple<WikiConfig, IPageCache>> config)
 {
     configMap = new ConcurrentDictionary<string, Tuple<WikiConfig, MasterRepository, IPageCache>>(
         config.ToDictionary(
             c => CreateSafeName(c.Item1.SiteName),
             c => new Tuple<WikiConfig, MasterRepository, IPageCache>(c.Item1, new MasterRepository(c.Item1.Convertor.FileExtension), c.Item2)));
 }
        private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum,
            TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads, LimitValue maxPendingItemsLimit)
        {
            Instance = this;
            DelayWarningThreshold = delayWarningThreshold;
            WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum;
            TurnWarningLengthThreshold = turnWarningLengthThreshold;
            applicationTurnsStopped = false;
            MaxPendingItemsLimit = maxPendingItemsLimit;
            workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>();
            RunQueue = new WorkQueue();
            logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads);
            Pool = new WorkerPool(this, maxActiveThreads, injectMoreWorkerThreads);
            IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount);
            IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength);

            if (!StatisticsCollector.CollectShedulerQueuesStats) return;

            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo);
            FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo);
        }
        public CouchbaseLiteHttpClientFactory(CookieStore cookieStore)
        {
            this.cookieStore = cookieStore;
            Headers = new ConcurrentDictionary<string,string>();

            // Disable SSL 3 fallback to mitigate POODLE vulnerability.
            ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;

            //
            // Source: http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx
            // ServerCertificateValidationCallback returns true if either of the following criteria are met:
            // The certificate is valid and signed with a valid root certificate.
            // The certificate is self-signed by the server that returned the certificate.
            //
            ServicePointManager.ServerCertificateValidationCallback = 
            (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                // If the certificate is a valid, signed certificate, return true.
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return true;
                }

                // If there are errors in the certificate chain, look at each error to determine the cause.
                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    if (chain != null && chain.ChainStatus != null)
                    {
                        foreach (X509ChainStatus status in chain.ChainStatus)
                        {
                            if ((certificate.Subject == certificate.Issuer) &&
                                (status.Status == X509ChainStatusFlags.UntrustedRoot))
                            {
                                // Self-signed certificates with an untrusted root are valid. 
                                continue;
                            }
                            else
                            {
                                if (status.Status != X509ChainStatusFlags.NoError)
                                {
                                    // If there are any other errors in the certificate chain, the certificate is invalid,
                                    // so the method returns false.
                                    return false;
                                }
                            }
                        }
                    }

                    // When processing reaches this line, the only errors in the certificate chain are 
                    // untrusted root errors for self-signed certificates. These certificates are valid
                    // for default Exchange server installations, so return true.
                    return true;
                }
                else
                {
                    // In all other cases, return false.
                    return false;
                }
            };
        }
Example #22
0
        /********************************************************
        * PUBLIC CONSTRUCTOR
        *********************************************************/
        /// <summary>
        /// Console result handler constructor.
        /// </summary>
        /// <remarks>Setup the default sampling and notification periods based on the backtest length.</remarks>
        public ConsoleResultHandler(AlgorithmNodePacket packet)
        {
            FinalStatistics = new Dictionary<string, string>();
            Log.Trace("Launching Console Result Handler: QuantConnect v2.0");
            Messages = new ConcurrentQueue<Packet>();
            Charts = new ConcurrentDictionary<string, Chart>();
            _chartLock = new Object();
            _isActive = true;

            // we expect one of two types here, the backtest node packet or the live node packet
            if (packet is BacktestNodePacket)
            {
                var backtest = packet as BacktestNodePacket;
                _algorithmNode = new BacktestConsoleStatusHandler(backtest);
            }
            else
            {
                var live = packet as LiveNodePacket;
                if (live == null)
                {
                    throw new ArgumentException("Unexpected AlgorithmNodeType: " + packet.GetType().Name);
                }
                _algorithmNode = new LiveConsoleStatusHandler(live);
            }

            _resamplePeriod = _algorithmNode.ComputeSampleEquityPeriod();

            //Notification Period for pushes:
            _notificationPeriod = TimeSpan.FromSeconds(5);
        }
Example #23
0
	HashSet<ILVariable> localVariablesToDefine = new HashSet<ILVariable>(); // local variables that are missing a definition
	
	/// <summary>
	/// Creates the body for the method definition.
	/// </summary>
	/// <param name="methodDef">Method definition to decompile.</param>
	/// <param name="context">Decompilation context.</param>
	/// <param name="parameters">Parameter declarations of the method being decompiled.
	/// These are used to update the parameter names when the decompiler generates names for the parameters.</param>
	/// <param name="localVariables">Local variables storage that will be filled/updated with the local variables.</param>
	/// <returns>Block for the method body</returns>
	public static BlockStatement CreateMethodBody(MethodDefinition methodDef,
	                                              DecompilerContext context,
	                                              IEnumerable<ParameterDeclaration> parameters = null,
	                                              ConcurrentDictionary<int, IEnumerable<ILVariable>> localVariables = null)
	{
		if (localVariables == null)
			localVariables = new ConcurrentDictionary<int, IEnumerable<ILVariable>>();
		
		MethodDefinition oldCurrentMethod = context.CurrentMethod;
		Debug.Assert(oldCurrentMethod == null || oldCurrentMethod == methodDef);
		context.CurrentMethod = methodDef;
		try {
			AstMethodBodyBuilder builder = new AstMethodBodyBuilder();
			builder.methodDef = methodDef;
			builder.context = context;
			builder.typeSystem = methodDef.Module.TypeSystem;
			if (Debugger.IsAttached) {
				return builder.CreateMethodBody(parameters, localVariables);
			} else {
				try {
					return builder.CreateMethodBody(parameters, localVariables);
				} catch (OperationCanceledException) {
					throw;
				} catch (Exception ex) {
					throw new ICSharpCode.Decompiler.DecompilerException(methodDef, ex);
				}
			}
		} finally {
			context.CurrentMethod = oldCurrentMethod;
		}
	}
        private async Task ProcessAsync(
            ConcurrentDictionary<Document, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>> documentMap)
        {
            using (Logger.LogBlock(FunctionId.FindReference_ProcessAsync, _cancellationToken))
            {
                // quick exit
                if (documentMap.Count == 0)
                {
                    return;
                }

                var wrapper = new ProgressWrapper(_progress, documentMap.Count);

                // Get the connected components of the dependency graph and process each individually.
                // That way once a component is done we can throw away all the memory associated with
                // it.
                var connectedProjects = _dependencyGraph.GetDependencySets(_cancellationToken);
                var projectMap = CreateProjectMap(documentMap);

                foreach (var projectSet in connectedProjects)
                {
                    _cancellationToken.ThrowIfCancellationRequested();

                    await ProcessProjectsAsync(projectSet, projectMap, wrapper).ConfigureAwait(false);
                }
            }
        }
        public ServerListReport(IPAddress listen, ushort port, Action<string, string> log, Action<string, string> logError)
        {
            Log = log;
            LogError = logError;

            GeoIP.Initialize(log, Category);

            Servers = new ConcurrentDictionary<string, GameServer>();

            Thread = new Thread(StartServer) {
                Name = "Server Reporting Socket Thread"
            };
            Thread.Start(new AddressInfo() {
                Address = listen,
                Port = port
            });

            new Thread(StartCleanup) {
                Name = "Server Reporting Cleanup Thread"
            }.Start();

            new Thread(StartDynamicInfoReload) {
                Name = "Dynamic Info Reload Thread"
            }.Start();
        }
Example #26
0
        public LcdpServer(ILcdpPacketSerializer lcdpPacketSerializer, IListener listener, IForwarder forwarder, IResolver resolver)
        {
            this.lcdpPacketSerializer = lcdpPacketSerializer;

            this.listener = listener;
            this.forwarder = forwarder;

            this.messages = new ConcurrentDictionary<string, LcdpMessage>();

            this.ChunkExpirationTimeMilliseconds = 5000;

            this.compressors = new Dictionary<byte, ICompressor>();
            this.serializers = new Dictionary<byte, ISerializer>();

            for(byte b = 0; b < byte.MaxValue; ++b)
            {
                ICompressor compressor = resolver.Resolve<ICompressor>(b.ToString());
                if (compressor != null)
                {
                    compressors[b] = compressor;
                }

                ISerializer serializer = resolver.Resolve<ISerializer>(b.ToString());
                if (serializer != null)
                {
                    serializers[b] = serializer;
                }
            }
        }
Example #27
0
 static Handler()
 {
     //current = new Handler(Guid.NewGuid().ToString());
     _defaultSessionId = Guid.NewGuid().ToString();
     _sessionHandlers = new ConcurrentDictionary<string, Handler>();
     _sessionHandlers[_defaultSessionId]= new Handler(_defaultSessionId);
 }
Example #28
0
 public Room()
 {
     PlayerReferences = new SafeCollection<Reference<Player>>();
     Items = new SafeCollection<Item>();
     Spawns = new Spawns();
     AdjacentRoomReferences = new ConcurrentDictionary<char, Reference<Room>>();
 }
Example #29
0
 public Evictor(ConcurrentDictionary<string, ServerCacheItem> dictionary)
 {
     _cache = dictionary;
     _evictionPeriod = Convert.ToInt32(ConfigurationManager.AppSettings["EvictionPeriod"] ?? "60000");
     _evictionTimer = new Timer(AtEvictionPeriod, null, _evictionPeriod, _evictionPeriod);
     _evictionClass = ConfigurationManager.AppSettings["EvictionStrategyClass"] ?? "HoC.Server.Eviction.LRUEvictionStrategy";
 }
Example #30
0
        /// <summary>
        /// Default constructor for the WizardryGameServer class.
        /// </summary>
        public WizardryGameServer()
        {
            graphics = new GraphicsDeviceManager( this );
            Content.RootDirectory = "Content";
            textureProvider = new TextureProvider( Content );

            // Windows Settings for the XNA window
            Window.Title = "Wizardry Server";
            graphics.PreferredBackBufferWidth = 200;
            graphics.PreferredBackBufferHeight = 1;

            // Set up the lobbies list
            lobbies = new GameLobby[GameSettings.MAX_LOBBIES];
            for ( int i = 0; i < GameSettings.MAX_LOBBIES; ++i )
            {
                lobbies[i] = null;
            }

            playerLobbies = new ConcurrentDictionary<long, int>();

            // Setup the server configuration
            NetPeerConfiguration config = new NetPeerConfiguration( GameSettings.APP_NAME );
            config.Port = GameSettings.SERVER_PORT_NUM;
            config.EnableMessageType( NetIncomingMessageType.DiscoveryRequest );

            // Start the server
            server = new NetServer( config );
            server.Start();
            WriteConsoleMessage( "Server starting!" );

            // Start the Packet Receiver thread
            Thread packets = new Thread( new ThreadStart( this.PacketProcessor ) );
            packets.Start();
        }