private static void StartService()
        {
            IContainer container = ContainerManager.Instance;

            HostFactory.Run(x =>
            {
                x.UseAutofacContainer(container);

                x.EnableServiceRecovery(rc =>
                {
                    rc.RestartService(1);
                    rc.OnCrashOnly();
                });

                x.Service <NancySelfHost>(s =>
                {
                    s.ConstructUsingAutofacContainer();
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.StartAutomatically();
                x.EnableShutdown();
                x.RunAsLocalService();

                x.SetDescription("NancyTopshelfBoilerplate Description");
                x.SetDisplayName("NancyTopshelfBoilerplate Display Name");
                x.SetServiceName("NancyTopshelfBoilerplate Service Name");

                x.UseNLog();
            });
        }
Ejemplo n.º 2
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();

            providerConfiguration.ModulesFolder = string.Empty;

            var bootstrapper = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);

            services.AddMvc().AddRazorOptions(options =>
            {
                options.ViewLocationFormats.Clear();
                options.ViewLocationFormats.Add("/Presentation/{0}.cshtml");
            });
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityServerConfiguration.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfiguration.GetApiResources())
            .AddInMemoryClients(IdentityServerConfiguration.GetClients(Configuration.GetSection("Clients").Get <List <string> >()));

            services.AddTransient <IResourceOwnerPasswordValidator, UserStore>()
            .AddTransient <IProfileService, UserStore>();

            builder.RegisterInstance <IConfiguration>(Configuration);
            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Ejemplo n.º 3
0
        //private static void ConfigureEnterpriseLibraries()
        //{
        //    using (var config = new SystemConfigurationSource())
        //    {
        //        var settings = RetryPolicyConfigurationSettings.GetRetryPolicySettings(config);

        //        // Initialize the RetryPolicyFactory with a RetryManager built from the
        //        // settings in the configuration file.
        //        RetryPolicyFactory.SetRetryManager(settings.BuildRetryManager());

        //    }
        //}

        #endregion

        #region Site

        private static void ConfigureSite(HttpConfiguration httpConfiguration, Autofac.IContainer container)
        {
            ConfigureSiteDependencyResolver(httpConfiguration, container);

            AreaRegistration.RegisterAllAreas();
            ConfigureSiteGlobalFilters(GlobalFilters.Filters);
            ConfigureSiteRouting();
        }
        public ScopeTrackerTests()
        {
            var cb = new ContainerBuilder();

            cb.RegisterType <SampleJob>();
            cb.RegisterType <DisposableDependency>().InstancePerLifetimeScope();

            _container = cb.Build();

            _lifetimeScope = _container.Resolve <ILifetimeScope>();
            _jobFactory    = new AutofacJobFactory(_lifetimeScope, QuartzAutofacFactoryModule.LifetimeScopeName);
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            IConfigurationSection configSection = Configuration.GetSection("ServiceConfig");

            ServiceConfigInfo.Init(configSection["consul"], configSection["configKey"], configSection["ip"], Convert.ToInt32(configSection["httpPort"]));

            services.AddGalaxyAuth("ShopInfoManage");
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder
                    .WithOrigins("*")
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });

            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("any"));
            });

            new AutoMapperInit().Init();

            DBConnectionProvider.Config(ServiceConfigInfo.Single.DBConfig.Server,
                                        ServiceConfigInfo.Single.DBConfig.Port,
                                        ServiceConfigInfo.Single.DBConfig.DBName,
                                        ServiceConfigInfo.Single.DBConfig.User,
                                        ServiceConfigInfo.Single.DBConfig.Password);
            CSRedisInitHelper.Init(ServiceConfigInfo.Single.RedisConfig.Server, System.Convert.ToInt32(ServiceConfigInfo.Single.RedisConfig.Port));

            //注册Swagger生成器,定义一个和多个Swagger 文档
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "ShopInfoServiceAPI", Version = "v1"
                });
                c.SwaggerDoc("v2", new Info {
                    Title = "ShopInfoServiceAPI_2", Version = "v2"
                });
                c.IncludeXmlComments(AppDomain.CurrentDomain.BaseDirectory + "/Galaxy.Taurus.ShopInfoAPI.xml");
            });

            DependencyRegister dependencyRegister = new DependencyRegister();

            ApplicationContainer = dependencyRegister.RegisterWeb(services);
            return(new AutofacServiceProvider(ApplicationContainer));//第三方IOC接管 core内置DI容器
        }
Ejemplo n.º 6
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();
            var bootstrapper          = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);


            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Configure Auth
        /// </summary>
        /// <param name="app">App builder</param>
        /// <param name="container">DI container</param>
        public void ConfigureAuth(IAppBuilder app, Autofac.IContainer container)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var validUpns = ConfigurationManager.AppSettings["ValidUpns"]
                            ?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                            ?.Select(s => s.Trim())
                            ?? new string[0];

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions("AppLogin")
            {
                ClientId              = clientId,
                Authority             = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = (context) =>
                    {
                        var upnClaim = context?.AuthenticationTicket?.Identity?.Claims?
                                       .FirstOrDefault(c => c.Type == ClaimTypes.Upn);
                        var upn = upnClaim?.Value;

                        if (upn == null ||
                            !validUpns.Contains(upn, StringComparer.OrdinalIgnoreCase))
                        {
                            context.OwinContext.Response.Redirect("/Account/InvalidUser");
                            context.HandleResponse();
                        }

                        return(Task.CompletedTask);
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            context.ProtocolMessage.Prompt = OpenIdConnectPrompt.Login;
                        }

                        return(Task.CompletedTask);
                    },
                },
            });
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Upn;
        }
Ejemplo n.º 8
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();
            var bootstrapper          = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);

            services.AddMvc();
            services.AddHangfire(x => x.UsePostgreSqlStorage(providerConfiguration.SqlStore.ConnectionString));

            builder.RegisterInstance <IConfiguration>(Configuration);
            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);

            return(new AutofacServiceProvider(ApplicationContainer));
        }
Ejemplo n.º 9
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var builder = new AutofacContainerBuilder();
            var providerConfiguration = Configuration.GetSection("Vedaantees").Get <ProviderConfiguration>();
            var bootstrapper          = new ProviderBootstrapper(builder, providerConfiguration);

            bootstrapper.Load(_env);
            LoadApiClientRegistrations(builder, bootstrapper.GetAssemblies);

            services.AddMvcCore(config => {
                //Enable this for security.
                //var policy = new AuthorizationPolicyBuilder()
                //                .RequireAuthenticatedUser()
                //                .Build();
                //config.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization()
            .AddJsonFormatters();

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = providerConfiguration.SingleSignOnServer;
                options.RequireHttpsMetadata = false;
                options.ApiName   = "axelius-api";
                options.ApiSecret = "guess-thi$-not-di55icult-resource";
            });

            services.AddCors(options =>
            {
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins(string.Join(',', Configuration.GetSection("Clients").Get <List <string> >()))
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            builder.RegisterInstance(Configuration);
            builder.Builder.Populate(services);
            ApplicationContainer = builder.Build();
            bootstrapper.InitializeFramework(ApplicationContainer);
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Ejemplo n.º 10
0
        public App()
        {
            InitializeComponent();
            //To initialize Containers..
            AppSetup appSetup = new AppSetup();

            _container = appSetup.CreateContainer();

            if (Helpers.Settings.GeneralAccessToken == string.Empty)
            {
                MainPage = new MonicaLoanApp.Views.Login.LoginPage(null);
            }
            else
            {
                App.masterDetailPage.Master = new MenuPage();
                App.masterDetailPage.Detail = new NavigationPage(new YourLoanBalancePage());
                App.Current.MainPage        = App.masterDetailPage;
            }
        }
Ejemplo n.º 11
0
        private static void Configure(HttpConfiguration httpConfiguration, Autofac.IContainer container)
        {
            try
            {
                ConfigureLogging();
                ConfigureMapping();
                //ConfigureEnterpriseLibraries();

                ConfigureWebApi(httpConfiguration, container);
                ConfigureSite(httpConfiguration, container);
            }
            catch (Exception exception)
            {
                // Attempt to log it
                var log = LogManager.GetLogger(Common.Contract.Constants.Global.DefaultLogName);
                log.Error(exception);

                throw new LoggedException("Error in DistyConfiguration startup.", exception);
            }
        }
Ejemplo n.º 12
0
        public MainViewModel([NotNull] IContainer container)
        {
            if (container == null) throw new ArgumentNullException("container");

            _container = container;

            LastSiusMessage = "Welcome!";
            LogCollection = new ObservableCollection<string>();

            Host = "localhost";
            Port = 4000;
            Server = "localhost";
            User = "******";
            Password = "";
            Database = "shootingrange";

            StartProcessingOnConnect = false;
            ConnectSiusCommand = new RelayCommand<object>(ExecuteConnectSiusCommand, CanExecuteConnectSiusCommand);
            StartProcessingCommand = new RelayCommand<object>(ExecuteStartProcessingCommand,
                CanExecuteStartProcessingCommand);
        }
Ejemplo n.º 13
0
        public App()
        {
            InitializeComponent();
            //To initialize Containers..
            AppSetup appSetup = new AppSetup();

            _container = appSetup.CreateContainer();

            if (!string.IsNullOrEmpty(Helpers.LocalStorage.GeneralProfileToken))
            {
                MainPage = new Views.Currencies.CurrencyPage();
            }
            else
            {
                MainPage = new Views.Introduction.IntroductionPage();
            }

            #region
            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("OTMyNDlAMzEzNzJlMzEyZTMwWVAxejJTOFhSaUswQm1MUGJoWC93K3pyRWpkdkNVM0oyemhkK1ZzY0pNbz0=");
            #endregion
        }
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        DispatcherUnhandledException += App_DispatcherUnhandledException;
        AppDomain.CurrentDomain.UnhandledException                   += CurrentDomain_UnhandledException;
        Application.Current.DispatcherUnhandledException             += Current_DispatcherUnhandledException;
        System.Threading.Tasks.TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        IEnumerable <IEndPointConfiguration> endPoints = ReadEndPointsFromDisk();

        Container = App.CreateContainer(endPoints, null, null);
        IDatabaseUtilities databaseUtilities = Container.Resolve <IDatabaseUtilities>();

        // Create all databases or apply migrations
        foreach (IEndPointConfiguration ep in endPoints.Where(x => x.EndPointType == EndPointType.DBMS))
        {
            Task.Run(() => databaseUtilities.CreateOrUpdateDatabase(ep)).Wait();
        }

        MainWindow mainWindow = Container.Resolve <MainWindow>();

        this.MainWindow = mainWindow;
        mainWindow.Show();
    }
Ejemplo n.º 15
0
        public MainViewModel([NotNull] IContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            _container = container;

            LastSiusMessage = "Welcome!";
            LogCollection   = new ObservableCollection <string>();

            Host     = "localhost";
            Port     = 4000;
            Server   = "localhost";
            User     = "******";
            Password = "";
            Database = "shootingrange";

            StartProcessingOnConnect = false;
            ConnectSiusCommand       = new RelayCommand <object>(ExecuteConnectSiusCommand, CanExecuteConnectSiusCommand);
            StartProcessingCommand   = new RelayCommand <object>(ExecuteStartProcessingCommand,
                                                                 CanExecuteStartProcessingCommand);
        }
Ejemplo n.º 16
0
 private static void ConfigureWebApiDependencyResolver(HttpConfiguration httpConfiguration, Autofac.IContainer container)
 {
     httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
 }
Ejemplo n.º 17
0
 public AutofacServiceProvider(Autofac.IContainer container)
 {
 }
Ejemplo n.º 18
0
		static Setup()
		{
			Container = SetupContainer();
		}
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the MachineLearningMicroService.MLMicroService class
 /// </summary>
 /// <param name="container"> The container </param>
 /// <param name="owningNode"> The owning node</param>
 public MLMicroService(Autofac.IContainer container, string owningNode)
 {
     _container    = container;
     _owningNodeId = owningNode;
 }
Ejemplo n.º 20
0
 public frmSettings(AContainer container)
 {
     InitializeComponent();
     _container = container;
 }
Ejemplo n.º 21
0
 private static void ConfigureSiteDependencyResolver(HttpConfiguration httpConfiguration, Autofac.IContainer container)
 {
     DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns a path that contains the generated markdown files
        /// </summary>
        /// <returns></returns>
        public string GenerateMarkdownFiles(AContainer container, string basePath)
        {
            //create directory if required
            var docsFolderName = "docs";
            var docsPath       = Path.Combine(basePath, docsFolderName);

            if (!Directory.Exists(docsPath))
            {
                Directory.CreateDirectory(docsPath);
            }

            var commandClasses = TypeMethods.GenerateCommandTypes(container);

            var           highLevelCommandInfo = new List <CommandMetaData>();
            StringBuilder stringBuilder;
            string        fullFileName;

            //loop each command
            foreach (var commandClass in commandClasses)
            {
                //instantiate and pull properties from command class
                ScriptCommand instantiatedCommand = (ScriptCommand)Activator.CreateInstance(commandClass);
                var           groupName           = GetClassValue(commandClass, typeof(CategoryAttribute));
                var           classDescription    = GetClassValue(commandClass, typeof(DescriptionAttribute));
                var           commandName         = instantiatedCommand.SelectionName;

                stringBuilder = new StringBuilder();

                //create string builder to build markdown document and append data
                stringBuilder.AppendLine("<!--TITLE: " + commandName + " Command -->");
                stringBuilder.AppendLine("<!-- SUBTITLE: a command in the " + groupName + " group. -->");
                stringBuilder.AppendLine("[Go To Automation Commands Overview](/automation-commands)");

                stringBuilder.AppendLine(Environment.NewLine);
                stringBuilder.AppendLine("# " + commandName + " Command");
                stringBuilder.AppendLine(Environment.NewLine);

                //append more
                stringBuilder.AppendLine("## What does this command do?");
                stringBuilder.AppendLine(classDescription);
                stringBuilder.AppendLine(Environment.NewLine);

                //build parameter table based on required user inputs
                stringBuilder.AppendLine("## Command Parameters");
                stringBuilder.AppendLine("| Parameter Question   	| What to input  	|  Sample Data 	| Remarks  	|");
                stringBuilder.AppendLine("| ---                    | ---               | ---           | ---       |");

                //loop each property
                foreach (var prop in commandClass.GetProperties().Where(f => f.Name.StartsWith("v_")).ToList())
                {
                    //pull attributes from property
                    var commandLabel       = CleanMarkdownValue(GetPropertyValue(prop, typeof(DisplayNameAttribute)));
                    var helpfulExplanation = CleanMarkdownValue(GetPropertyValue(prop, typeof(DescriptionAttribute)));
                    var sampleUsage        = CleanMarkdownValue(GetPropertyValue(prop, typeof(SampleUsage)));
                    var remarks            = CleanMarkdownValue(GetPropertyValue(prop, typeof(Remarks)));

                    //append to parameter table
                    stringBuilder.AppendLine("|" + commandLabel + "|" + helpfulExplanation + "|" + sampleUsage + "|" + remarks + "|");
                }

                stringBuilder.AppendLine(Environment.NewLine);
                stringBuilder.AppendLine("## Developer/Additional Reference");
                stringBuilder.AppendLine("Automation Class Name: " + commandClass.Name);
                stringBuilder.AppendLine("Parent Namespace: " + commandClass.Namespace);
                stringBuilder.AppendLine("This page was generated on " + DateTime.Now.ToString("MM/dd/yy hh:mm tt"));
                stringBuilder.AppendLine(Environment.NewLine);
                stringBuilder.AppendLine("## Help");
                stringBuilder.AppendLine("[Open/Report an issue on GitHub](https://github.com/OpenBotsAI/OpenBots.Studio/issues/new)");
                stringBuilder.AppendLine("[Ask a question on the OpenBots Forum](https://openbots.ai/forums/)");

                //create kebob destination and command file name
                var kebobDestination = groupName.Replace(" ", "-").Replace("/", "-").ToLower();
                var kebobFileName    = commandName.Replace(" ", "-").Replace("/", "-").ToLower() + "-command.md";

                //create directory if required
                var destinationdirectory = Path.Combine(docsPath, kebobDestination);
                if (!Directory.Exists(destinationdirectory))
                {
                    Directory.CreateDirectory(destinationdirectory);
                }

                //write file
                fullFileName = Path.Combine(destinationdirectory, kebobFileName);
                File.WriteAllText(fullFileName, stringBuilder.ToString());

                //add to high level
                var serverPath = "/automation-commands/" + kebobDestination + "/" + kebobFileName.Replace(".md", "");
                highLevelCommandInfo.Add(
                    new CommandMetaData()
                {
                    Group       = groupName,
                    Description = classDescription,
                    Name        = commandName,
                    Location    = serverPath
                });
            }

            stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("<!--TITLE: Automation Commands -->");
            stringBuilder.AppendLine("<!-- SUBTITLE: an overview of available commands in OpenBots. -->");
            stringBuilder.AppendLine("## Automation Commands");
            stringBuilder.AppendLine("| Command Group   	| Command Name 	|  Command Description	|");
            stringBuilder.AppendLine("| ---                | ---           | ---                   |");

            foreach (var cmd in highLevelCommandInfo)
            {
                stringBuilder.AppendLine("|" + cmd.Group + "|[" + cmd.Name + "](" + cmd.Location + ")|" + cmd.Description + "|");
            }

            stringBuilder.AppendLine(Environment.NewLine);
            stringBuilder.AppendLine("## Help");
            stringBuilder.AppendLine("[Open/Report an issue on GitHub](https://github.com/OpenBotsAI/OpenBots.Studio/issues/new)");
            stringBuilder.AppendLine("[Ask a question on the OpenBots forum](https://openbots.ai/forums/)");

            //write file
            fullFileName = Path.Combine(docsPath, "automation-commands.md");
            File.WriteAllText(fullFileName, stringBuilder.ToString());

            return(docsPath);
        }
Ejemplo n.º 23
0
 private static void ConfigureWebApi(HttpConfiguration httpConfiguration, Autofac.IContainer container)
 {
     ConfigureWebApiDependencyResolver(httpConfiguration, container);
     ConfigureWebApiRouting(httpConfiguration);
     ConfigureWebApiSerialization(httpConfiguration);
 }