Ejemplo n.º 1
0
		public void Compile()
		{
			var baseType = typeof(IBuilderTest);
			var handlers = new ReadOnlyDictionary<int, ReadOnlyCollection<HandlerInformation>>(
				new Dictionary<int, ReadOnlyCollection<HandlerInformation>>());
			var namespaces = new SortedSet<string> { baseType.Namespace };
			var options = new RockOptions();

			var builder = new InMemoryBuilder(baseType, handlers, namespaces, options, false);
			builder.Build();

			var trees = new[] { builder.Tree };
			var compiler = new InMemoryCompiler(trees, options.Optimization, 
				new List<Assembly> { baseType.Assembly }.AsReadOnly(), builder.IsUnsafe,
				options.AllowWarnings);
			compiler.Compile();

			Assert.AreEqual(options.Optimization, compiler.Optimization, nameof(compiler.Optimization));
			Assert.AreSame(trees, compiler.Trees, nameof(compiler.Trees));
			Assert.IsNotNull(compiler.Result, nameof(compiler.Result));
			Assert.IsNotNull(
				(from type in compiler.Result.GetTypes()
				where baseType.IsAssignableFrom(type)
				select type).Single());
		}
 internal WebSocketMessageProperty(WebSocketContext context, string subProtocol, WebSocketMessageType incomingMessageType, ReadOnlyDictionary<string, object> properties)
 {
     this.context = context;
     this.subProtocol = subProtocol;
     this.messageType = incomingMessageType;
     this.properties = properties;
 }
Ejemplo n.º 3
0
        public Response(IDictionary<string, string> headers)
        {
            Ensure.ArgumentNotNull(headers, "headers");

            Headers = new ReadOnlyDictionary<string, string>(headers);
            ApiInfo = ApiInfoParser.ParseResponseHeaders(headers);
        }
Ejemplo n.º 4
0
        static Initializers()
        {
            var timer = new Stopwatch();
            timer.Start();

            var initializers = new Dictionary<ID, ITemplateInitializer>();

            var initializerTypes = ProviderResolver.Current.TypeListProvider.CreateTypeList().ImplementingInterface(typeof(ITemplateInitializer));

            foreach (var initializer in initializerTypes)
            {
                var instance = (ITemplateInitializer)Activator.CreateInstance(initializer);

                if (initializers.ContainsKey(instance.InitializesTemplateId))
                {
                    throw new InvalidOperationException("Synthesis: Multiple initializers were found for template {0} ({1}, {2}).".FormatWith(instance.InitializesTemplateId, initializers[instance.InitializesTemplateId].GetType().FullName, instance.GetType().FullName));
                }

                // ignore test and standard template initializers
                if (instance.InitializesTemplateId == ID.Null) continue;

                initializers.Add(instance.InitializesTemplateId, instance);
            }

            InitializerCache = new ReadOnlyDictionary<ID, ITemplateInitializer>(initializers);

            timer.Stop();
            Log.Info("Synthesis: Initialized template initializer cache (" + InitializerCache.Count + " templates) in " + timer.ElapsedMilliseconds + " ms", InitializerCache);
        }
Ejemplo n.º 5
0
        public ActionResult(string returnValue, IDictionary<string, string> outArguments)
        {
            if (outArguments == null) throw new ArgumentNullException ();

            return_value = returnValue;
            out_arguments = new ReadOnlyDictionary<string,string> (outArguments);
        }
Ejemplo n.º 6
0
Archivo: GIC.cs Proyecto: rte-se/emul8
        public GIC(int numberOfCPUs = 1, int itLinesNumber = 10)
        {
            this.numberOfCPUs = numberOfCPUs;
            this.itLinesNumber = itLinesNumber;
            var innerConnections = new Dictionary<int, IGPIO>();
            for(var i = 0; i < numberOfCPUs; i++)
            {
                innerConnections[i] = new GPIO();
            }
            Connections = new ReadOnlyDictionary<int, IGPIO>(innerConnections);

            privateInterrupts = new IRQState[numberOfCPUs][];
            for(var i = 0; i < privateInterrupts.Length; i++)
            {
                privateInterrupts[i] = new IRQState[32];
            }
            publicInterrupts = new IRQState[991];
            privatePriorities = new byte[numberOfCPUs][];
            for(var i = 0; i < privatePriorities.Length; i++)
            {
                privatePriorities[i] = new byte[32];
            }
            publicPriorities = new byte[991];
            runningPriorities = new byte[numberOfCPUs];
            priorityMasks = new byte[numberOfCPUs];
            enabled = new bool[numberOfCPUs];
            localReceivers = new LocalGPIOReceiver[numberOfCPUs];
            for(var i = 0; i < localReceivers.Length; i++)
            {
                localReceivers[i] = new LocalGPIOReceiver(i, this);
            }
            Reset();
        }
Ejemplo n.º 7
0
        private NodeDevice(ReadOnlyDictionary<FieldIdentifier, FieldBase> Fields,
            ReadOnlyCollection<NodeBase> Children)
            : base(Fields, Children)
        {
            NodeDeviceChildren = new TypedChildCollection<NodeDevice, NodeDevice>(this);
            NodeDiscreteInputChildren = new TypedChildCollection<NodeDiscreteInput, NodeDevice>(this);
            NodeDiscreteOutputChildren = new TypedChildCollection<NodeDiscreteOutput, NodeDevice>(this);
            NodeAnalogInputChildren = new TypedChildCollection<NodeAnalogInput, NodeDevice>(this);
            NodeAnalogOutputChildren = new TypedChildCollection<NodeAnalogOutput, NodeDevice>(this);
            NodeStringInputChildren = new TypedChildCollection<NodeStringInput, NodeDevice>(this);
            NodeStringOutputChildren = new TypedChildCollection<NodeStringOutput, NodeDevice>(this);

            // Validation
            if (Code == null)
            {
                throw new ArgumentNullException(m_CodeName);
            }
            if (TypeId == null)
            {
                throw new ArgumentNullException(m_TypeIdName);
            }
            if (Address == null)
            {
                throw new ArgumentNullException(m_AddressName);
            }
            if (Configuration == null)
            {
                throw new ArgumentNullException(m_ConfigurationName);
            }
            if (DeviceName == null)
            {
                throw new ArgumentNullException(m_DeviceNameName);
            }
        }
Ejemplo n.º 8
0
        public Model(ISessionFactory sessionfactory, Type type)
        {
            if (sessionfactory == null) throw new ArgumentNullException("sessionfactory");
            if (type == null) throw new ArgumentNullException("type");

            IsComponent = false;
            Type = type;
            Metadata = sessionfactory.GetClassMetadata(Type);
            Properties = new Dictionary<string, IType>();
            Components = new Dictionary<string, Model>();
            BelongsTos = new Dictionary<string, ManyToOneType>();
            OneToOnes = new Dictionary<string, OneToOneType>();
            Anys = new Dictionary<string, AnyType>();
            HasManys = new Dictionary<string, Collection>();
            HasAndBelongsToManys = new Dictionary<string, Collection>();

            PrimaryKey = new KeyValuePair<string, IType>(Metadata.IdentifierPropertyName, Metadata.IdentifierType);
            foreach (var name in Metadata.PropertyNames) {
                var prop = Metadata.GetPropertyType(name);
                CategorizeProperty(sessionfactory, prop, name);
            }
            Properties = new ReadOnlyDictionary<string, IType>(Properties);
            Components = new ReadOnlyDictionary<string, Model>(Components);
            BelongsTos = new ReadOnlyDictionary<string, ManyToOneType>(BelongsTos);
            OneToOnes = new ReadOnlyDictionary<string, OneToOneType>(OneToOnes);
            Anys = new ReadOnlyDictionary<string, AnyType>(Anys);
            HasManys = new ReadOnlyDictionary<string, Collection>(HasManys);
            HasAndBelongsToManys = new ReadOnlyDictionary<string, Collection>(HasAndBelongsToManys);
        }
Ejemplo n.º 9
0
        private GameState(
            Game game,
            ReadOnlyCollection<string> playerIds,
            ReadOnlyCollection<Card> deck,
            ReadOnlyDictionary<string, int> scores,
            ReadOnlyDictionary<string, ReadOnlyCollection<Card>> hands,
            int dealer,
            int turn,
            ReadOnlyCollection<Premise> proof,
            bool isRoundOver)
        {
            if (game == null)
            {
                throw new ArgumentNullException("game");
            }

            this.game = game;

            this.playerIds = playerIds;
            this.deck = deck;
            this.scores = scores;
            this.hands = hands;
            this.dealer = dealer;
            this.turn = turn;
            this.proof = proof;
            this.isRoundOver = isRoundOver;
        }
Ejemplo n.º 10
0
        public async Task Can_dispatch_event()
        {
            List<object> projectedEvents = new List<object>();
            var handlerResolver = new ProjectionHandlerResolver(new TestProjectionModule(projectedEvents));
            const string streamId = "stream";
            var eventId = Guid.NewGuid();
            const int version = 2;
            var timeStamp = DateTimeOffset.UtcNow;
            var headers = new ReadOnlyDictionary<string, object>(new Dictionary<string, object>());

            using(var dispatcher = new TestProjectionDispatcher(handlerResolver, new InMemoryCheckpointRepository()))
            {
                await dispatcher.Start();
                await dispatcher.DoDispatch(streamId, eventId, version, timeStamp, "checkpoint", headers, new TestEvent());
            }

            projectedEvents.Count.Should().Be(1);
            
            var projectionEvent = projectedEvents[0].As<ProjectionEvent<TestEvent>>();
            projectionEvent.StreamId.Should().Be(streamId);
            projectionEvent.EventId.Should().Be(eventId);
            projectionEvent.Version.Should().Be(version);
            projectionEvent.TimeStamp.Should().Be(timeStamp);
            projectionEvent.Headers.Should().NotBeNull();
        }
Ejemplo n.º 11
0
        public SunxiHighSpeedTimer(Machine machine, long frequency)
        {
            irqEnableRegister = new DoubleWordRegister(this);
            irqStatusRegister = new DoubleWordRegister(this);
            
            timers = new SunxiHighSpeedTimerUnit[4];
            interruptFlags = new IFlagRegisterField[4];
            enableFlags = new IFlagRegisterField[4];

            for(var i = 0; i < 4; ++i)
            {
                var j = i;
                timers[i] = new SunxiHighSpeedTimerUnit(machine, frequency);
                timers[i].LimitReached += () => OnTimerLimitReached(j);
                interruptFlags[i] = irqStatusRegister.DefineFlagField(i, FieldMode.WriteOneToClear, name: "Tx_IRQ_PEND");
                enableFlags[i] = irqEnableRegister.DefineFlagField(i, name: "Tx_INT_EN");
            }

            var innerConnections = new Dictionary<int, IGPIO>();
            for(var i = 0; i < 4; ++i)
            {
                innerConnections[i] = new GPIO();
            }
            Connections = new ReadOnlyDictionary<int, IGPIO>(innerConnections);
        }
		public void Create()
		{
			var expectations = new ReadOnlyDictionary<string, ArgumentExpectation>(new Dictionary<string, ArgumentExpectation>());
			var handler = new HandlerInformation<string>(expectations);
			var returnValue = new MethodAdornments<string>(handler);
			Assert.AreEqual(default(string), handler.ReturnValue, nameof(handler.ReturnValue));
		}
        internal TokenUsedEventArgs(CommandParameterGroupList commandParameterGroupList)
        {
            if (commandParameterGroupList == null)
                throw new ArgumentNullException("commandParameterGroupList");

            const string PATTERN = @"ident=(?<ident>[^\s=]+)\s+(?<value>value=.*)";

            string customSettingsString = commandParameterGroupList.GetParameterValue("tokencustomset");
            Dictionary<string, string> customSettings = new Dictionary<string, string>();

            if (!customSettingsString.IsNullOrTrimmedEmpty())
            {
                foreach (string splittedSetting in customSettingsString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Match match = Regex.Match(splittedSetting, PATTERN, RegexOptions.Singleline | RegexOptions.IgnoreCase);

                    if (!match.Success)
                        continue;

                    customSettings[match.Groups["ident"].Value] = match.Groups["value"].Value;
                }
            }

            ClientId = commandParameterGroupList.GetParameterValue<uint>("clid");
            ClientUniqueId = commandParameterGroupList.GetParameterValue("cluid");
            ClientDatabaseId = commandParameterGroupList.GetParameterValue<uint>("cldbid");
            TokenText = commandParameterGroupList.GetParameterValue("token");
            GroupId = commandParameterGroupList.GetParameterValue<uint>("token1");
            ChannelId = commandParameterGroupList.GetParameterValue<uint>("token2");
            CustomSettings = customSettings.AsReadOnly();
        }
Ejemplo n.º 14
0
 public void ReadOnlyDictionaryConstructorwithstuffTest()
 {
     var dictionary = new Dictionary<string, Tuple<string, Type, TimeSpan>>();
     dictionary.Add("John", new Tuple<string, Type, TimeSpan>("John", typeof(string), new TimeSpan(0,1,0)));
     ReadOnlyDictionary<string, Tuple<string, Type, TimeSpan>> target = new ReadOnlyDictionary<string, Tuple<string, Type, TimeSpan>>(dictionary);
     Assert.IsInstanceOfType(target, typeof(ReadOnlyDictionary<string, Tuple<string, Type, TimeSpan>>));
 }
 public ConflictingVersionRequirementsException(string message, AppIdentifier dependency,
     IDictionary<AppIdentifier, string> requiredVersionsByDependent)
     : base(message)
 {
     Dependency = dependency;
     RequiredVersionsByDependent = new ReadOnlyDictionary<AppIdentifier, string>(requiredVersionsByDependent);
 }
        /// <summary>
        /// Initializes a new cellular automaton with false that has the specified rule.
        /// </summary>
        /// <param name="rule">A rule number</param>
        /// <param name="length">A length of cells</param>
        public LinearCellularAutomaton(byte rule, int length)
        {
            if (length < 3)
                throw new ArgumentOutOfRangeException("Length is must be more than or equal to 3");

            _ruleNumber = rule;
            _length = length;
            _density = 0.0;

            var rules = Convert.ToString(rule, 2).PadLeft(8, '0');
            _rules = new ReadOnlyDictionary<Tuple<bool, bool, bool>, bool>(new Dictionary<Tuple<bool, bool, bool>, bool>()
            {
                {Tuple.Create(true, true, true), rules[0] == '1' ? true : false},
                {Tuple.Create(true, true, false), rules[1] == '1' ? true : false},
                {Tuple.Create(true, false, true), rules[2] == '1' ? true : false},
                {Tuple.Create(true, false, false), rules[3] == '1' ? true : false},
                {Tuple.Create(false, true, true), rules[4] == '1' ? true : false},
                {Tuple.Create(false, true, false), rules[5] == '1' ? true : false},
                {Tuple.Create(false, false, true), rules[6] == '1' ? true : false},
                {Tuple.Create(false, false, false), rules[7] == '1' ? true : false}
            });
            state = Enumerable.Repeat(false, length).ToArray();
            _initialState = new System.Collections.ObjectModel.ReadOnlyCollection<bool>(state);
            time = 0;
        }
Ejemplo n.º 17
0
        private NodeAnalogInput(ReadOnlyDictionary<FieldIdentifier, FieldBase> Fields,
            ReadOnlyCollection<NodeBase> Children)
            : base(Fields, Children)
        {
            m_Signal = new SingleChild<NodeSignal, NodeAnalogInput>(this);

            // Validation
            if (Code == null)
            {
                throw new ArgumentNullException(m_CodeName);
            }
            if (Address == null)
            {
                throw new ArgumentNullException(m_AddressName);
            }
            if (Forced == null)
            {
                throw new ArgumentNullException(m_ForcedName);
            }
            if (ForcedValue == null)
            {
                throw new ArgumentNullException(m_ForcedValueName);
            }
            if (Signal == null)
            {
                throw new ArgumentNullException(m_SignalName);
            }
            if (InputName == null)
            {
                throw new ArgumentNullException(m_InputNameName);
            }
        }
Ejemplo n.º 18
0
        public HandlerContext(RestRequest request, ReadOnlyDictionary<String, String> env, MethodInfo code)
        {
            Request = request.AssertNotNull();
            Env = env.AssertNotNull();
            Code = code.AssertNotNull();

            // todo:
            // 1) allow to return void, json, string, byte[], stream and any other object (the latter will then be serialized to json)
            // 2) allow non-statics
            // 3) allow RestRequest, RestResponse, RestContext, RestHints, Query, RequestHeaders, ResponseHeaders, Cookies, dynamic/Json (Data), Stream (output stream), TextWriter (response)
            // 4) allow config types
            // 5) deserialize when binding
            // 6) bind to fields as well
            // 7) comprehensive logging
            // 8) try to bind everything, rather than stop at first error

            Debug.EnsureBlankLine();
            Debug.WriteLine("    * Env: {0}", Env.Select(kvp => String.Format("{0} = {1}", kvp.Key, kvp.Value)).StringJoin());
            Debug.WriteLine("    * Query: {0}", request.Query.Select(kvp => String.Format("{0} = {1}", kvp.Key, (String)kvp.Value)).StringJoin().Fluent(s => s.IsEmpty() ? "<empty>" : s));
            Debug.WriteLine("    * Data: {0}", ((Json)request.Data).ToCompactString().Fluent(s => s.IsEmpty() ? "<empty>" : s));
            // todo. after that log:
            // Write("    * field foo <= ")
            // do something, then write either:
            // 1) WriteLine("Data.foo") or
            // 2) WriteLine("FAIL") or even
            // 3) exception.... [will be traced by RestGateway]
        }
Ejemplo n.º 19
0
        public Object(IEnumerable<KeyValuePair<string, Value>> properties)
        {
            if (properties == null)
                throw new ArgumentNullException ("properties");

            Properties = new ReadOnlyDictionary<string,Value>(properties.ToDictionary (x => x.Key, x => x.Value));
        }
        public async Task Execute()
        {
            var loggers = new List<ILog>
            {
                new ConsoleLog()
            };

            if (!string.IsNullOrEmpty(LogTo))
                loggers.Add(new FileLog(LogTo));

            var engine = TemplatingEngine.Init(loggers.ToArray());

            var alterationDirectories = TemplatePaths
                .Select(x => Path.Combine(x, "alterations\\base"))
                .Where(Directory.Exists)
                .ToList();

            alterationDirectories.AddRange(TemplatePaths
                .Select(x => Path.Combine(x, $"alterations\\{Template}"))
                .Where(Directory.Exists));

            var substitutions = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>
            {
                {"PROJECT_NAME", Name},
                {"SOLUTION", Solution}
            });

            foreach (var alterationDirectory in alterationDirectories)
                await
                    engine.RunTemplate(
                        new AlterationTemplateType(Name, Location, Path.Combine(Location, $"src\\{Name}"), substitutions),
                        alterationDirectory).ConfigureAwait(false);
        }
Ejemplo n.º 21
0
        public TotemArgs(TotemContext context, string[] names, IList<object> args, Dictionary<string, object> kwargs)
            : base(context.GetType<Types.Arguments>())
        {
            _names = new ReadOnlyCollectionBuilder<string>(names).ToReadOnlyCollection();
            var vb = new ReadOnlyCollectionBuilder<object>();
            var nvb = new Dictionary<string, object>();
            var snb = new ReadOnlyCollectionBuilder<string>();

            for (var i = 0; i < args.Count; i++)
            {
                vb.Add(args[i]);
                if (i < names.Length)
                    nvb.Add(names[i], args[i]);
            }

            foreach (var arg in kwargs)
            {
                nvb.Add(arg.Key, arg.Value);
                snb.Add(arg.Key);
            }

            _values = vb.ToReadOnlyCollection();
            _namedValues = new ReadOnlyDictionary<string, object>(nvb);
            _named = snb.ToReadOnlyCollection();
        }
Ejemplo n.º 22
0
		public void Build()
		{
			var baseType = typeof(IBuilderTest);
			var handlers = new ReadOnlyDictionary<int, ReadOnlyCollection<HandlerInformation>>(
				new Dictionary<int, ReadOnlyCollection<HandlerInformation>>());
			var namespaces = new SortedSet<string> { baseType.Namespace };
			var options = new RockOptions();

			var builder = new InMemoryBuilder(baseType, handlers, namespaces, options, false);
			builder.Build();

			Assert.AreSame(baseType, builder.BaseType, nameof(builder.BaseType));
			Assert.AreSame(handlers, builder.Handlers, nameof(builder.Handlers));
			Assert.AreSame(namespaces, builder.Namespaces, nameof(builder.Namespaces));
			Assert.AreEqual(0, namespaces.Count, nameof(namespaces.Count));

			Assert.AreSame(options, builder.Options, nameof(builder.Options));
			Assert.IsNotNull(builder.Tree, nameof(builder.Tree));
			Assert.IsTrue(!string.IsNullOrWhiteSpace(builder.TypeName), nameof(builder.TypeName));

			var tree = builder.Tree.ToString();

			Assert.IsFalse(tree.StartsWith("#pragma warning disable CS0618"));
			Assert.IsFalse(tree.Contains("#pragma warning disable CS0672"));
			Assert.IsFalse(tree.Contains("#pragma warning restore CS0672"));
			Assert.IsFalse(tree.EndsWith("#pragma warning restore CS0618"));
		}
Ejemplo n.º 23
0
 private SimpleSentenceForm(int name, int arity, ReadOnlyDictionary<int, SimpleSentenceForm> functions, int tupleSize)
 {
     _arity = arity;
     _functions = functions;
     Name = name;
     TupleSize = tupleSize;
 }
Ejemplo n.º 24
0
 public Element(string name, string argument, IDictionary<string, string> attributes, IList<IElement> elements)
 {
     Name = name;
     Argument = argument;
     Attributes = new ReadOnlyDictionary<string, string>(attributes);
     Elements = new ReadOnlyCollection<IElement>(elements);
 }
Ejemplo n.º 25
0
		private void CheckDuchyKingdom( ReadOnlyDictionary<string, Title> titles )
		{
			foreach( var pair in titles )
			{
				if( TaskStatus.Abort )
					return;

				Log( " --" + pair.Value.TitleID );

				Title d = pair.Value;

				if ( d.HolyOrder || d.Mercenary )
					m_options.RuleSet.IgnoredTitles.Add( d.TitleID );

				if( d.Primary || d.Landless || ( d.IsTitular && d.Capital == -1 ) )
					continue;

				if( d.Capital == -1 )
					d.Capital = d.SubTitles.ElementAt( 0 ).Value.Capital;

				if( !m_options.Data.Provinces.ContainsKey( d.Capital ) )
				{
					d.Primary = true;
					continue;
				}

				if( String.IsNullOrEmpty( d.Culture ) )
					d.Culture = m_options.Data.Provinces[d.Capital].Culture;
				if( String.IsNullOrEmpty( d.Religion ) )
					d.Religion = m_options.Data.Provinces[d.Capital].Religion;
			}
		}
        private WindowsPhoneServiceLocator()
        {
            _appverseServices =
                new ReadOnlyDictionary<string, IAppverseService>(new Dictionary<string, IAppverseService>
                {
                    {"net", new WindowsPhoneNet()},
                    {"system", new WindowsPhoneSystem()},
                    {"pim", new WindowsPhonePim()},
                    {"file", new WindowsPhoneFileSystem()},
                    {"io", new WindowsPhoneIO()},
                    {"geo", new WindowsPhoneGeo()},
                    {"message", new WindowsPhoneMessaging()},
                    {"phone", new WindowsPhoneTelephony()},
                    {"media", new WindowsPhoneMedia()},
                    {"i18n", new WindowsPhoneI18N()},
                    {"log", new WindowsPhoneLog()},
                    {"scanner", new WindowsPhoneScanner()},
                    {"push", new WindowsPhonePushNotification()},
                    //{"notify", new WindowsPhoneNotification},
                    //{"db", new WindowsPhoneDatabase()},
                    //{"analytics", new WindowsPhoneAnalytics()},
                    //{"webtrekk", new WindowsPhoneWebtrekk()},
                    //{"loader", new WindowsPhoneAppLoader()},
                    {"security", new WindowsPhoneSecurity()}

                });
            Task.Run(() => { InitAppverseContext(); });
        }
Ejemplo n.º 27
0
Archivo: Program.cs Proyecto: jagt/llml
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello llml!");

            var dict = new Dictionary<string, object>();
            IDictionary<string, object> roDict = new ReadOnlyDictionary<string, object>(dict);
        }
Ejemplo n.º 28
0
        static PasswordProviderPool()
        {
            var types = new[] {
                typeof(PasswordProviderV1),
                typeof(PasswordProviderV2),
            };

            Providers = types
                .Select(s => new ProviderInfo
                {
                    Version = s.GetCustomAttributes(typeof(PasswordProviderVersionAttribute), false)
                        .Cast<PasswordProviderVersionAttribute>()
                        .Single()
                        .Version,
                    Type = s,
                    Creater = Expression.Lambda<PasswordProviderActivator>(Expression.New(s.GetConstructors().Single()))
                        .Compile(),
                })
                .OrderByDescending(s => s.Version)
                .ToArray();

            Pool = new ReadOnlyDictionary<int, ConcurrentBag<PasswordProvider>>(
                Providers
                    .ToDictionary(s => s.Version, s => new ConcurrentBag<PasswordProvider>()));

            LastVersion = Providers.Max(s => s.Version);
        }
Ejemplo n.º 29
0
        private void Init(
            string httpMethod,
            Uri url,
            string applicationPath,
            IEnumerable<KeyValuePair<string, string[]>> formData,
            IEnumerable<KeyValuePair<string, string>> cookies,
            Func<byte[], byte[]> cookieDecryptor)
        {
            HttpMethod = httpMethod;
            Url = url;
            ApplicationUrl = new Uri(url, applicationPath);
            Form = new ReadOnlyDictionary<string, string>(
                (formData ?? Enumerable.Empty<KeyValuePair<string, string[]>>())
                .ToDictionary(kv => kv.Key, kv => kv.Value.Single()));
            QueryString = QueryStringHelper.ParseQueryString(url.Query);

            var relayState = QueryString["RelayState"].SingleOrDefault();

            if (relayState != null)
            {
                var cookieName = "Kentor." + relayState;
                if (cookies.Any(c => c.Key == cookieName))
                {
                    var cookieData = cookies.SingleOrDefault(c => c.Key == cookieName).Value;

                    var unescapedBase64Data = cookieData
                        .Replace('_', '/')
                        .Replace('-', '+')
                        .Replace('.', '=');

                    CookieData = Encoding.UTF8.GetString(cookieDecryptor(
                        Convert.FromBase64String(unescapedBase64Data)));
                }
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Create a new Page
        /// </summary>
        /// <param Name="x">The x coordinate of the top-left corner of the page</param>
        /// <param Name="y">The y coordinate of the top-left corner of the page</param>
        /// <param Name="c">The character the page is initialised with</param>
        /// <param Name="document">The document the page is attached to</param>
        /// <param Name="pr">The previous page in the document</param>
        /// <param Name="nx">The next page in the document</param>
        public Page(float x, float y, char c, Document document, Page pr, Page nx)
            : base(c.ToString(), document.Window)
        {
            Document = document;
            Prev = pr;
            Next = nx;

            EscapeKeys = new ReadOnlyDictionary<Keys, ShowInterfaceHandler>(
                new Dictionary<Keys, ShowInterfaceHandler>()
                {
                    {Keys.F1, Window.CommandHandler},
                    {Keys.F2, Window.FindHandler},
                    {Keys.F3, Window.FindHandler}
                });

            //Set the size of the page
            ConstrainHeightToTextHeight = false;
            ConstrainWidthToTextWidth = false;
            Bounds = new RectangleF(x, y, PageSize.A4.Width, PageSize.A4.Height);
            DrawBorder();

            //Add event listeners
            AddInputEventListener(Window.CommandHandler);
            AddInputEventListener(Window.FindHandler);

            ConfirmSelection += Window.ConfirmSelection;
            Reflow += OnReflow;

            Model.KeyDown += Model_KeyDown;
        }
Ejemplo n.º 31
0
        public CoreLevelInterruptor(Machine machine, long frequency, int numberOfTargets = 1)
        {
            this.machine        = machine;
            this.timerFrequency = frequency;
            if (numberOfTargets < 1)
            {
                throw new ConstructionException("Invalid numberOfTargets: provided {numberOfTargets} but should be greater or equal to 1.");
            }
            for (var i = 0; i < numberOfTargets; i++)
            {
                var hartId = i;
                irqs[2 * hartId]     = new GPIO();
                irqs[2 * hartId + 1] = new GPIO();

                var timer = new ComparingTimer(machine.ClockSource, timerFrequency, this, hartId.ToString(), enabled: true, eventEnabled: true);
                timer.CompareReached += () => irqs[2 * hartId + 1].Set(true);

                mTimers.Add(timer);
            }

            var registersMap = new Dictionary <long, DoubleWordRegister>
            {
                {
                    (long)Registers.MTimeLo, new DoubleWordRegister(this).WithValueField(0, 32, FieldMode.Read,
                                                                                         valueProviderCallback: _ => (uint)mTimers[0].Value,
                                                                                         writeCallback: (_, value) =>
                    {
                        var timerValue = mTimers[0].Value;
                        timerValue    &= ~0xffffffffUL;
                        timerValue    |= value;
                        foreach (var timer in mTimers)
                        {
                            timer.Value = timerValue;
                        }
                    })
                },
                {
                    (long)Registers.MTimeHi, new DoubleWordRegister(this).WithValueField(0, 32, FieldMode.Read,
                                                                                         valueProviderCallback: _ => (uint)(mTimers[0].Value >> 32),
                                                                                         writeCallback: (_, value) =>
                    {
                        var timerValue = mTimers[0].Value;
                        timerValue    &= 0xffffffffUL;
                        timerValue    |= (ulong)value << 32;
                        foreach (var timer in mTimers)
                        {
                            timer.Value = timerValue;
                        }
                    })
                }
            };

            for (var hart = 0; hart < numberOfTargets; ++hart)
            {
                var hartId = hart;
                registersMap.Add((long)Registers.MSipHart0 + 4 * hartId, new DoubleWordRegister(this).WithFlag(0, writeCallback: (_, value) => { irqs[2 * hartId].Set(value); }));
                registersMap.Add((long)Registers.MTimeCmpHart0Lo + 8 * hartId, new DoubleWordRegister(this).WithValueField(0, 32, writeCallback: (_, value) =>
                {
                    var limit = mTimers[hartId].Compare;
                    limit    &= ~0xffffffffUL;
                    limit    |= value;

                    irqs[2 * hartId + 1].Set(false);
                    mTimers[hartId].Compare = limit;
                }));

                registersMap.Add((long)Registers.MTimeCmpHart0Hi + 8 * hartId, new DoubleWordRegister(this).WithValueField(0, 32, writeCallback: (_, value) =>
                {
                    var limit = mTimers[hartId].Compare;
                    limit    &= 0xffffffffUL;
                    limit    |= (ulong)value << 32;

                    irqs[2 * hartId + 1].Set(false);
                    mTimers[hartId].Compare = limit;
                }));
            }

            registers = new DoubleWordRegisterCollection(this, registersMap);

            Connections = new ReadOnlyDictionary <int, IGPIO>(irqs);
        }
Ejemplo n.º 32
0
 public ExportCommand(ReadOnlyDictionary <CalculationsMode, IChart> charts) : base(charts)
 {
     Text    = MenuStrings.export_Text;
     ToolTip = MenuStrings.export_Text;
 }
 internal PartyMembersChanged(EventSource readerBackendType, SortedDictionary <uint, string> partyMembers) : base(readerBackendType)
 {
     EventType    = GetType();
     PartyMembers = new ReadOnlyDictionary <uint, string>(partyMembers);
 }
Ejemplo n.º 34
0
        static ExpTable()
        {
            #region Initialize table

            Experience[] shipexp = new Experience[] {
                new Experience(1, 0, 100),
                new Experience(2, 100, 200),
                new Experience(3, 300, 300),
                new Experience(4, 600, 400),
                new Experience(5, 1000, 500),
                new Experience(6, 1500, 600),
                new Experience(7, 2100, 700),
                new Experience(8, 2800, 800),
                new Experience(9, 3600, 900),
                new Experience(10, 4500, 1000),
                new Experience(11, 5500, 1100),
                new Experience(12, 6600, 1200),
                new Experience(13, 7800, 1300),
                new Experience(14, 9100, 1400),
                new Experience(15, 10500, 1500),
                new Experience(16, 12000, 1600),
                new Experience(17, 13600, 1700),
                new Experience(18, 15300, 1800),
                new Experience(19, 17100, 1900),
                new Experience(20, 19000, 2000),
                new Experience(21, 21000, 2100),
                new Experience(22, 23100, 2200),
                new Experience(23, 25300, 2300),
                new Experience(24, 27600, 2400),
                new Experience(25, 30000, 2500),
                new Experience(26, 32500, 2600),
                new Experience(27, 35100, 2700),
                new Experience(28, 37800, 2800),
                new Experience(29, 40600, 2900),
                new Experience(30, 43500, 3000),
                new Experience(31, 46500, 3100),
                new Experience(32, 49600, 3200),
                new Experience(33, 52800, 3300),
                new Experience(34, 56100, 3400),
                new Experience(35, 59500, 3500),
                new Experience(36, 63000, 3600),
                new Experience(37, 66600, 3700),
                new Experience(38, 70300, 3800),
                new Experience(39, 74100, 3900),
                new Experience(40, 78000, 4000),
                new Experience(41, 82000, 4100),
                new Experience(42, 86100, 4200),
                new Experience(43, 90300, 4300),
                new Experience(44, 94600, 4400),
                new Experience(45, 99000, 4500),
                new Experience(46, 103500, 4600),
                new Experience(47, 108100, 4700),
                new Experience(48, 112800, 4800),
                new Experience(49, 117600, 4900),
                new Experience(50, 122500, 5000),
                new Experience(51, 127500, 5200),
                new Experience(52, 132700, 5400),
                new Experience(53, 138100, 5600),
                new Experience(54, 143700, 5800),
                new Experience(55, 149500, 6000),
                new Experience(56, 155500, 6200),
                new Experience(57, 161700, 6400),
                new Experience(58, 168100, 6600),
                new Experience(59, 174700, 6800),
                new Experience(60, 181500, 7000),
                new Experience(61, 188500, 7300),
                new Experience(62, 195800, 7600),
                new Experience(63, 203400, 7900),
                new Experience(64, 211300, 8200),
                new Experience(65, 219500, 8500),
                new Experience(66, 228000, 8800),
                new Experience(67, 236800, 9100),
                new Experience(68, 245900, 9400),
                new Experience(69, 255300, 9700),
                new Experience(70, 265000, 10000),
                new Experience(71, 275000, 10400),
                new Experience(72, 285400, 10800),
                new Experience(73, 296200, 11200),
                new Experience(74, 307400, 11600),
                new Experience(75, 319000, 12000),
                new Experience(76, 331000, 12400),
                new Experience(77, 343400, 12800),
                new Experience(78, 356200, 13200),
                new Experience(79, 369400, 13600),
                new Experience(80, 383000, 14000),
                new Experience(81, 397000, 14500),
                new Experience(82, 411500, 15000),
                new Experience(83, 426500, 15500),
                new Experience(84, 442000, 16000),
                new Experience(85, 458000, 16500),
                new Experience(86, 474500, 17000),
                new Experience(87, 491500, 17500),
                new Experience(88, 509000, 18000),
                new Experience(89, 527000, 18500),
                new Experience(90, 545500, 19000),
                new Experience(91, 564500, 20000),
                new Experience(92, 584500, 22000),
                new Experience(93, 606500, 25000),
                new Experience(94, 631500, 30000),
                new Experience(95, 661500, 40000),
                new Experience(96, 701500, 60000),
                new Experience(97, 761500, 90000),
                new Experience(98, 851500, 148500),
                new Experience(99, 1000000, 0),
                new Experience(100, 1000000, 10000),
                new Experience(101, 1010000, 1000),
                new Experience(102, 1011000, 2000),
                new Experience(103, 1013000, 3000),
                new Experience(104, 1016000, 4000),
                new Experience(105, 1020000, 5000),
                new Experience(106, 1025000, 6000),
                new Experience(107, 1031000, 7000),
                new Experience(108, 1038000, 8000),
                new Experience(109, 1046000, 9000),
                new Experience(110, 1055000, 10000),
                new Experience(111, 1065000, 12000),
                new Experience(112, 1077000, 14000),
                new Experience(113, 1091000, 16000),
                new Experience(114, 1107000, 18000),
                new Experience(115, 1125000, 20000),
                new Experience(116, 1145000, 23000),
                new Experience(117, 1168000, 26000),
                new Experience(118, 1194000, 29000),
                new Experience(119, 1223000, 32000),
                new Experience(120, 1255000, 35000),
                new Experience(121, 1290000, 39000),
                new Experience(122, 1329000, 43000),
                new Experience(123, 1372000, 47000),
                new Experience(124, 1419000, 51000),
                new Experience(125, 1470000, 55000),
                new Experience(126, 1525000, 59000),
                new Experience(127, 1584000, 63000),
                new Experience(128, 1647000, 67000),
                new Experience(129, 1714000, 71000),
                new Experience(130, 1785000, 75000),
                new Experience(131, 1860000, 80000),
                new Experience(132, 1940000, 85000),
                new Experience(133, 2025000, 90000),
                new Experience(134, 2115000, 95000),
                new Experience(135, 2210000, 100000),
                new Experience(136, 2310000, 105000),
                new Experience(137, 2415000, 110000),
                new Experience(138, 2525000, 115000),
                new Experience(139, 2640000, 120000),
                new Experience(140, 2760000, 127000),
                new Experience(141, 2887000, 134000),
                new Experience(142, 3021000, 141000),
                new Experience(143, 3162000, 148000),
                new Experience(144, 3310000, 155000),
                new Experience(145, 3465000, 163000),
                new Experience(146, 3628000, 171000),
                new Experience(147, 3799000, 179000),
                new Experience(148, 3978000, 187000),
                new Experience(149, 4165000, 195000),
                new Experience(150, 4360000, 204000),
                new Experience(151, 4564000, 213000),
                new Experience(152, 4777000, 222000),
                new Experience(153, 4999000, 231000),
                new Experience(154, 5230000, 240000),
                new Experience(155, 5470000, 250000),
                new Experience(156, 5720000, 60000),
                new Experience(157, 5780000, 80000),
                new Experience(158, 5860000, 110000),
                new Experience(159, 5970000, 150000),
                new Experience(160, 6120000, 200000),
                new Experience(161, 6320000, 260000),
                new Experience(162, 6580000, 330000),
                new Experience(163, 6910000, 410000),
                new Experience(164, 7320000, 500000),
                new Experience(165, 7820000, 0),
            };


            Experience[] admiralexp = new Experience[] {
                new Experience(1, 0, 100),
                new Experience(2, 100, 200),
                new Experience(3, 300, 300),
                new Experience(4, 600, 400),
                new Experience(5, 1000, 500),
                new Experience(6, 1500, 600),
                new Experience(7, 2100, 700),
                new Experience(8, 2800, 800),
                new Experience(9, 3600, 900),
                new Experience(10, 4500, 1000),
                new Experience(11, 5500, 1100),
                new Experience(12, 6600, 1200),
                new Experience(13, 7800, 1300),
                new Experience(14, 9100, 1400),
                new Experience(15, 10500, 1500),
                new Experience(16, 12000, 1600),
                new Experience(17, 13600, 1700),
                new Experience(18, 15300, 1800),
                new Experience(19, 17100, 1900),
                new Experience(20, 19000, 2000),
                new Experience(21, 21000, 2100),
                new Experience(22, 23100, 2200),
                new Experience(23, 25300, 2300),
                new Experience(24, 27600, 2400),
                new Experience(25, 30000, 2500),
                new Experience(26, 32500, 2600),
                new Experience(27, 35100, 2700),
                new Experience(28, 37800, 2800),
                new Experience(29, 40600, 2900),
                new Experience(30, 43500, 3000),
                new Experience(31, 46500, 3100),
                new Experience(32, 49600, 3200),
                new Experience(33, 52800, 3300),
                new Experience(34, 56100, 3400),
                new Experience(35, 59500, 3500),
                new Experience(36, 63000, 3600),
                new Experience(37, 66600, 3700),
                new Experience(38, 70300, 3800),
                new Experience(39, 74100, 3900),
                new Experience(40, 78000, 4000),
                new Experience(41, 82000, 4100),
                new Experience(42, 86100, 4200),
                new Experience(43, 90300, 4300),
                new Experience(44, 94600, 4400),
                new Experience(45, 99000, 4500),
                new Experience(46, 103500, 4600),
                new Experience(47, 108100, 4700),
                new Experience(48, 112800, 4800),
                new Experience(49, 117600, 4900),
                new Experience(50, 122500, 5000),
                new Experience(51, 127500, 5200),
                new Experience(52, 132700, 5400),
                new Experience(53, 138100, 5600),
                new Experience(54, 143700, 5800),
                new Experience(55, 149500, 6000),
                new Experience(56, 155500, 6200),
                new Experience(57, 161700, 6400),
                new Experience(58, 168100, 6600),
                new Experience(59, 174700, 6800),
                new Experience(60, 181500, 7000),
                new Experience(61, 188500, 7300),
                new Experience(62, 195800, 7600),
                new Experience(63, 203400, 7900),
                new Experience(64, 211300, 8200),
                new Experience(65, 219500, 8500),
                new Experience(66, 228000, 8800),
                new Experience(67, 236800, 9100),
                new Experience(68, 245900, 9400),
                new Experience(69, 255300, 9700),
                new Experience(70, 265000, 10000),
                new Experience(71, 275000, 10400),
                new Experience(72, 285400, 10800),
                new Experience(73, 296200, 11200),
                new Experience(74, 307400, 11600),
                new Experience(75, 319000, 12000),
                new Experience(76, 331000, 12400),
                new Experience(77, 343400, 12800),
                new Experience(78, 356200, 13200),
                new Experience(79, 369400, 13600),
                new Experience(80, 383000, 14000),
                new Experience(81, 397000, 14500),
                new Experience(82, 411500, 15000),
                new Experience(83, 426500, 15500),
                new Experience(84, 442000, 16000),
                new Experience(85, 458000, 16500),
                new Experience(86, 474500, 17000),
                new Experience(87, 491500, 17500),
                new Experience(88, 509000, 18000),
                new Experience(89, 527000, 18500),
                new Experience(90, 545500, 19000),
                new Experience(91, 564500, 20000),
                new Experience(92, 584500, 22000),
                new Experience(93, 606500, 25000),
                new Experience(94, 631500, 30000),
                new Experience(95, 661500, 40000),
                new Experience(96, 701500, 60000),
                new Experience(97, 761500, 90000),
                new Experience(98, 851500, 148500),
                new Experience(99, 1000000, 300000),
                new Experience(100, 1300000, 300000),
                new Experience(101, 1600000, 300000),
                new Experience(102, 1900000, 300000),
                new Experience(103, 2200000, 400000),
                new Experience(104, 2600000, 400000),
                new Experience(105, 3000000, 500000),
                new Experience(106, 3500000, 500000),
                new Experience(107, 4000000, 600000),
                new Experience(108, 4600000, 600000),
                new Experience(109, 5200000, 700000),
                new Experience(110, 5900000, 700000),
                new Experience(111, 6600000, 800000),
                new Experience(112, 7400000, 800000),
                new Experience(113, 8200000, 900000),
                new Experience(114, 9100000, 900000),
                new Experience(115, 10000000, 1000000),
                new Experience(116, 11000000, 1000000),
                new Experience(117, 12000000, 1000000),
                new Experience(118, 13000000, 1000000),
                new Experience(119, 14000000, 1000000),
                new Experience(120, 15000000, 0)
            };

            ShipExp    = new ReadOnlyDictionary <int, Experience>(shipexp.ToDictionary(exp => exp.Level));
            AdmiralExp = new ReadOnlyDictionary <int, Experience>(admiralexp.ToDictionary(exp => exp.Level));

            #endregion
        }
Ejemplo n.º 35
0
            public SettingsUpdates(/*OPTIONAL*/ ExceptionBreakpointState?initialNewCategoryState, /*OPTIONAL*/ ReadOnlyDictionary <string, ExceptionBreakpointState> initialRuleChanges)
            {
                this.NewCategoryState = initialNewCategoryState;

                // The dictionary constructor which takes a read only dictionary is unhappy if we pass in null, so switch off which constructor we call
                if (initialRuleChanges != null)
                {
                    this.RulesToAdd = new Dictionary <string, ExceptionBreakpointState>(initialRuleChanges);
                }
                else
                {
                    this.RulesToAdd = new Dictionary <string, ExceptionBreakpointState>();
                }
            }
Ejemplo n.º 36
0
 public KeywordsViewModel(ReadOnlyDictionary <string, int> keywords)
 {
     Keywords = keywords ?? throw new ArgumentNullException(nameof(keywords));
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Finds the best streams for audio video, and subtitles.
        /// </summary>
        /// <param name="ic">The ic.</param>
        /// <param name="streams">The streams.</param>
        /// <returns>The star infos</returns>
        private static Dictionary <AVMediaType, StreamInfo> FindBestStreams(AVFormatContext *ic, ReadOnlyDictionary <int, StreamInfo> streams)
        {
            // Initialize and clear all the stream indexes.
            var streamIndexes = new Dictionary <AVMediaType, int>();

            for (var i = 0; i < (int)AVMediaType.AVMEDIA_TYPE_NB; i++)
            {
                streamIndexes[(AVMediaType)i] = -1;
            }

            // Find best streams for each component
            // if we passed null instead of the requestedCodec pointer, then
            // find_best_stream would not validate whether a valid decoder is registed.
            AVCodec *requestedCodec = null;

            streamIndexes[AVMediaType.AVMEDIA_TYPE_VIDEO] =
                ffmpeg.av_find_best_stream(
                    ic,
                    AVMediaType.AVMEDIA_TYPE_VIDEO,
                    streamIndexes[(int)AVMediaType.AVMEDIA_TYPE_VIDEO],
                    -1,
                    &requestedCodec,
                    0);

            streamIndexes[AVMediaType.AVMEDIA_TYPE_AUDIO] =
                ffmpeg.av_find_best_stream(
                    ic,
                    AVMediaType.AVMEDIA_TYPE_AUDIO,
                    streamIndexes[AVMediaType.AVMEDIA_TYPE_AUDIO],
                    streamIndexes[AVMediaType.AVMEDIA_TYPE_VIDEO],
                    &requestedCodec,
                    0);

            streamIndexes[AVMediaType.AVMEDIA_TYPE_SUBTITLE] =
                ffmpeg.av_find_best_stream(
                    ic,
                    AVMediaType.AVMEDIA_TYPE_SUBTITLE,
                    streamIndexes[AVMediaType.AVMEDIA_TYPE_SUBTITLE],
                    streamIndexes[AVMediaType.AVMEDIA_TYPE_AUDIO] >= 0 ?
                    streamIndexes[AVMediaType.AVMEDIA_TYPE_AUDIO] :
                    streamIndexes[AVMediaType.AVMEDIA_TYPE_VIDEO],
                    &requestedCodec,
                    0);

            var result = new Dictionary <AVMediaType, StreamInfo>();

            foreach (var kvp in streamIndexes.Where(n => n.Value >= 0))
            {
                result[kvp.Key] = streams[kvp.Value];
            }

            return(result);
        }
Ejemplo n.º 38
0
 public CancellableEventArgs(bool canCancel, EventMessages messages, IDictionary <string, object> additionalData)
 {
     CanCancel      = canCancel;
     Messages       = messages;
     AdditionalData = new ReadOnlyDictionary <string, object>(additionalData);
 }
Ejemplo n.º 39
0
 public void LoadExtensions(IDictionary <Type, IDictionary <string, string> > extensions)
 {
     Extensions = new ReadOnlyDictionary <Type, IDictionary <string, string> >(extensions);
 }
Ejemplo n.º 40
0
        private string GetQuery(string queryType, ICollection <GraphQLField> fields, params GraphQLQueryArgument[] queryArguments)
        {
            // Get all the arguments from the fields
            var fieldArguments = Helper.GetAllArgumentsFromFields(fields).ToList();

            // Create mapping for each argument field
            IDictionary <GraphQLFieldArguments, GraphQLQueryArgument> arguments = new Dictionary <GraphQLFieldArguments, GraphQLQueryArgument>();
            ICollection <GraphQLFieldArguments> argumentsNotSet = new Collection <GraphQLFieldArguments>();
            List <string> duplicateVariableNames = new List <string>();

            foreach (var fieldArgument in fieldArguments)
            {
                // Find matching query arguments
                var queryArgument = queryArguments.Where(e => e.VariableName == fieldArgument.VariableName).Take(2).ToList();

                switch (queryArgument.Count)
                {
                case 0:
                    // Set default value
                    if (fieldArgument.DefaultValue != null)
                    {
                        arguments.Add(fieldArgument, new GraphQLQueryArgument(fieldArgument.VariableName, fieldArgument.DefaultValue));
                        break;
                    }
                    // If no default was set we need to check if it was required
                    if (fieldArgument.IsRequired)
                    {
                        argumentsNotSet.Add(fieldArgument);
                    }
                    break;

                case 1:
                    arguments.Add(fieldArgument, queryArgument[0]);
                    break;

                default:
                    duplicateVariableNames.Add(queryArgument[0].VariableName);
                    break;
                }
            }

            // If any arguments was detected not set
            if (argumentsNotSet.Any())
            {
                throw new GraphQLArgumentsRequiredException(argumentsNotSet);
            }

            // If duplicate variable names has been detected
            if (duplicateVariableNames.Any())
            {
                throw new GraphQLDuplicateVariablesException(duplicateVariableNames);
            }

            // Get readonly arguments
            var readonlyArguments = new ReadOnlyDictionary <GraphQLFieldArguments, GraphQLQueryArgument>(arguments);

            // Get query
            var query   = GetGraphQLQuery(queryType, GetArguments(readonlyArguments), GetFields(fields, readonlyArguments));
            var request = GetQueryRequest(query, readonlyArguments);

            // Logging
            if (Logger != null && Logger.IsEnabled(LogLevel.Debug))
            {
                Logger.LogDebug($"Generated the GraphQL query {request} from the fields:{Environment.NewLine + string.Join(Environment.NewLine, fields)}");
            }

            return(request);
        }
Ejemplo n.º 41
0
        internal static void SetWorkAll()
        {
            if (isSetAllWorkRun)
            {
                return;
            }

            Task.Factory.StartNew(() =>
            {
                isSetAllWorkRun = true;
                MyLog.LogDarkBlue("ScheduleAPIPatch.SetAllWork. start");

                ReadOnlyDictionary <int, NightWorkState> night_works_state_dic = GameMain.Instance.CharacterMgr.status.night_works_state_dic;
                MyLog.LogMessage("ScheduleAPIPatch.SetAllWork.night_works_state_dic:" + night_works_state_dic.Count);

                foreach (var item in night_works_state_dic)
                {
                    NightWorkState nightWorkState = item.Value;
                    nightWorkState.finish         = true;
                }

                MyLog.LogMessage("ScheduleAPIPatch.SetAllWork.YotogiData:" + ScheduleCSVData.YotogiData.Values.Count);
                foreach (Maid maid in GameMain.Instance.CharacterMgr.GetStockMaidList())
                {
                    MyLog.LogMessage(".SetAllWork.Yotogi:" + MyUtill.GetMaidFullName(maid), ScheduleCSVData.YotogiData.Values.Count);
                    if (maid.status.heroineType == HeroineType.Sub)
                    {
                        continue;
                    }


                    foreach (ScheduleCSVData.Yotogi yotogi in ScheduleCSVData.YotogiData.Values)
                    {
#if DEBUG
                        if (Lilly.isLogOn)
                        {
                            MyLog.LogInfo(".SetAllWork:"
                                          + yotogi.id
                                          , yotogi.name
                                          , yotogi.type
                                          , yotogi.yotogiType
                                          );
                        }
#endif
                        if (DailyMgr.IsLegacy)
                        {
                            maid.status.OldStatus.SetFlag("_PlayedNightWorkId" + yotogi.id, 1);
                        }
                        else
                        {
                            maid.status.SetFlag("_PlayedNightWorkId" + yotogi.id, 1);
                        }
                        if (yotogi.condFlag1.Count > 0)
                        {
                            for (int n = 0; n < yotogi.condFlag1.Count; n++)
                            {
                                maid.status.SetFlag(yotogi.condFlag1[n], 1);
                            }
                        }
                        if (yotogi.condFlag0.Count > 0)
                        {
                            for (int num = 0; num < yotogi.condFlag0.Count; num++)
                            {
                                maid.status.SetFlag(yotogi.condFlag0[num], 0);
                            }
                        }
                    }
                    if (DailyMgr.IsLegacy)
                    {
                        maid.status.OldStatus.SetFlag("_PlayedNightWorkVip", 1);
                    }
                    else
                    {
                        maid.status.SetFlag("_PlayedNightWorkVip", 1);
                    }
                }

                MyLog.LogDarkBlue("ScheduleAPIPatch.SetAllWork. end");
                isSetAllWorkRun = false;
            });
        }
Ejemplo n.º 42
0
 private ErrorData MakeError(ReadOnlyDictionary <string, object> attributes = null)
 {
     return(new ErrorData("error message", "error.type", null, System.DateTime.UtcNow, attributes, false));
 }
 public TestConfiguration()
 {
     _settings = new ReadOnlyDictionary <string, string>(new Dictionary <string, string>());
     _truncatedRuntimeFrameworkVersion = null;
     _configStringView = string.Empty;
 }
Ejemplo n.º 44
0
 public void LoadProviders(Dictionary <string, string> providers)
 {
     Providers = new ReadOnlyDictionary <string, string>(providers);
 }
        public virtual async Task <TResponse> RequestAsync <TResponse>(RequestData requestData,
                                                                       CancellationToken cancellationToken
                                                                       )
            where TResponse : class, ITransportResponse, new()
        {
            Action unregisterWaitHandle   = null;
            int?   statusCode             = null;
            IEnumerable <string> warnings = null;
            Stream    responseStream      = null;
            Exception ex       = null;
            string    mimeType = null;
            ReadOnlyDictionary <TcpState, int> tcpStats = null;
            ReadOnlyDictionary <string, ThreadPoolStatistics> threadPoolStats = null;

            try
            {
                var data    = requestData.PostData;
                var request = CreateHttpWebRequest(requestData);
                using (cancellationToken.Register(() => request.Abort()))
                {
                    if (data != null)
                    {
                        var apmGetRequestStreamTask =
                            Task.Factory.FromAsync(request.BeginGetRequestStream, r => request.EndGetRequestStream(r), null);
                        unregisterWaitHandle = RegisterApmTaskTimeout(apmGetRequestStreamTask, request, requestData);

                        using (var stream = await apmGetRequestStreamTask.ConfigureAwait(false))
                        {
                            if (requestData.HttpCompression)
                            {
                                using (var zipStream = new GZipStream(stream, CompressionMode.Compress))
                                    await data.WriteAsync(zipStream, requestData.ConnectionSettings, cancellationToken).ConfigureAwait(false);
                            }
                            else
                            {
                                await data.WriteAsync(stream, requestData.ConnectionSettings, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        unregisterWaitHandle?.Invoke();
                    }
                    requestData.MadeItToResponse = true;
                    //http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx
                    //Either the stream or the response object needs to be closed but not both although it won't
                    //throw any errors if both are closed atleast one of them has to be Closed.
                    //Since we expose the stream we let closing the stream determining when to close the connection

                    var apmGetResponseTask = Task.Factory.FromAsync(request.BeginGetResponse, r => request.EndGetResponse(r), null);
                    unregisterWaitHandle = RegisterApmTaskTimeout(apmGetResponseTask, request, requestData);

                    if (requestData.TcpStats)
                    {
                        tcpStats = TcpStats.GetStates();
                    }

                    if (requestData.ThreadPoolStats)
                    {
                        threadPoolStats = ThreadPoolStats.GetStats();
                    }

                    var httpWebResponse = (HttpWebResponse)await apmGetResponseTask.ConfigureAwait(false);

                    HandleResponse(httpWebResponse, out statusCode, out responseStream, out mimeType);
                    if (httpWebResponse.SupportsHeaders && httpWebResponse.Headers.HasKeys() && httpWebResponse.Headers.AllKeys.Contains("Warning"))
                    {
                        warnings = httpWebResponse.Headers.GetValues("Warning");
                    }
                }
            }
            catch (WebException e)
            {
                ex = e;
                if (e.Response is HttpWebResponse httpWebResponse)
                {
                    HandleResponse(httpWebResponse, out statusCode, out responseStream, out mimeType);
                }
            }
            finally
            {
                unregisterWaitHandle?.Invoke();
            }
            responseStream ??= Stream.Null;
            var response = await ResponseBuilder.ToResponseAsync <TResponse>
                               (requestData, ex, statusCode, warnings, responseStream, mimeType, cancellationToken)
                           .ConfigureAwait(false);

            // set TCP and threadpool stats on the response here so that in the event the request fails after the point of
            // gathering stats, they are still exposed on the call details. Ideally these would be set inside ResponseBuilder.ToResponse,
            // but doing so would be a breaking change in 7.x
            response.ApiCall.TcpStats        = tcpStats;
            response.ApiCall.ThreadPoolStats = threadPoolStats;
            return(response);
        }
 public TestConfiguration(Dictionary <string, string> initialSettings)
 {
     _settings = new ReadOnlyDictionary <string, string>(new Dictionary <string, string>(initialSettings));
     _truncatedRuntimeFrameworkVersion = GetTruncatedRuntimeFrameworkVersion();
     _configStringView = GetStringViewWithVersion(RuntimeFrameworkVersion);
 }
Ejemplo n.º 47
0
            public void TestCSharpQueryClassGenerator()
            {
                var intType     = new BindVariableType("INT", typeof(int), false);
                var varcharType = new BindVariableType("VARCHAR", typeof(string), false);

                var dataTypes =
                    new Dictionary <string, BindVariableType>
                {
                    { intType.Name, intType },
                    { varcharType.Name, varcharType }
                };

                var readOnlyDataTypes = new ReadOnlyDictionary <string, BindVariableType>(dataTypes);

                var columnHeaders =
                    new[]
                {
                    new ColumnHeader {
                        ColumnIndex = 0, Name = "TestColumn1", DataType = typeof(int)
                    },
                    new ColumnHeader {
                        ColumnIndex = 1, Name = "TestColumn2", DataType = typeof(string)
                    }
                };

                var statementModel =
                    new StatementExecutionModel
                {
                    StatementText = "SELECT @testBindVariable1 TestColumn1, @testBindVariable2 TestColumn2",
                    BindVariables =
                        new[]
                    {
                        new BindVariableModel(new BindVariableConfiguration {
                            Name = "testBindVariable1", DataType = intType.Name, DataTypes = readOnlyDataTypes
                        }),
                        new BindVariableModel(new BindVariableConfiguration {
                            Name = "testBindVariable2", DataType = varcharType.Name, DataTypes = readOnlyDataTypes
                        })
                    }
                };

                var builder = new StringBuilder();

                using (var writer = new StringWriter(builder))
                {
                    CSharpQueryClassGenerator.Generate(statementModel, columnHeaders, writer);
                }

                var result = builder.ToString();

                const string expectedResult =
                    @"using System;
using System.Data;

public class Query
{
	private readonly IDbConnection _connection;

	private const string CommandText =
@""SELECT @testBindVariable1 TestColumn1, @testBindVariable2 TestColumn2"";

	public Query(IDbConnection connection)
	{
		_connection = connection;
	}

	public IEnumerable<ResultRow> Execute(Int32 testBindVariable1, String testBindVariable2)
	{
		using (var command = _connection.CreateCommand())
		{
			command.CommandText = CommandText;
			
			var parametertestBindVariable1 = command.CreateParameter();
			parametertestBindVariable1.Value = testBindVariable1;
			command.Parameters.Add(parametertestBindVariable1);

			var parametertestBindVariable2 = command.CreateParameter();
			parametertestBindVariable2.Value = testBindVariable2;
			command.Parameters.Add(parametertestBindVariable2);

			_connection.Open();

			using (var reader = command.ExecuteReader())
			{
				while (reader.Read())
				{
					var row =
						new ResultRow
						{
							TestColumn1 = GetReaderValue<Int32?>(reader[nameof(ResultRow.TestColumn1)]),
							TestColumn2 = GetReaderValue<String>(reader[nameof(ResultRow.TestColumn2)])
						};

					yield return row;
				}
			}

			_connection.Close();
		}
	}

	private static T GetReaderValue<T>(object value)
	{
		return value == DBNull.Value
			? default(T)
			: (T)value;
	}
}

public class ResultRow
{
	public Int32? TestColumn1 { get; set; }
	public String TestColumn2 { get; set; }
}
";

                result.ShouldBe(expectedResult);
            }
        public virtual TResponse Request <TResponse>(RequestData requestData)
            where TResponse : class, ITransportResponse, new()
        {
            int?statusCode = null;
            IEnumerable <string> warnings = null;
            Stream    responseStream      = null;
            Exception ex       = null;
            string    mimeType = null;
            ReadOnlyDictionary <TcpState, int> tcpStats = null;
            ReadOnlyDictionary <string, ThreadPoolStatistics> threadPoolStats = null;

            try
            {
                var request = CreateHttpWebRequest(requestData);
                var data    = requestData.PostData;

                if (data != null)
                {
                    using (var stream = request.GetRequestStream())
                    {
                        if (requestData.HttpCompression)
                        {
                            using (var zipStream = new GZipStream(stream, CompressionMode.Compress))
                                data.Write(zipStream, requestData.ConnectionSettings);
                        }
                        else
                        {
                            data.Write(stream, requestData.ConnectionSettings);
                        }
                    }
                }
                requestData.MadeItToResponse = true;

                if (requestData.TcpStats)
                {
                    tcpStats = TcpStats.GetStates();
                }

                if (requestData.ThreadPoolStats)
                {
                    threadPoolStats = ThreadPoolStats.GetStats();
                }

                //http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx
                //Either the stream or the response object needs to be closed but not both although it won't
                //throw any errors if both are closed atleast one of them has to be Closed.
                //Since we expose the stream we let closing the stream determining when to close the connection
                var httpWebResponse = (HttpWebResponse)request.GetResponse();
                HandleResponse(httpWebResponse, out statusCode, out responseStream, out mimeType);

                //response.Headers.HasKeys() can return false even if response.Headers.AllKeys has values.
                if (httpWebResponse.SupportsHeaders && httpWebResponse.Headers.Count > 0 && httpWebResponse.Headers.AllKeys.Contains("Warning"))
                {
                    warnings = httpWebResponse.Headers.GetValues("Warning");
                }
            }
            catch (WebException e)
            {
                ex = e;
                if (e.Response is HttpWebResponse httpWebResponse)
                {
                    HandleResponse(httpWebResponse, out statusCode, out responseStream, out mimeType);
                }
            }

            responseStream ??= Stream.Null;
            var response = ResponseBuilder.ToResponse <TResponse>(requestData, ex, statusCode, warnings, responseStream, mimeType);

            // set TCP and threadpool stats on the response here so that in the event the request fails after the point of
            // gathering stats, they are still exposed on the call details. Ideally these would be set inside ResponseBuilder.ToResponse,
            // but doing so would be a breaking change in 7.x
            response.ApiCall.TcpStats        = tcpStats;
            response.ApiCall.ThreadPoolStats = threadPoolStats;
            return(response);
        }
Ejemplo n.º 49
0
 internal TimeTable(List <Html.Input> inputs)
 {
     Grid = new ReadOnlyDictionary <DayOfWeek, TimeSlot[]>(InitializeSlots(inputs));
     Rows = InitializeRows();
 }
Ejemplo n.º 50
0
 public ConstantDictionary(IDictionary <K, V> map)
 {
     wrapped = new ReadOnlyDictionary <K, V>(map);
 }
Ejemplo n.º 51
0
 static PluginDescription()
 {
     NoPlugins           = new IPluginImplementationDescription[0];
     NoSerializableTypes = new ReadOnlyDictionary <string, string>(new Dictionary <string, string>());
 }
Ejemplo n.º 52
0
 public ActionListDescriptor(uint type, ReadOnlyDictionary <uint, AETEValue> descriptorValues)
 {
     this.type             = type;
     this.descriptorValues = descriptorValues;
 }