示例#1
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();
        }
示例#2
0
文件: Evictor.cs 项目: nittikkin/hoc
 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";
 }
示例#3
0
 static Handler()
 {
     //current = new Handler(Guid.NewGuid().ToString());
     _defaultSessionId = Guid.NewGuid().ToString();
     _sessionHandlers = new ConcurrentDictionary<string, Handler>();
     _sessionHandlers[_defaultSessionId]= new Handler(_defaultSessionId);
 }
示例#4
0
        public SpeechService()
        {
            this.textToSpeech = new TextToSpeech(Application.Context, this);
            this.textToSpeech.SetOnUtteranceProgressListener(this);

            this.inFlightSpeech = new ConcurrentDictionary<int, AsyncSubject<Unit>>();
        }
        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;
        }
        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();
        }
        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;
        }
示例#8
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;
			}
		}
        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 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;
                }
            };
        }
示例#11
0
 static void test3()
 {
     ConcurrentDictionary<string, string> list = new ConcurrentDictionary<string, string>();
     list["a"]="a";
     list["b"] = "b";
     Console.WriteLine(list.Count);
 }
示例#12
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)));
 }
        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);
        }
示例#14
0
            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();
            }
 public FileSystemRefreshableWatcher(IFileSystemWatcher watcher) : base(watcher)
 {
     _refreshTokenSource = new CancellationTokenSource();
     _waitingThreadsEvents = new ConcurrentDictionary<Thread, ManualResetEventSlim>();
     IsRefreshing = false;
     _refreshLock = new object();
 }
示例#16
0
 public Room()
 {
     PlayerReferences = new SafeCollection<Reference<Player>>();
     Items = new SafeCollection<Item>();
     Spawns = new Spawns();
     AdjacentRoomReferences = new ConcurrentDictionary<char, Reference<Room>>();
 }
示例#17
0
文件: Consumer.cs 项目: uliian/equeue
        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>();
        }
        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);
                }
            }
        }
示例#19
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;
                }
            }
        }
        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);
        }
示例#21
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);
        }
示例#22
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));
        }
示例#23
0
 public ClusterMembership(ClusterMembershipConfiguration config,  ILogger logger)
 {
     lastPingTime = DateTime.UtcNow;
     this.config = config;
     this.logger = logger;
     clusterMembers = new ConcurrentDictionary<SocketEndpoint, ClusterMemberMeta>();
 }
示例#24
0
 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;
        }
示例#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);
        }
示例#27
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.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>Static constructor.</summary>
 static QueryCacheManager()
 {
     Cache = new MemoryCache(new MemoryCacheOptions());
     DefaultMemoryCacheEntryOptions = new MemoryCacheEntryOptions();
     CachePrefix = "Z.EntityFramework.Plus.QueryCacheManager;";
     CacheTags = new ConcurrentDictionary<string, List<string>>();
 }
示例#29
0
	    public WorkContext()
	    {
	        DoNotTouchAgainIfMissingReferences = new ConcurrentDictionary<int, ConcurrentSet<string>>();
            CurrentlyRunningQueries = new ConcurrentDictionary<string, ConcurrentSet<ExecutingQueryInfo>>(StringComparer.OrdinalIgnoreCase);
            MetricsCounters = new MetricsCountersManager();
	        InstallGauges();
	    }
        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);
            }
        }
示例#31
0
        private async Task ExecuteJob(ExecutedJob job, ITransaction transaction)
        {
            if (!_listeners.ContainsKey(job.Name) && !_listenersNoArgs.ContainsKey(job.Name))
            {
                await OnJobError(job, new NoHandlerFoundException(job), transaction);

                return;
            }

            await OnJobStart(job, transaction);

            await transaction.ExecuteAsync();

            transaction = _connection.GetDatabase().CreateTransaction();

            try
            {
                if (_listeners.ContainsKey(job.Name))
                {
                    await _listeners[job.Name](job.Parameters);
                }
                else
                {
                    await _listenersNoArgs[job.Name]();
                }
            }
            catch (Exception e)
            {
                await OnJobError(job, e, transaction);

                return;
            }

            try
            {
                transaction.StringIncrementAsync($"{_options.KeyPrefix}_job_{job.Name}_run_count");
                transaction.ListRemoveAsync($"{_options.KeyPrefix}_progress", job.RunId.ToString());
                transaction.StringIncrementAsync($"{_options.KeyPrefix}_stats_total_runs");
                await SaveJobRun(job, JobStatus.Success, transaction);

                switch (job.Type)
                {
                case JobType.Immediate:
                    await OnImmediateJobFinish(job, transaction);

                    break;

                case JobType.Scheduled:
                    await OnScheduledJobFinish(job, transaction);

                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                await transaction.ExecuteAsync(CommandFlags.FireAndForget);
            }
        }
示例#32
0
 public PhotonWireOutboundS2SPeer(ApplicationBase application)
     : base(application)
 {
     Items = new ConcurrentDictionary <object, object>();
 }
 /// <summary>
 /// Create an instance of RequestResponseAgent.
 /// </summary>
 /// <param name="modelMsgSender">The interface for send request message to the server.</param>
 public RequestResponseAgent(IRequestMessageSender modelMsgSender)
 {
     Contract.Requires(modelMsgSender != null);
     _modelSender        = modelMsgSender;
     _reqReponseTaskDict = new ConcurrentDictionary <Guid, RequestResponseTask>();
 }
        internal static IDictionary <string, AzureEnvironment> InitializeBuiltInEnvironments(IHttpOperations httpOperations)
        {
            IDictionary <string, AzureEnvironment> armAzureEnvironments = null;

            try
            {
                var armMetadataRequestUri = Environment.GetEnvironmentVariable(ArmMetadataEnvVariable);
                if (!string.IsNullOrEmpty(armMetadataRequestUri))
                {
                    armAzureEnvironments = InitializeEnvironmentsFromArm(httpOperations, armMetadataRequestUri).Result;
                }
            }
            catch (Exception)
            {
                armAzureEnvironments = null;
            }

            if (armAzureEnvironments != null)
            {
                return(armAzureEnvironments);
            }

            var azureCloud = new AzureEnvironment
            {
                Name = EnvironmentName.AzureCloud,
                PublishSettingsFileUrl   = AzureEnvironmentConstants.AzurePublishSettingsFileUrl,
                ServiceManagementUrl     = AzureEnvironmentConstants.AzureServiceEndpoint,
                ResourceManagerUrl       = AzureEnvironmentConstants.AzureResourceManagerEndpoint,
                ManagementPortalUrl      = AzureEnvironmentConstants.AzureManagementPortalUrl,
                ActiveDirectoryAuthority = AzureEnvironmentConstants.AzureActiveDirectoryEndpoint,
                ActiveDirectoryServiceEndpointResourceId = AzureEnvironmentConstants.AzureServiceEndpoint,
                StorageEndpointSuffix = AzureEnvironmentConstants.AzureStorageEndpointSuffix,
                GalleryUrl            = AzureEnvironmentConstants.GalleryEndpoint,
                SqlDatabaseDnsSuffix  = AzureEnvironmentConstants.AzureSqlDatabaseDnsSuffix,
                GraphUrl = AzureEnvironmentConstants.AzureGraphEndpoint,
                TrafficManagerDnsSuffix = AzureEnvironmentConstants.AzureTrafficManagerDnsSuffix,
                AzureKeyVaultDnsSuffix  = AzureEnvironmentConstants.AzureKeyVaultDnsSuffix,
                AzureKeyVaultServiceEndpointResourceId            = AzureEnvironmentConstants.AzureKeyVaultServiceEndpointResourceId,
                AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = AzureEnvironmentConstants.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix,
                AzureDataLakeStoreFileSystemEndpointSuffix        = AzureEnvironmentConstants.AzureDataLakeStoreFileSystemEndpointSuffix,
                GraphEndpointResourceId    = AzureEnvironmentConstants.AzureGraphEndpoint,
                DataLakeEndpointResourceId = AzureEnvironmentConstants.AzureDataLakeServiceEndpointResourceId,
                BatchEndpointResourceId    = AzureEnvironmentConstants.BatchEndpointResourceId,
                AdTenant = "Common"
            };

            var azureChina = new AzureEnvironment
            {
                Name = EnvironmentName.AzureChinaCloud,
                PublishSettingsFileUrl   = AzureEnvironmentConstants.ChinaPublishSettingsFileUrl,
                ServiceManagementUrl     = AzureEnvironmentConstants.ChinaServiceEndpoint,
                ResourceManagerUrl       = AzureEnvironmentConstants.ChinaResourceManagerEndpoint,
                ManagementPortalUrl      = AzureEnvironmentConstants.ChinaManagementPortalUrl,
                ActiveDirectoryAuthority = AzureEnvironmentConstants.ChinaActiveDirectoryEndpoint,
                ActiveDirectoryServiceEndpointResourceId = AzureEnvironmentConstants.ChinaServiceEndpoint,
                StorageEndpointSuffix = AzureEnvironmentConstants.ChinaStorageEndpointSuffix,
                GalleryUrl            = AzureEnvironmentConstants.GalleryEndpoint,
                SqlDatabaseDnsSuffix  = AzureEnvironmentConstants.ChinaSqlDatabaseDnsSuffix,
                GraphUrl = AzureEnvironmentConstants.ChinaGraphEndpoint,
                TrafficManagerDnsSuffix = AzureEnvironmentConstants.ChinaTrafficManagerDnsSuffix,
                AzureKeyVaultDnsSuffix  = AzureEnvironmentConstants.ChinaKeyVaultDnsSuffix,
                AzureKeyVaultServiceEndpointResourceId            = AzureEnvironmentConstants.ChinaKeyVaultServiceEndpointResourceId,
                AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = null,
                AzureDataLakeStoreFileSystemEndpointSuffix        = null,
                DataLakeEndpointResourceId = null,
                GraphEndpointResourceId    = AzureEnvironmentConstants.ChinaGraphEndpoint,
                BatchEndpointResourceId    = AzureEnvironmentConstants.ChinaBatchEndpointResourceId,
                AdTenant = "Common"
            };

            var azureUSGovernment = new AzureEnvironment
            {
                Name = EnvironmentName.AzureUSGovernment,
                PublishSettingsFileUrl   = AzureEnvironmentConstants.USGovernmentPublishSettingsFileUrl,
                ServiceManagementUrl     = AzureEnvironmentConstants.USGovernmentServiceEndpoint,
                ResourceManagerUrl       = AzureEnvironmentConstants.USGovernmentResourceManagerEndpoint,
                ManagementPortalUrl      = AzureEnvironmentConstants.USGovernmentManagementPortalUrl,
                ActiveDirectoryAuthority = AzureEnvironmentConstants.USGovernmentActiveDirectoryEndpoint,
                ActiveDirectoryServiceEndpointResourceId = AzureEnvironmentConstants.USGovernmentServiceEndpoint,
                StorageEndpointSuffix = AzureEnvironmentConstants.USGovernmentStorageEndpointSuffix,
                GalleryUrl            = AzureEnvironmentConstants.GalleryEndpoint,
                SqlDatabaseDnsSuffix  = AzureEnvironmentConstants.USGovernmentSqlDatabaseDnsSuffix,
                GraphUrl = AzureEnvironmentConstants.USGovernmentGraphEndpoint,
                TrafficManagerDnsSuffix = AzureEnvironmentConstants.USGovernmentTrafficManagerDnsSuffix,
                AzureKeyVaultDnsSuffix  = AzureEnvironmentConstants.USGovernmentKeyVaultDnsSuffix,
                AzureKeyVaultServiceEndpointResourceId            = AzureEnvironmentConstants.USGovernmentKeyVaultServiceEndpointResourceId,
                AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = null,
                AzureDataLakeStoreFileSystemEndpointSuffix        = null,
                DataLakeEndpointResourceId = null,
                GraphEndpointResourceId    = AzureEnvironmentConstants.USGovernmentGraphEndpoint,
                BatchEndpointResourceId    = AzureEnvironmentConstants.USGovernmentBatchEndpointResourceId,
                AdTenant = "Common"
            };

            var azureGermany = new AzureEnvironment
            {
                Name = EnvironmentName.AzureGermanCloud,
                PublishSettingsFileUrl   = AzureEnvironmentConstants.GermanPublishSettingsFileUrl,
                ServiceManagementUrl     = AzureEnvironmentConstants.GermanServiceEndpoint,
                ResourceManagerUrl       = AzureEnvironmentConstants.GermanResourceManagerEndpoint,
                ManagementPortalUrl      = AzureEnvironmentConstants.GermanManagementPortalUrl,
                ActiveDirectoryAuthority = AzureEnvironmentConstants.GermanActiveDirectoryEndpoint,
                ActiveDirectoryServiceEndpointResourceId = AzureEnvironmentConstants.GermanServiceEndpoint,
                StorageEndpointSuffix = AzureEnvironmentConstants.GermanStorageEndpointSuffix,
                GalleryUrl            = AzureEnvironmentConstants.GalleryEndpoint,
                SqlDatabaseDnsSuffix  = AzureEnvironmentConstants.GermanSqlDatabaseDnsSuffix,
                GraphUrl = AzureEnvironmentConstants.GermanGraphEndpoint,
                TrafficManagerDnsSuffix = AzureEnvironmentConstants.GermanTrafficManagerDnsSuffix,
                AzureKeyVaultDnsSuffix  = AzureEnvironmentConstants.GermanKeyVaultDnsSuffix,
                AzureKeyVaultServiceEndpointResourceId            = AzureEnvironmentConstants.GermanAzureKeyVaultServiceEndpointResourceId,
                AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = null,
                AzureDataLakeStoreFileSystemEndpointSuffix        = null,
                DataLakeEndpointResourceId = null,
                GraphEndpointResourceId    = AzureEnvironmentConstants.GermanGraphEndpoint,
                BatchEndpointResourceId    = AzureEnvironmentConstants.GermanBatchEndpointResourceId,
                AdTenant = "Common"
            };

            var result = new ConcurrentDictionary <string, AzureEnvironment>(StringComparer.InvariantCultureIgnoreCase)
            {
                [EnvironmentName.AzureCloud]        = azureCloud,
                [EnvironmentName.AzureChinaCloud]   = azureChina,
                [EnvironmentName.AzureUSGovernment] = azureUSGovernment,
                [EnvironmentName.AzureGermanCloud]  = azureGermany
            };

            SetExtendedProperties(result);
            return(result);
        }
 static BaseClass()
 {
     TextureImageCache = new ConcurrentDictionary <Type, Texture>();
 }
示例#36
0
 /// <summary>
 /// Populate the transaction lookup dictionary with the current
 /// contents of the watch only wallet's watched addresses and
 /// transactions.
 /// </summary>
 private void LoadTransactionLookup()
 {
     this.txLookup = this.Wallet.GetWatchedTransactions();
 }
示例#37
0
 public Signal()
 {
     _changeTokens = new ConcurrentDictionary <string, ChangeTokenInfo>();
 }
 static NotifiableObject()
 {
     //缓存PropertyChangedEventArgs,以提高性能。
     _eventArgCache = new ConcurrentDictionary <string, PropertyChangedEventArgs>();
 }
示例#39
0
 public Terrain(double dimensionX = 100, double dimensionY = 100, int cellSize = 1)
 {
     _dimensionX   = Convert.ToInt32(dimensionX); _dimensionY = Convert.ToInt32(dimensionY);
     StringTerrain = new ConcurrentDictionary <Position, string>();
     RealTerrain   = new ConcurrentDictionary <Position, double>();
 }
 public void Setup()
 {
     map = new ConcurrentDictionary <string, int> ();
     AddStuff();
 }
示例#41
0
 public FileDeleter(ConcurrentDictionary<string, Peer> peers, NetworkPorts ports){
     _peers = peers;
     _port = ports.GetAvailablePort();
 }
示例#42
0
 static UtilityTools()
 {
     createdObjectsOfInstances = new ConcurrentDictionary<string, object>();
 }
 internal AudioVideoFlow(IRestfulClient restfulClient, AudioVideoFlowResource resource, Uri baseUri, Uri resourceUri, object parent)
     : base(restfulClient, resource, baseUri, resourceUri, parent)
 {
     m_onGoingPromptTcses = new ConcurrentDictionary <string, TaskCompletionSource <Prompt> >();
 }
示例#44
0
 static AppConfigurations()
 {
     ConfigurationCache = new ConcurrentDictionary <string, IConfigurationRoot>();
 }
示例#45
0
        public RuntimeViewCompiler(
            IFileProvider fileProvider,
            RazorProjectEngine projectEngine,
            CSharpCompiler csharpCompiler,
            IList <CompiledViewDescriptor> precompiledViews,
            ILogger logger)
        {
            if (fileProvider == null)
            {
                throw new ArgumentNullException(nameof(fileProvider));
            }

            if (projectEngine == null)
            {
                throw new ArgumentNullException(nameof(projectEngine));
            }

            if (csharpCompiler == null)
            {
                throw new ArgumentNullException(nameof(csharpCompiler));
            }

            if (precompiledViews == null)
            {
                throw new ArgumentNullException(nameof(precompiledViews));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _fileProvider   = fileProvider;
            _projectEngine  = projectEngine;
            _csharpCompiler = csharpCompiler;
            _logger         = logger;


            _normalizedPathCache = new ConcurrentDictionary <string, string>(StringComparer.Ordinal);

            // This is our L0 cache, and is a durable store. Views migrate into the cache as they are requested
            // from either the set of known precompiled views, or by being compiled.
            _cache = new MemoryCache(new MemoryCacheOptions());

            // We need to validate that the all of the precompiled views are unique by path (case-insensitive).
            // We do this because there's no good way to canonicalize paths on windows, and it will create
            // problems when deploying to linux. Rather than deal with these issues, we just don't support
            // views that differ only by case.
            _precompiledViews = new Dictionary <string, CompiledViewDescriptor>(
                precompiledViews.Count,
                StringComparer.OrdinalIgnoreCase);

            foreach (var precompiledView in precompiledViews)
            {
                logger.ViewCompilerLocatedCompiledView(precompiledView.RelativePath);

                if (!_precompiledViews.ContainsKey(precompiledView.RelativePath))
                {
                    // View ordering has precedence semantics, a view with a higher precedence was
                    // already added to the list.
                    _precompiledViews.Add(precompiledView.RelativePath, precompiledView);
                }
            }

            if (_precompiledViews.Count == 0)
            {
                logger.ViewCompilerNoCompiledViewsFound();
            }
        }
示例#46
0
        /// <summary>
        /// Parsed formula cache
        /// </summary>
        public FormulaCache(IFormulaParser formulaParser)
        {
            _formulaNodes = new ConcurrentDictionary<string, FormulaNodes>();

            _formulaParser = formulaParser;
        }
示例#47
0
 public EntityMap(IDataContext dataContext)
 {
     _entities = new ConcurrentDictionary <T, EntityMapEntry <T> >(dataContext.GetKeyEqualityComparer <T>());
 }
示例#48
0
 static BaseCacheManager()
 {
     _allKeys = new ConcurrentDictionary <string, bool>();
 }
示例#49
0
 private void ThreatMgr_OnDestroy()
 {
     Clear();
     m_threat = null;
 }
示例#50
0
文件: Profile.cs 项目: poutine70/UCR
 internal void PrepareProfile()
 {
     StateDictionary = new ConcurrentDictionary <Guid, bool>();
     States.ForEach(s => StateDictionary.TryAdd(s.Guid, false));
 }
示例#51
0
 public void SetCharacterMappings(ConcurrentDictionary <string, string> charMappings)
 {
     _charMappings = charMappings;
 }
示例#52
0
 public SyncTokenPolicy()
 {
     _syncTokens = new ConcurrentDictionary <string, SyncToken>();
 }
 static HttpClientFactory()
 {
     SetTimeout();
     Clients = new ConcurrentDictionary <string, HttpClientFacade>();
 }
 static EntityMetadataProvider()
 {
     RuntimeEntityMetadata = new ConcurrentDictionary <string, IEntityMetadata>();
 }
示例#55
0
 static Store()
 {
     _store = new ConcurrentDictionary <object, object>();
 }
示例#56
0
 public PCCollection()
 {
     _items = new ConcurrentDictionary <string, T>();
 }
示例#57
0
        private void ProcessIQAsync(agsXMPP.XmppSeverConnection contextConnection, IQ iq)
        {
            if (iq.Query.GetType() == typeof(Auth))
            {
                Auth   auth     = iq.Query as Auth;
                string name     = (auth.Username);
                string resource = auth.Resource;
                if (resource == null)
                {
                    resource = "";
                }
                var user = new FoxundermoonLib.XmppEx.Data.User(name, resource);
                switch (iq.Type)
                {
                case IqType.get:
                    iq.SwitchDirection();
                    iq.Type = IqType.result;
                    auth.AddChild(new Element("password"));
                    //auth.AddChild(new Element("digest"));
                    Console.WriteLine(auth.Username + " :开始登陆!");
                    contextConnection.Send(iq);
                    break;

                case IqType.set:
                    // Here we should verify the authentication credentials
                    Console.WriteLine(auth.Username + " : " + "开始验证, 密码:" + auth.Password);
                    iq.SwitchDirection();
                    if (AccountBus.CheckAccountAsync(auth.Username, auth.Password))      //验证用户是否存在或者密码是否正确
                    {
                        contextConnection.IsAuthentic = true;
                        iq.Type  = IqType.result;
                        iq.Query = null;
                        try
                        {
                            ConcurrentDictionary <string, XmppSeverConnection> cons = null;
                            //Func<int,XmppSeverConnection,XmppSeverConnection> update = (k,v)=>{return v;};
                            //XmppConnectionDic.AddOrUpdate(uid, contextConnection),(k,v)=>{return v;});
                            var hasCons = XmppConnectionDic.TryGetValue(name, out cons);
                            if (hasCons)
                            {
                                XmppSeverConnection con = null;
                                var hasCon = cons.TryGetValue(resource, out con);
                                if (hasCon)
                                {
                                    cons.TryRemove(resource, out con);
                                    Console.WriteLine(name + " 重新登录");
                                    try
                                    {
                                        //con.Stop();
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("[email protected] old connection  :" + e.Message);
                                    }
                                }
                            }

                            if (!hasCons)
                            {
                                cons = new ConcurrentDictionary <string, XmppSeverConnection>();
                                if (XmppConnectionDic.TryAdd(name, cons))
                                {
                                    Console.WriteLine(auth.Username + ": 账号验证成功,并加入连接池!");
                                }
                                else
                                {
                                    Console.WriteLine(auth.Username + ": 账号验证成功,但是加入连接池失败!");
                                }
                            }

                            cons.TryAdd(resource, contextConnection);
                            contextConnection.User = user;
                            UserOnline(user);
                        }
                        catch (Exception e)
                        {
                            // 消息没有 From    dosomething
                            iq.Type  = IqType.error;
                            iq.Value = e.Message;
                            Console.WriteLine("Exception --> message: " + e.Message + "  data:" + e.Data);
                        }
                    }
                    else
                    {
                        // authorize failed
                        iq.Type = IqType.error;      //若要开启验证功能去掉此注释
                        Console.WriteLine(auth.Username + ":账号验证失败!");
                        FoxundermoonLib.XmppEx.Data.Message loginFailed = new FoxundermoonLib.XmppEx.Data.Message();
                        loginFailed.Command.Name = FoxundermoonLib.XmppEx.Command.Cmd.ErrorMessage;
                        loginFailed.AddProperty("Cause", "账号验证失败,请检查用户名或者密码");
                        loginFailed.ToUser = user;
                        UniCast(loginFailed);
                        //iq.Type = IqType.result;
                        iq.Query = null;
                        iq.Value = "authorized failed";
                        contextConnection.IsAuthentic = false;
                    }
                    try
                    {
                        contextConnection.Send(iq);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception->@IQhandler.processIq:" + e.Message);
                    }
                    break;
                }
            }
            else if (!contextConnection.IsAuthentic)
            {
                contextConnection.Stop();
            }
            else if (iq.Query.GetType() == typeof(Roster))
            {
                ProcessRosterIQ(contextConnection, iq);
            }
        }
示例#58
0
 internal void SetMethodTestData(ConcurrentDictionary <IMethodSymbolInternal, CompilationTestData.MethodData> methods)
 {
     Debug.Assert(TestData == null);
     TestData = methods;
 }
示例#59
0
        /// <summary>
        /// Build operation containes structure that will be serialized
        /// </summary>
        /// <returns>
        /// List of <see cref="OperationContainer"/>
        /// </returns>
        private IEnumerable <OperationContainer> BuildOperationContainers()
        {
            var cache = new ConcurrentDictionary <CacheKey, Lazy <Thing> >();

            // DomainOfExpertise
            var domain = new DomainOfExpertise(Guid.NewGuid(), cache, this.credentials.Uri)
            {
                ShortName = "SYS"
            };

            this.siteDirectoryData.Domain.Add(domain);

            // PersonRole
            var role = new PersonRole(Guid.NewGuid(), null, null);

            this.siteDirectoryData.PersonRole.Add(role);
            this.siteDirectoryData.DefaultPersonRole = role;

            // ParticipantRole
            var participantRole = new ParticipantRole(Guid.Empty, null, null);

            this.siteDirectoryData.ParticipantRole.Add(participantRole);
            this.siteDirectoryData.DefaultParticipantRole = participantRole;

            // Organization
            var organization = new Organization(Guid.NewGuid(), null, null)
            {
                Container = this.siteDirectoryData
            };

            // Iteration
            var iterationIid       = new Guid("b58ea73d-350d-4520-b9d9-a52c75ac2b5d");
            var iterationSetup     = new IterationSetup(Guid.NewGuid(), 0);
            var iterationSetupPoco = new CDP4Common.SiteDirectoryData.IterationSetup(iterationSetup.Iid, cache, this.credentials.Uri);

            // EngineeringModel
            var model      = new EngineeringModel(Guid.NewGuid(), cache, this.credentials.Uri);
            var modelSetup = new CDP4Common.SiteDirectoryData.EngineeringModelSetup();

            modelSetup.ActiveDomain.Add(domain);

            var requiredRdl = new ModelReferenceDataLibrary();

            var person = new Person {
                ShortName = "admin", Organization = organization
            };
            var participant = new Participant(Guid.NewGuid(), cache, this.credentials.Uri)
            {
                Person = person
            };

            participant.Person.Role = role;
            participant.Role        = participantRole;
            participant.Domain.Add(domain);
            modelSetup.Participant.Add(participant);

            var lazyPerson    = new Lazy <Thing>(() => person);
            var iterationPoco = new CDP4Common.EngineeringModelData.Iteration(iterationIid, cache, this.credentials.Uri)
            {
                IterationSetup = iterationSetupPoco
            };

            model.Iteration.Add(iterationPoco);
            var iteration = (Iteration)iterationPoco.ToDto();

            model.EngineeringModelSetup = modelSetup;
            this.siteDirectoryData.Model.Add(modelSetup);
            modelSetup.RequiredRdl.Add(requiredRdl);
            modelSetup.IterationSetup.Add(iterationSetupPoco);
            cache.TryAdd(new CacheKey(person.Iid, this.siteDirectoryData.Iid), lazyPerson);
            this.siteDirectoryData.Cache = cache;
            iteration.IterationSetup     = iterationSetup.Iid;
            var iterationClone = iteration.DeepClone <Iteration>();

            var operation           = new Operation(iteration, iterationClone, OperationKind.Update);
            var operationContainers = new[] { new OperationContainer("/EngineeringModel/" + model.Iid + "/iteration/" + iteration.Iid, 0) };

            operationContainers.Single().AddOperation(operation);

            return(operationContainers);
        }
示例#60
0
 /// <summary>
 ///
 /// </summary>
 protected internal ObjectExtensionManager()
 {
     ObjectsExtensions = new ConcurrentDictionary <Type, ObjectExtensionInfo>();
     Configuration     = new ConcurrentDictionary <object, object>();
 }