private void GetListByType(DefaultTypes type, out List <SoundEffect> searchList)
    {
        switch (type)
        {
        case DefaultTypes.UseItem:
            searchList = Items;
            break;

        case DefaultTypes.Death:
            searchList = Deaths;
            break;

        case DefaultTypes.Win:
            searchList = Wins;
            break;

        case DefaultTypes.Damage:
            searchList = Damage;
            break;

        default:
            searchList = Clips;
            break;
        }
    }
        /// <summary>
        /// Adds an instance of <see cref="Logger"/> retrieved from <see cref="LoggerFactory"/> and an
        /// instance of <see cref="ILoggerProvider"/> that uses that logger to the specified
        /// <see cref="IServiceCollection"/> as singletons.
        /// </summary>
        /// <param name="builder">The IWebHostBuilder being extended.</param>
        /// <param name="rockLibLoggerName">The name of the RockLib logger used for logging.</param>
        /// /// <param name="defaultTypes">
        /// An object that defines the default types to be used when a type is not explicitly specified by a
        /// configuration section.
        /// </param>
        /// <param name="valueConverters">
        /// An object that defines custom converter functions that are used to convert string configuration
        /// values to a target type.
        /// </param>
        /// <param name="setConfigRoot">
        /// Whether to set the value of the <see cref="Config.Root"/> property to the <see cref="IConfiguration"/>
        /// containing the merged configuration of the application and the <see cref="IWebHost"/>.
        /// </param>
        /// <param name="registerAspNetCoreLogger">
        /// Whether to register a RockLib <see cref="ILoggerProvider"/> with the DI system.
        /// </param>
        /// <returns>IWebHostBuilder for chaining</returns>
        /// <remarks>
        /// This method has a side-effect of calling the <see cref="Config.SetRoot(IConfiguration)"/>
        /// method, passing it the instance of <see cref="IConfiguration"/> obtained from the local
        /// <see cref="IServiceProvider"/>.
        /// </remarks>
        public static IWebHostBuilder UseRockLibLogging(this IWebHostBuilder builder, string rockLibLoggerName = Logger.DefaultName,
                                                        DefaultTypes defaultTypes = null, ValueConverters valueConverters = null,
                                                        bool setConfigRoot        = true, bool registerAspNetCoreLogger   = false)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (setConfigRoot)
            {
                builder.SetConfigRoot();
            }

            builder.ConfigureServices(services =>
            {
                services.AddLoggerFromLoggerFactory(rockLibLoggerName, defaultTypes, valueConverters);
                if (registerAspNetCoreLogger)
                {
                    services.AddRockLibLoggerProvider();
                }
            });

            return(builder);
        }
Example #3
0
        /// <summary>
        /// Creates a new instance of <see cref="ILogger"/> with a name matching the <paramref name="name"/>
        /// parameter that is backed by the value of the <paramref name="configuration"/> parameter.
        /// </summary>
        /// <param name="configuration">
        /// An instance of <see cref="IConfiguration"/> that defines the loggers that can be retrieved. The
        /// configuration can define a single logger object or a list of logger objects.
        /// </param>
        /// <param name="name">The name of the logger to create.</param>
        /// <param name="defaultTypes">
        /// An object that defines the default types to be used when a type is not explicitly specified by a
        /// configuration section.
        /// </param>
        /// <param name="valueConverters">
        /// An object that defines custom converter functions that are used to convert string configuration
        /// values to a target type.
        /// </param>
        /// <param name="resolver">
        /// An object that can retrieve constructor parameter values that are not found in configuration. This
        /// object is an adapter for dependency injection containers, such as Ninject, Unity, Autofac, or
        /// StructureMap. Consider using the <see cref="Resolver"/> class for this parameter, as it supports
        /// most depenedency injection containers.
        /// </param>
        /// <param name="reloadOnConfigChange">
        /// Whether to create an instance of <see cref="ILogger"/> that automatically reloads itself when its
        /// configuration changes. Default is true.
        /// </param>
        /// <returns>A new logger with a matching name.</returns>
        /// <exception cref="KeyNotFoundException">
        /// If a logger with a name specified by the <paramref name="name"/> parameter is not defined in
        /// the value of the <paramref name="configuration"/> parameter.
        /// </exception>
        public static ILogger CreateLogger(this IConfiguration configuration, string name = Logger.DefaultName,
                                           DefaultTypes defaultTypes = null, ValueConverters valueConverters = null,
                                           IResolver resolver        = null, bool reloadOnConfigChange = true)
        {
            if (defaultTypes == null)
            {
                defaultTypes = new DefaultTypes();
            }
            if (!defaultTypes.TryGet(typeof(ILogger), out var dummy))
            {
                defaultTypes.Add(typeof(ILogger), typeof(Logger));
            }

            if (configuration.IsList())
            {
                foreach (var child in configuration.GetChildren())
                {
                    if (name.Equals(child.GetSectionName(), StringComparison.OrdinalIgnoreCase))
                    {
                        return(reloadOnConfigChange
                            ? child.CreateReloadingProxy <ILogger>(defaultTypes, valueConverters, resolver)
                            : child.Create <ILogger>(defaultTypes, valueConverters, resolver));
                    }
                }
            }
            else if (name.Equals(configuration.GetSectionName(), StringComparison.OrdinalIgnoreCase))
            {
                return(reloadOnConfigChange
                    ? configuration.CreateReloadingProxy <ILogger>(defaultTypes, valueConverters, resolver)
                    : configuration.Create <ILogger>(defaultTypes, valueConverters, resolver));
            }

            throw new KeyNotFoundException($"No loggers were found matching the name '{name}'.");
        }
Example #4
0
        public void DefaultTypesFunctionsProperly()
        {
            if (!Config.IsLocked)
            {
                var dummy = Config.Root;
            }

            var defaultTypes = new DefaultTypes
            {
                { typeof(ILogger), typeof(TestLogger) },
                { typeof(ITestDependency), typeof(TestDependencyB) }
            };

            var fakeBuilder = new FakeWebHostBuilder()
            {
                ServiceCollection = new ServiceCollection()
            };

            fakeBuilder.UseRockLibLogging("TestLogger1", defaultTypes: defaultTypes, registerAspNetCoreLogger: true);

            var logger = fakeBuilder.ServiceCollection[1].ImplementationFactory.Invoke(null);

            logger.Should().BeOfType <TestLogger>();

            var testLogger = (TestLogger)logger;

            testLogger.Dependency.Should().BeOfType <TestDependencyB>();
        }
        /// <summary>
        /// Adds a singleton <see cref="ILogger"/> service, created with <see cref="LoggerFactory"/>, to the specified
        /// <see cref="IServiceCollection"/>.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
        /// <param name="rockLibLoggerName">The name of the RockLib logger used for logging.</param>
        /// <param name="defaultTypes">
        /// An object that defines the default types to be used when a type is not explicitly specified by a
        /// configuration section.
        /// </param>
        /// <param name="valueConverters">
        /// An object that defines custom converter functions that are used to convert string configuration
        /// values to a target type.
        /// </param>
        /// <param name="addLoggerProvider">
        /// Whether to also add a singleton <see cref="ILoggerProvider"/> service with a <see cref="RockLibLoggerProvider"/>
        /// implementation to the service collection.
        /// </param>
        /// <param name="reloadOnConfigChange">
        /// Whether instances of <see cref="ILogger"/> created by the service collection will reload when their
        /// configuration changes.
        /// </param>
        /// <returns>The same <see cref="IServiceCollection"/>.</returns>
        public static IServiceCollection AddRockLibLoggerSingleton(this IServiceCollection services, string rockLibLoggerName = Logger.DefaultName,
                                                                   DefaultTypes defaultTypes = null, ValueConverters valueConverters = null, bool addLoggerProvider = false, bool reloadOnConfigChange = true)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (services.Any(s => s.ServiceType == typeof(ILogger)))
            {
                throw new ArgumentException("RockLib.Logging.ILogger has already been added to the service collection.", nameof(services));
            }

            services.AddSingleton(serviceProvider =>
            {
                var resolver = new Resolver(type => serviceProvider.GetService(type));
                return(LoggerFactory.Create(rockLibLoggerName, defaultTypes, valueConverters, resolver, reloadOnConfigChange));
            });

            if (addLoggerProvider)
            {
                services.AddRockLibLoggerProviderSingleton();
            }

            return(services);
        }
        public virtual JsonResult AgreementTypeOptions()
        {
            var comboBox = new ComboBoxOptions
            {
                strict      = false,
                buttonTitle = "Show examples",
                source      = DefaultTypes.Select(text => new AutoCompleteOption {
                    label = text, value = text,
                }),
            };
            var configuration = _queryProcessor.Execute(new GetMyInstitutionalAgreementConfigurationQuery(User));

            if (configuration != null)
            {
                comboBox.source = configuration.AllowedTypeValues.OrderBy(o => o.Text).Select(o => o.Text)
                                  .Select(t => new AutoCompleteOption {
                    label = t, value = t,
                });
                comboBox.strict = !configuration.IsCustomTypeAllowed;
                if (comboBox.strict)
                {
                    comboBox.buttonTitle = "Select one";
                }
            }
            return(Json(comboBox, JsonRequestBehavior.AllowGet));
        }
Example #7
0
        public void ValueConvertersFunctionsProperly()
        {
            var defaultTypes = new DefaultTypes
            {
                { typeof(ILogger), typeof(TestLogger) }
            };

            Point ParsePoint(string value)
            {
                var split = value.Split(',');

                return(new Point(int.Parse(split[0]), int.Parse(split[1])));
            }

            var valueConverters = new ValueConverters
            {
                { typeof(Point), ParsePoint }
            };

            var fakeBuilder = new FakeWebHostBuilder();

            fakeBuilder.UseRockLibLogging("TestLogger2", defaultTypes: defaultTypes, valueConverters: valueConverters, registerAspNetCoreLogger: true);

            var logger = fakeBuilder.ServiceCollection[1].ImplementationFactory.Invoke(null);

            logger.Should().BeOfType <TestLogger>();

            var testLogger = (TestLogger)logger;

            testLogger.Location.X.Should().Be(2);
            testLogger.Location.Y.Should().Be(3);
        }
    public void PlaySFX(string soundName, DefaultTypes type = DefaultTypes.Any, float volume = 1f)
    {
        AudioClip clip = GetSound(soundName, type);

        if (clip)
        {
            SFX.PlayOneShot(clip, volume);
        }
    }
    public void PlayRandomSFX(DefaultTypes type, float volume = 1f)
    {
        AudioClip clip = GetRandomSound(type);

        if (clip)
        {
            SFX.PlayOneShot(clip, volume);
        }
    }
Example #10
0
        /// <summary>
        /// Creates an instance of <see cref="DiagnosticsSettings"/> from the specified configuration.
        /// </summary>
        /// <see cref="EventTypeFilter"/>.
        /// <param name="configuration">
        /// A configuration object that contains the values for a <see cref="DiagnosticsSettings"/> object.
        /// </param>
        /// <returns>
        /// A <see cref="DiagnosticsSettings"/> object created from the values found in the
        /// <paramref name="configuration"/> parameter.
        /// </returns>
        /// <remarks>
        /// This method creates the instance of <see cref="DiagnosticsSettings"/> by applying the
        /// <see cref="ConfigurationObjectFactory.Create{T}(IConfiguration, DefaultTypes, ValueConverters)"/>
        /// extension method to the <paramref name="configuration"/> parameter and passing
        /// it a <see cref="DefaultTypes"/> argument with two mappings: the default type for
        /// the abstract <see cref="TraceListener"/> class is <see cref="DefaultTraceListener"/>,
        /// and the default type for the abstract <see cref="TraceFilter"/> class is
        /// </remarks>
        public static DiagnosticsSettings CreateDiagnosticsSettings(this IConfiguration configuration)
        {
            var defaultTypes = new DefaultTypes
            {
                { typeof(TraceListener), typeof(DefaultTraceListener) },
                { typeof(TraceFilter), typeof(EventTypeFilter) }
            };

            return(configuration.Create <DiagnosticsSettings>(defaultTypes));
        }
Example #11
0
        public void TryGetByDeclaringTypeAndMemberNameReturnsFalseWhenThereNotIsAMatch()
        {
            var defaultTypes = new DefaultTypes();

            Assert.False(defaultTypes.TryGet(typeof(Foo), "bar", out Type defaultFooBar));
            Assert.Null(defaultFooBar);

            Assert.False(defaultTypes.TryGet(typeof(Foo), "baz", out Type defaultFooBaz));
            Assert.Null(defaultFooBaz);
        }
Example #12
0
        public void TryGetByTargetTypeReturnsFalseWhenThereNotIsAMatch()
        {
            var defaultTypes = new DefaultTypes();

            Assert.False(defaultTypes.TryGet(typeof(IBar), out Type defaultFooBar));
            Assert.Null(defaultFooBar);

            Assert.False(defaultTypes.TryGet(typeof(IBaz), out Type defaultFooBaz));
            Assert.Null(defaultFooBaz);
        }
Example #13
0
        public void GivenNoMatchingMembers_ThrowsArgumentException()
        {
            var defaultTypes = new DefaultTypes();

            var actual = Assert.Throws <ArgumentException>(() => defaultTypes.Add(typeof(Foo), "qux", typeof(Qux)));

#if DEBUG
            var expected = Exceptions.NoMatchingMembers(typeof(Foo), "qux");
            Assert.Equal(expected.Message, actual.Message);
#endif
        }
Example #14
0
        public void GivenDefaultTypeIsNotAssignableToTargetType_ThrowsArgumentException()
        {
            var defaultTypes = new DefaultTypes();

            var actual = Assert.Throws <ArgumentException>(() => defaultTypes.Add(typeof(IBar), typeof(Qux)));

#if DEBUG
            var expected = Exceptions.DefaultTypeIsNotAssignableToTargetType(typeof(IBar), typeof(Qux));
            Assert.Equal(expected.Message, actual.Message);
#endif
        }
Example #15
0
        public void GivenAbstractDefaultType2_ThrowsArgumentException()
        {
            var defaultTypes = new DefaultTypes();

            var actual = Assert.Throws <ArgumentException>(() => defaultTypes.Add(typeof(IBar), typeof(AbstractBar)));

#if DEBUG
            var expected = Exceptions.DefaultTypeCannotBeAbstract(typeof(AbstractBar));
            Assert.Equal(expected.Message, actual.Message);
#endif
        }
Example #16
0
        /// <summary>
        /// Creates an instance of the <see cref="ISender"/> interface identified by
        /// its name from the 'senders' section of the <paramref name="configuration"/> parameter.
        /// </summary>
        /// <param name="configuration">
        /// A configuration object that contains the specified sender in its 'senders' section.
        /// </param>
        /// <param name="name">The name that identifies which sender from configuration to create.</param>
        /// <param name="defaultTypes">
        /// An object that defines the default types to be used when a type is not explicitly specified by a
        /// configuration section.
        /// </param>
        /// <param name="valueConverters">
        /// An object that defines custom converter functions that are used to convert string configuration
        /// values to a target type.
        /// </param>
        /// <param name="resolver">
        /// An object that can retrieve constructor parameter values that are not found in configuration. This
        /// object is an adapter for dependency injection containers, such as Ninject, Unity, Autofac, or
        /// StructureMap. Consider using the <see cref="Resolver"/> class for this parameter, as it supports
        /// most depenedency injection containers.
        /// </param>
        /// <param name="reloadOnConfigChange">
        /// Whether to create an instance of <see cref="ISender"/> that automatically reloads itself when its
        /// configuration changes. Default is true.
        /// </param>
        /// <returns>A new instance of the <see cref="ISender"/> interface.</returns>
        public static ISender CreateSender(this IConfiguration configuration, string name,
                                           DefaultTypes defaultTypes = null, ValueConverters valueConverters = null,
                                           IResolver resolver        = null, bool reloadOnConfigChange = true)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            return(configuration.CreateScenario <ISender>("senders", name, defaultTypes, valueConverters, resolver, reloadOnConfigChange));
        }
        private static void AddLoggerFromLoggerFactory(this IServiceCollection services, string rockLibLoggerName,
                                                       DefaultTypes defaultTypes, ValueConverters valueConverters)
        {
            services.AddSingleton <ILogProcessor, BackgroundLogProcessor>();

            services.AddTransient(serviceProvider =>
            {
                var resolver = new Resolver(t => serviceProvider.GetService(t));
                return(LoggerFactory.Create(rockLibLoggerName, defaultTypes, valueConverters, resolver, reloadOnConfigChange: false));
            });
        }
Example #18
0
        public void TryGetByTargetTypeReturnsTrueWhenThereIsAMatch()
        {
            var defaultTypes = new DefaultTypes()
                               .Add(typeof(IBar), typeof(Bar))
                               .Add(typeof(IBaz), typeof(Baz));

            Assert.True(defaultTypes.TryGet(typeof(IBar), out Type defaultFooBar));
            Assert.Equal(typeof(Bar), defaultFooBar);

            Assert.True(defaultTypes.TryGet(typeof(IBaz), out Type defaultFooBaz));
            Assert.Equal(typeof(Baz), defaultFooBaz);
        }
Example #19
0
        public void TryGetByDeclaringTypeAndMemberNameReturnsTrueWhenThereIsAMatch()
        {
            var defaultTypes = new DefaultTypes()
                               .Add(typeof(Foo), "bar", typeof(Bar))
                               .Add(typeof(Foo), "baz", typeof(Baz));

            Assert.True(defaultTypes.TryGet(typeof(Foo), "bar", out Type defaultFooBar));
            Assert.Equal(typeof(Bar), defaultFooBar);

            Assert.True(defaultTypes.TryGet(typeof(Foo), "baz", out Type defaultFooBaz));
            Assert.Equal(typeof(Baz), defaultFooBaz);
        }
Example #20
0
        public void GivenDefaultTypeIsNotAssignableToMemberType_ThrowsArgumentException()
        {
            var defaultTypes = new DefaultTypes();

            var actual = Assert.Throws <ArgumentException>(() => defaultTypes.Add(typeof(Foo), "bar", typeof(Qux)));

#if DEBUG
            var expected = Exceptions.DefaultTypeNotAssignableToMembers(typeof(Foo), "bar", typeof(Qux), new List <Member> {
                new Member("Bar", typeof(IBar), MemberType.Property)
            });
            Assert.Equal(expected.Message, actual.Message);
#endif
        }
Example #21
0
        public void TypeSpecifiedByDefaultType()
        {
            var config = GetNonTypeSpecifiedConfig();

            var garplies  = 0;
            var reloading = 0;
            var reloaded  = 0;

            var defaultTypes = new DefaultTypes().Add(typeof(IFoo), typeof(Foo));

            IFoo foo = new ProxyFoo(config.GetSection("foo"), defaultTypes, new ValueConverters(), null, null);

            ConfigReloadingProxy <IFoo> proxyFoo = (ConfigReloadingProxy <IFoo>)foo;
            Foo initialFoo = (Foo)proxyFoo.Object;

            foo.Qux     = "xyz";
            foo.Garply += (s, e) => { garplies++; };

            proxyFoo.Reloading += (s, e) => { reloading++; };
            proxyFoo.Reloaded  += (s, e) => { reloaded++; };

            initialFoo.OnGarply();

            Assert.Equal(123, foo.Bar);
            Assert.Equal("xyz", foo.Qux);
            Assert.Equal(1, garplies);

            Assert.False(initialFoo.IsDisposed);
            Assert.Equal(0, reloading);
            Assert.Equal(0, reloaded);

            ChangeNonTypeSpecifiedConfig(config);

            Assert.True(initialFoo.IsDisposed);
            Assert.Equal(1, reloading);
            Assert.Equal(1, reloaded);

            Foo changedFoo = (Foo)proxyFoo.Object;

            changedFoo.OnGarply();

            Assert.Equal(456, foo.Bar);
            Assert.Equal("xyz", foo.Qux);
            Assert.Equal(2, garplies);

            Assert.False(changedFoo.IsDisposed);

            ((IDisposable)foo).Dispose();

            Assert.True(changedFoo.IsDisposed);
        }
    private AudioClip GetSound(string soundName, DefaultTypes type = DefaultTypes.Any)
    {
        List <SoundEffect> searchList = new List <SoundEffect>();

        GetListByType(type, out searchList);

        foreach (SoundEffect sfx in searchList)
        {
            if (sfx.Name.ToLower().Trim().Equals(soundName.ToLower().Trim()))
            {
                return(sfx.File);
            }
        }

        Debug.LogError("Sound not found - " + soundName);
        return(null);
    }
    private AudioClip GetRandomSound(DefaultTypes type)
    {
        List <SoundEffect> searchList = new List <SoundEffect>();

        GetListByType(type, out searchList);

        if (searchList.Count > 0)
        {
            System.Random rng    = new System.Random();
            int           random = rng.Next(0, searchList.Count);

            return(searchList[random].File);
        }

        Debug.LogError("Random sound not found for type - " + type);
        return(null);
    }
Example #24
0
        /// <summary>
        /// Gets a cached instance of <see cref="ILogger"/> with a name matching the <paramref name="name"/>
        /// parameter that is backed by the value of the <paramref name="configuration"/> parameter.
        /// </summary>
        /// <param name="configuration">
        /// An instance of <see cref="IConfiguration"/> that defines the loggers that can be retrieved. The
        /// configuration can define a single logger object or a list of logger objects.
        /// </param>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <param name="defaultTypes">
        /// An object that defines the default types to be used when a type is not explicitly specified by a
        /// configuration section.
        /// </param>
        /// <param name="valueConverters">
        /// An object that defines custom converter functions that are used to convert string configuration
        /// values to a target type.
        /// </param>
        /// <param name="resolver">
        /// An object that can retrieve constructor parameter values that are not found in configuration. This
        /// object is an adapter for dependency injection containers, such as Ninject, Unity, Autofac, or
        /// StructureMap. Consider using the <see cref="Resolver"/> class for this parameter, as it supports
        /// most depenedency injection containers.
        /// </param>
        /// <param name="reloadOnConfigChange">
        /// Whether to create an instance of <see cref="ILogger"/> that automatically reloads itself when its
        /// configuration changes. Default is true.
        /// </param>
        /// <returns>A logger with a matching name.</returns>
        /// <exception cref="KeyNotFoundException">
        /// If a logger with a name specified by the <paramref name="name"/> parameter is not defined in
        /// the value of the <paramref name="configuration"/> parameter.
        /// </exception>
        public static ILogger GetCachedLogger(this IConfiguration configuration, string name = Logger.DefaultName,
                                              DefaultTypes defaultTypes = null, ValueConverters valueConverters = null,
                                              IResolver resolver        = null, bool reloadOnConfigChange = true)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            var configCache = _cache.GetValue(configuration, c => new ConcurrentDictionary <string, ILogger>());

            return(configCache.GetOrAdd(name, n => configuration.CreateLogger(n, defaultTypes, valueConverters, resolver, reloadOnConfigChange)));
        }
Example #25
0
        public void DefaultTypesFunctionsProperly()
        {
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "RockLib.Logging:Name", "foo" }
            }).Build();

            var defaultTypes = new DefaultTypes
            {
                { typeof(ILogger), typeof(TestLogger) }
            };

            var section = config.GetSection("RockLib.Logging");

            var logger = section.CreateLogger("foo", defaultTypes: defaultTypes, reloadOnConfigChange: false);

            logger.Should().BeOfType <TestLogger>();
        }
        public virtual ActionResult Add()
        {
            var model = new InstitutionalAgreementConfigurationForm();

            // find the configuration for the currently signed in user's default affiliation
            var configuration = _queryProcessor.Execute(new GetMyInstitutionalAgreementConfigurationQuery(User));

            // if configuration exists, cannot add
            if (configuration != null)
            {
                model = Mapper.Map <InstitutionalAgreementConfigurationForm>(configuration);
            }
            else
            {
                // when configuration does not exist, get the default affiliation for the currently signed in user
                var person = GetConfigurationSupervisor();
                if (person == null)
                {
                    return(HttpNotFound());
                }

                // allow the viewmodel to disclose the establishment official name
                model.ForEstablishmentOfficialName = person.DefaultAffiliation.Establishment.OfficialName;

                // add default options
                DefaultTypes.ForEach(option => model.AllowedTypeValues.Add(
                                         new InstitutionalAgreementTypeValueForm {
                    IsAdded = true, Text = option
                }));
                DefaultStatuses.ForEach(option => model.AllowedStatusValues.Add(
                                            new InstitutionalAgreementStatusValueForm {
                    IsAdded = true, Text = option
                }));
                DefaultContactTypes.ForEach(option => model.AllowedContactTypeValues.Add(
                                                new InstitutionalAgreementContactTypeValueForm {
                    IsAdded = true, Text = option
                }));

                // add a default empty allowed options
                AddEmptyAllowedOptions(model);
            }
            return(View(model));
        }
Example #27
0
        public void CanAddByTargetType()
        {
            // Register a default type by target type when you want all properties of the
            // target type to have the same default type.

            // Call the Add method for each default type that needs to be registered.
            var first = new DefaultTypes();

            first.Add(typeof(IBar), typeof(Bar));
            first.Add(typeof(IBaz), typeof(Baz));

            // The Add method returns 'this', so you can chain them together:
            var second = new DefaultTypes()
                         .Add(typeof(IBar), typeof(Bar))
                         .Add(typeof(IBaz), typeof(Baz));

            // List initialization syntax works also.
            var third = new DefaultTypes
            {
                { typeof(IBar), typeof(Bar) },
                { typeof(IBaz), typeof(Baz) }
            };

            // All three instances represent the same thing. Verify that their
            // contents are the same.

            // DefaultTypes implements IEnumerable<KeyValuePair<string, Type>>
            var firstList  = first.ToList();
            var secondList = second.ToList();
            var thirdList  = third.ToList();

            Assert.Equal(firstList.Count, secondList.Count);
            Assert.Equal(secondList.Count, thirdList.Count);

            for (int i = 0; i < firstList.Count; i++)
            {
                Assert.Equal(firstList[i].Key, secondList[i].Key);
                Assert.Equal(firstList[i].Value, secondList[i].Value);

                Assert.Equal(secondList[i].Key, thirdList[i].Key);
                Assert.Equal(secondList[i].Value, thirdList[i].Value);
            }
        }
        public void DefaultTypesFunctionsProperly()
        {
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "RockLib.Messaging:Senders:Name", "foo" },
                { "RockLib.Messaging:Receivers:Name", "foo" }
            }).Build();

            var defaultTypes = new DefaultTypes
            {
                { typeof(ISender), typeof(TestSender) },
                { typeof(IReceiver), typeof(TestReceiver) }
            };

            var messagingSection = config.GetSection("RockLib.Messaging");

            using var sender   = messagingSection.CreateSender("foo", defaultTypes: defaultTypes, reloadOnConfigChange: false);
            using var receiver = messagingSection.CreateReceiver("foo", defaultTypes: defaultTypes, reloadOnConfigChange: false);

            sender.Should().BeOfType <TestSender>();
            receiver.Should().BeOfType <TestReceiver>();
        }
        public void MissingConstructorParametersAreSuppliedByTheResolver()
        {
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string> {
                { "waldo", "123" }
            })
                         .Build();

            var garply = new Garply();

            var defaultTypes = new DefaultTypes().Add(typeof(IGrault), typeof(Grault));
            var resolver     = new Resolver(t => garply, t => t == typeof(IGarply));

            var grault = config.CreateReloadingProxy <IGrault>(defaultTypes, resolver: resolver);

            Assert.Same(garply, grault.Garply);
            Assert.Equal(123, grault.Waldo);

            ChangeConfig(config, new KeyValuePair <string, string>("waldo", "456"));

            Assert.Same(garply, grault.Garply);
            Assert.Equal(456, grault.Waldo);
        }
Example #30
0
        public void GivenNullDefaultType2_ThrowsArgumentNullException()
        {
            var defaultTypes = new DefaultTypes();

            Assert.Throws <ArgumentNullException>(() => defaultTypes.Add(typeof(IBar), null));
        }