Example #1
0
        private Session CreateSession(
            Action <ScopedObjectRegistry> sessionObjectsConfigurator = null,
            params Type[] commandTypes)
        {
            var parser              = new Parser();
            var nameValidator       = new NameValidator();
            var descriptorGenerator = new CommandAttributeInspector();
            var registry            = new CommandRegistry(nameValidator, descriptorGenerator);

            foreach (var commandType in commandTypes)
            {
                registry.Register(commandType);
            }

            var services      = new CommandServices();
            var scopedObjects = new ScopedObjectRegistry();

            scopedObjects.Register <VariableCollection>();
            sessionObjectsConfigurator?.Invoke(scopedObjects);

            var factory = new CommandFactory(registry, services, scopedObjects);

            var variables = scopedObjects.Resolve(typeof(VariableCollection)) as VariableCollection;
            var replacer  = new VariableReplacer();
            var binder    = new CommandParameterBinder(registry, replacer, variables);

            return(new Session(parser, factory, binder));
        }
Example #2
0
        private CommandFactory CreateCommandFactory(
            Action <CommandRegistry> commandRegistryConfigurator           = null,
            Action <CommandServices> commandServicesConfigurator           = null,
            Action <ScopedObjectRegistry> scopedObjectRegistryConfigurator = null)
        {
            var nameValidator       = new NameValidator();
            var descriptorGenerator = new CommandAttributeInspector();
            var registry            = new CommandRegistry(nameValidator, descriptorGenerator);

            if (commandRegistryConfigurator != null)
            {
                commandRegistryConfigurator.Invoke(registry);
            }

            var services = new CommandServices();

            if (commandServicesConfigurator != null)
            {
                commandServicesConfigurator.Invoke(services);
            }

            var sessionObjects = new ScopedObjectRegistry();

            sessionObjects.Register <VariableCollection>();

            if (scopedObjectRegistryConfigurator != null)
            {
                scopedObjectRegistryConfigurator.Invoke(sessionObjects);
            }

            return(new CommandFactory(registry, services, sessionObjects));
        }
    public override IModable copyDeep()
    {
        var result = new CommandServices();

        result.ServicePointID = Modable.copyDeep(ServicePointID);

        return(result);
    }
 public void mod(CommandServices modable)
 {
     if (modable == null)
     {
         return;
     }
     mod(this, modable);
 }
Example #5
0
        public void Register_ObjectInstanceProvided_DoesNotThrow()
        {
            // arrange
            var sut     = new CommandServices();
            var service = new SampleService();

            // act
            sut.Register(service);
        }
Example #6
0
        public void Register_BaseInterfaceTypeUsed_DoesNotThrow()
        {
            // arrange
            var sut     = new CommandServices();
            var service = new SampleService();

            // act
            sut.Register <ISuperSampleService>(service);
        }
Example #7
0
        public void Register_ServiceAlreadyRegisteredUnderDifferentType_DoesNotThrow()
        {
            // arrange
            var sut     = new CommandServices();
            var service = new SampleService();

            sut.Register <ISuperSampleService>(service);

            // act
            sut.Register <ISampleService>(service);
        }
Example #8
0
        public void ResolveGeneric_ServiceTypeNotRegistered_ReturnsNull()
        {
            // arrange
            var sut = new CommandServices();

            // act
            var service = sut.Resolve <ISampleService>();

            // assert
            Assert.Null(service);
        }
Example #9
0
        public void Register_ServiceIsNull_ThrowsException()
        {
            // arrange
            var    sut       = new CommandServices();
            Action sutAction = () => sut.Register <object>(null);

            // act, assert
            var ex = Assert.Throws <ArgumentNullException>(sutAction);

            Assert.Equal("service", ex.ParamName);
        }
Example #10
0
        public void Ctor_SessionObjectsNull_ThrowsException()
        {
            // arrange
            var    registry  = Substitute.For <ICommandRegistry>();
            var    services  = new CommandServices();
            Action sutAction = () => new CommandFactory(registry, services, null);

            // act, assert
            var ex = Assert.Throws <ArgumentNullException>(sutAction);

            Assert.Equal("sessionObjects", ex.ParamName);
        }
Example #11
0
    public override void mod(IModable modable)
    {
        CommandServices modCommand = modable as CommandServices;

        if (modCommand == null)
        {
            Debug.LogError("Type mismatch");
            return;
        }

        mod(modCommand);
    }
Example #12
0
        public void Ctor_CommandRegistryNull_ThrowsException()
        {
            // arrange
            var    services      = new CommandServices();
            var    scopedObjects = new ScopedObjectRegistry();
            Action sutAction     = () => new CommandFactory(null, services, scopedObjects);

            // act, assert
            var ex = Assert.Throws <ArgumentNullException>(sutAction);

            Assert.Equal("commandRegistry", ex.ParamName);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uniqueKey"></param>
        protected virtual T UniqueKeyCommand <T>(UniqueKeyInfo uniqueKey) where T : class, IUniqueKeyCommand
        {
            var service = CommandServices.GetCommand <T>();

            if (service == null)
            {
                return(null);
            }

            service.SetUniqueKey(uniqueKey);
            Commands.Add(service);
            return(service);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="column"></param>
        protected virtual T ColumnCommand <T>(ColumnInfo column) where T : class, IColumnCommand
        {
            var service = CommandServices.GetCommand <T>();

            if (service == null)
            {
                return(null);
            }

            service.SetColumn(column);
            Commands.Add(service);
            return(service);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="foreignKey"></param>
        protected virtual T ForeignKeyCommand <T>(ForeignKeyInfo foreignKey) where T : class, IForeignKeyCommand
        {
            var service = CommandServices.GetCommand <T>();

            if (service == null)
            {
                return(null);
            }

            service.SetForeignKey(foreignKey);
            Commands.Add(service);
            return(service);
        }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="primaryKey"></param>
        protected virtual T PrimaryKeyCommand <T>(PrimaryKeyInfo primaryKey) where T : class, IPrimaryKeyCommand
        {
            var service = CommandServices.GetCommand <T>();

            if (service == null)
            {
                return(null);
            }

            service.SetPrimaryKey(primaryKey);
            Commands.Add(service);
            return(service);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        protected virtual T TableCommand <T>(TableInfo table) where T : class, ITableCommand
        {
            var service = CommandServices.GetCommand <T>();

            if (service == null)
            {
                return(null);
            }

            service.SetTable(table);
            Commands.Add(service);
            return(service);
        }
Example #18
0
        public void ResolveGeneric_ServiceIsRegistered_ReturnsService()
        {
            // arrange
            var sut     = new CommandServices();
            var service = new SampleService();

            sut.Register(service);

            // act
            var resolvedService = sut.Resolve <SampleService>();

            // assert
            Assert.Same(service, resolvedService);
        }
Example #19
0
        public void Resolve_UseInterfaceType_ReturnsService()
        {
            // arrange
            var sut     = new CommandServices();
            var service = new SampleService();

            sut.Register <ISampleService>(service);

            // act
            var resolvedService = sut.Resolve(typeof(ISampleService));

            // assert
            Assert.Same(service, resolvedService);
        }
Example #20
0
        public void Register_TypeAlreadyUsed_ThrowsException()
        {
            // arrange
            var sut      = new CommandServices();
            var service1 = new SampleService();
            var service2 = new SampleService();

            sut.Register(service1);
            Action sutAction = () => sut.Register(service2);

            // act, assert
            var ex = Assert.Throws <InvalidOperationException>(sutAction);

            Assert.Contains("The service type Chel.UnitTests.Services.SampleService has already been registered", ex.Message);
        }
        private (CommandContext, IArgumentParser) GetContextAndArgumentParser(Action <MariCommandsOptions> options = null)
        {
            var services = new ServiceCollection();

            services.AddOptions <MariCommandsOptions>();

            if (options.HasContent())
            {
                services.Configure <MariCommandsOptions>(options);
            }

            services.AddTransient <ITypeParserProvider, TypeParserProvider>();

            services.AddAllDefaultTypeParsers(true);

            services.AddTransient <IArgumentParser, ArgumentParser>();

            var provider = services.BuildServiceProvider(true);

            var context = new CommandContext();

            context.ServiceScopeFactory = provider.GetRequiredService <IServiceScopeFactory>();
            return(context, context.CommandServices.GetRequiredService <IArgumentParser>());
        }
Example #22
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(op =>
            {
                op.Filters.Add <ValidationFilter>();
                op.RespectBrowserAcceptHeader = true;
            })
            .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
            .AddXmlSerializerFormatters();

            services.AddTransient <TokenService, TokenService>();
            services.AddTransient <TaxAndShippingCalculationService, TaxAndShippingCalculationService>();

            services.AddSwaggerGen(x =>
            {
                x.ExampleFilters();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                x.IncludeXmlComments(xmlPath);

                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey,
                    In   = ParameterLocation.Header,
                });
                x.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Jwt:Audience"],
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });


            services.AddSwaggerExamplesFromAssemblyOf <Startup>();

            services.AddMvc(op =>
            {
                op.Filters.Add <ApiExceptionAttribute>();
            })
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddAutoMapper(typeof(Startup));

            services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            var container = new ContainerBuilder();

            CommandServices.RegisterServices(container, services);
            QueryServices.RegisterServices(container, services);

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
Example #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            DataAccessLayerBase.Configuration = Configuration;

            services.AddHttpContextAccessor();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.Configure <TokenSettings>(Configuration.GetSection("tokenSettings"));

            var token  = Configuration.GetSection("tokenSettings").Get <TokenSettings>();
            var secret = Encoding.ASCII.GetBytes(token.Secret);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                    ValidIssuer      = token.Issuer,
                    ValidAudience    = token.Audience,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });

            services.AddMvc(options =>
            {
                options.Filters.Add <ApiExceptionFilter>();
            }).AddJsonOptions(x =>
            {
                x.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                x.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                x.SerializerSettings.Formatting            = Formatting.Indented;
                x.SerializerSettings.ContractResolver      = new DefaultContractResolver();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors(c => c.AddPolicy("AllowAllHeaders", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(nameof(v1), new Info()
                {
                    Title       = $"Roulette Api {nameof(v1)}",
                    Description = "Service for managing virtual roulette game",
                    Version     = nameof(v1)
                });

                var currentDir = new DirectoryInfo(AppContext.BaseDirectory);
                foreach (var xmlCommentFile in currentDir.EnumerateFiles("Roulette.*.xml"))
                {
                    c.IncludeXmlComments(xmlCommentFile.FullName);
                }
                c.DescribeAllEnumsAsStrings();

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });

            services.AddTransient <IDBProvider, DBProvider>();
            services.AddTransient <ISignInManager, SignInManager>();

            var container = new ContainerBuilder();

            CommandServices.RegisterServices(container, services);
            QueryServices.RegisterServices(container, services);

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
Example #24
0
 private void mod(CommandServices original, CommandServices mod)
 {
     ServicePointID = Modable.mod(original.ServicePointID, mod.ServicePointID);
 }
Example #25
0
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        Command result;

        JObject jo = JObject.Load(reader);

        if (!Enum.TryParse((string)jo["Type"], out Command.Type commandType))
        {
            Debug.LogError($"CommandType {jo["Type"]} not recognized in {jo}");
            return(new CommandNone());
        }

        switch (commandType)
        {
        case (Command.Type.Break):
            result = new CommandBreak();
            break;

        case (Command.Type.Call):
            result = new CommandCall();
            break;

        case (Command.Type.Conditional):
            result = new CommandConditional();
            break;

        case (Command.Type.Consume):
            result = new CommandConsume();
            break;

        case (Command.Type.Continue):
            result = new CommandContinue();
            break;

        case (Command.Type.Debug):
            result = new CommandDebug();
            break;

        case (Command.Type.Dialog):
            result = new CommandDialog();
            break;

        case (Command.Type.Dialogue):
            result = new CommandDialogue();
            break;

        case (Command.Type.Event):
            result = new CommandEvent();
            break;

        case (Command.Type.EventEnd):
            result = new CommandEventEnd();
            break;

        case (Command.Type.Flush):
            result = new CommandFlush();
            break;

        case (Command.Type.GotoLocation):
            result = new CommandGotoLocation();
            break;

        case (Command.Type.Interrupt):
            result = new CommandInterrupt();
            break;

        case (Command.Type.ItemAdd):
            result = new CommandItemAdd();
            break;

        case (Command.Type.ItemRemove):
            result = new CommandItemRemove();
            break;

        case (Command.Type.NoteAdd):
            result = new CommandNoteAdd();
            break;

        case (Command.Type.NoteRemove):
            result = new CommandNoteRemove();
            break;

        case (Command.Type.Outfit):
            result = new CommandOutfit();
            break;

        case (Command.Type.OutfitManage):
            result = new CommandOutfitManage();
            break;

        case (Command.Type.Pause):
            result = new CommandPause();
            break;

        case (Command.Type.Services):
            result = new CommandServices();
            break;

        case (Command.Type.Set):
            result = new CommandSet();
            break;

        case (Command.Type.Shop):
            result = new CommandShop();
            break;

        case (Command.Type.Sleep):
            result = new CommandSleep();
            break;

        case (Command.Type.TimePass):
            result = new CommandTimePass();
            break;

        case (Command.Type.None):
        default:
            result = new CommandNone();
            break;
        }

        serializer.Populate(jo.CreateReader(), result);

        return(result);

        /*if (reader.TokenType == JsonToken.Null)
         *  return new CText();
         *
         * if (reader.TokenType == JsonToken.StartObject)
         * {
         *  //https://stackoverflow.com/questions/35586987/json-net-custom-serialization-with-jsonconverter-how-to-get-the-default-beha
         *  existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
         *  serializer.Populate(reader, existingValue);
         *  return existingValue;
         * }
         *
         * if (reader.TokenType == JsonToken.String)
         *  return new CText((string)reader.Value);
         *
         */
        //throw new JsonSerializationException();
    }