public void ConnectToUnexistingHostFailsWithinTimeout(CompletionType completionType)
        {
            var sw = Stopwatch.StartNew();

            try
            {
                var config = new ConfigurationOptions
                {
                    EndPoints = { { "invalid", 1234 } },
                    ConnectTimeout = 1000
                };

                SocketManager.ConnectCompletionType = completionType;

                using (var muxer = ConnectionMultiplexer.Connect(config))
                {
                    Thread.Sleep(10000);
                }

                Assert.Fail("Connect should fail with RedisConnectionException exception");
            }
            catch (RedisConnectionException)
            {
                var elapsed = sw.ElapsedMilliseconds;
                if (elapsed > 9000) 
                {
                    Assert.Fail("Connect should fail within ConnectTimeout");
                }
            }
            finally
            {
                SocketManager.ConnectCompletionType = CompletionType.Any;
            }
        }
        public static IConfigurationSourceRoot RegisterConfiguration([NotNull] this Startup startup, [NotNull] string toolsDirectory, [NotNull] string projectDirectory, ConfigurationOptions options)
        {
            var configuration = new Microsoft.Framework.ConfigurationModel.Configuration();
            configuration.Add(new MemoryConfigurationSource());

            configuration.Set(Constants.Configuration.ToolsDirectory, toolsDirectory);
            configuration.Set(Constants.Configuration.ProjectDirectory, projectDirectory);
            configuration.Set(Constants.Configuration.SystemConfigFileName, "scconfig.json");

            var configurationService = new ConfigurationService(configuration);

            if ((options & ConfigurationOptions.DoNotLoadConfig) != ConfigurationOptions.DoNotLoadConfig)
            {
                try
                {                       
                    configurationService.Load(options);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    return null;
                }
            }

            return configuration;
        }
예제 #3
0
        public void ConnectToSSLServer(int port, string sslHost)
        {
            var config = new ConfigurationOptions
            {
                CommandMap = CommandMap.Create( // looks like "config" is disabled
                    new Dictionary<string, string>
                    {
                        { "config", null },
                        { "cluster", null }
                    }
                ),
                SslHost = sslHost,
                EndPoints = { { "sslredis", port} },
                AllowAdmin = true,
                SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000
            };
            config.CertificateValidation += (sender, cert, chain, errors) =>
            {
                Console.WriteLine("cert issued to: " + cert.Subject);
                return true; // fingers in ears, pretend we don't know this is wrong
            };
            using (var muxer = ConnectionMultiplexer.Connect(config, Console.Out))
            {
                muxer.ConnectionFailed += OnConnectionFailed;
                muxer.InternalError += OnInternalError;
                var db = muxer.GetDatabase();
                db.Ping();
                using (var file = File.Create("ssl" + port + ".zip"))
                {
                    muxer.ExportConfiguration(file);
                }
                RedisKey key = "SE.Redis";

                const int AsyncLoop = 2000;
                // perf; async
                db.KeyDelete(key, CommandFlags.FireAndForget);
                var watch = Stopwatch.StartNew();
                for (int i = 0; i < AsyncLoop; i++)
                {
                    db.StringIncrement(key, flags: CommandFlags.FireAndForget);
                }
                // need to do this inside the timer to measure the TTLB
                long value = (long)db.StringGet(key);
                watch.Stop();
                Assert.AreEqual(AsyncLoop, value);
                Console.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}",
                    AsyncLoop,
                    (long)watch.ElapsedMilliseconds,
                    (long)(AsyncLoop / watch.Elapsed.TotalSeconds),
                    value);

                // perf: sync/multi-threaded
                TestConcurrent(db, key, 30, 10);
                TestConcurrent(db, key, 30, 20);
                TestConcurrent(db, key, 30, 30);
                TestConcurrent(db, key, 30, 40);
                TestConcurrent(db, key, 30, 50);
            }
        }
예제 #4
0
 public void Setup() {
     dir = FileSystemHelper.ResetTemporaryDirectory();
     opts = new ConfigurationOptions {
         FileSet = new FileSet(dir,"*.bxls")
     };
     writefile("simple_config", simple_config);
     loader = new ConfigurationLoader(opts);
 }
예제 #5
0
        static void Main()
        {
            ServiceManager.Initialize("MyService", "My Service", "This is my special service that doesn't do much of anything!");

            var config = new ConfigurationOptions("--");
            var runner = new Runner(new Service(), config);
            runner.Run();
        }
        protected ConnectionMultiplexer CreateMultiplexer(Action<ConfigurationOptions> init = null)
        {
            ConfigurationOptions options = new ConfigurationOptions();
            options.AllowAdmin = true;
            options.EndPoints.Add("localhost:8512");

            if (init != null)
                init(options);

            return ConnectionMultiplexer.Connect(options);
        }
예제 #7
0
        public void MonitorInit(ConfigurationOptions configurationOptions)
        {
            if (Log.IsDebugEnabled) Log.Debug(Resources.Msg_Monitor_InitCalled);

            // Register interal event handlers for external events
            RequestStart += MonitorService_RequestStart;
            RequestStop += MonitorService_RequestStop;

            _configurationOptions = configurationOptions;
            _isWorking = false;

            if (Log.IsDebugEnabled) Log.Debug(Resources.Msg_Montior_InitFinished);
        }
 public void SocketFailureError()
 {
     var options = new ConfigurationOptions();
     options.EndPoints.Add(".redis.cache.windows.net");
     options.Ssl = true;
     options.Password = "";
     options.AbortOnConnectFail = false;
     using (var muxer = ConnectionMultiplexer.Connect(options))
     {
         var ex = Assert.Throws<RedisConnectionException>(() => muxer.GetDatabase().Ping());
         var rde = (RedisConnectionException)ex.InnerException;
         Assert.That(rde.FailureType, Is.EqualTo(ConnectionFailureType.SocketFailure));
     }
 }
 public static ConnectionMultiplexer GetRedisConn()
 {
     // create a connection
     var options = new ConfigurationOptions()
     {
         AllowAdmin = true, //To allow shutdown
         SentinelConnection = SentinelConn,
         SyncTimeout = 5000
     };
     var connection = ConnectionMultiplexer.Connect(options, Console.Out);
     Thread.Sleep(3000);
     Assert.IsTrue(connection.IsConnected);
     return connection;
 }
예제 #10
0
        public void ConfigManualWithDefaultPorts(string host, int port, bool useSsl, int expectedPort)
        {
            var options = new ConfigurationOptions();
            if(port == 0)
            {
                options.EndPoints.Add(host);
            } else
            {
                options.EndPoints.Add(host, port);
            }
            if (useSsl) options.Ssl = true;

            options.SetDefaultPorts(); // normally it is the multiplexer that calls this, not us
            Assert.AreEqual(expectedPort, ((DnsEndPoint)options.EndPoints.Single()).Port);
        }
예제 #11
0
        public ConnectionMultiplexer GetRedisConnection()
        {
            // create a connection
            var options = new ConfigurationOptions();
            options.AllowAdmin = true;
            options.SentinelConnection = sentinelConnection;
            options.ResponseTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["redis.responsetimeout"]);
            options.SyncTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["redis.synctimeout"]); ;

            Console.WriteLine("Connecting to master...");
            var connection = ConnectionMultiplexer.Connect(options, fileStreamWriter);
            Thread.Sleep(1000);

            Console.WriteLine(connection.IsConnected ? "CONNECTED at :" + GetMasterEndpoint() : "FAILED");
            return connection;
        }
예제 #12
0
 public void ConnectToSSDB()
 {
     var config = new ConfigurationOptions
     {
         EndPoints = { { "ubuntu", 8888 } },
         CommandMap = CommandMap.SSDB
     };
     RedisKey key = Me();
     using (var conn = ConnectionMultiplexer.Connect(config))
     {
         var db = conn.GetDatabase(0);
         db.KeyDelete(key);
         Assert.IsTrue(db.StringGet(key).IsNull);
         db.StringSet(key, "abc");
         Assert.AreEqual("abc", (string)db.StringGet(key));
     }
 }
예제 #13
0
 public static ConnectionMultiplexer GetConn()
 {
     // create a connection
     var options = new ConfigurationOptions()
     {
         CommandMap = CommandMap.Sentinel,
         EndPoints = { { IP, Port } },
         AllowAdmin = true,
         TieBreaker = "",
         ServiceName = ServiceName,
         SyncTimeout = 5000
     };
     var connection = ConnectionMultiplexer.Connect(options, Console.Out);
     Thread.Sleep(3000);
     Assert.IsTrue(connection.IsConnected);
     return connection;
 }
예제 #14
0
 public void TalkToNonsenseServer()
 {
     var config = new ConfigurationOptions
     {
         AbortOnConnectFail = false,
         EndPoints =
         {
             { "127.0.0.1:1234" }
         },
         ConnectTimeout = 200
     };
     var log = new StringWriter();
     using(var conn = ConnectionMultiplexer.Connect(config, log))
     {
         Console.WriteLine(log);
         Assert.IsFalse(conn.IsConnected);
     }
 }
예제 #15
0
 public void Basic()
 {
     var fromConfig = new ConfigurationOptions { EndPoints = { { PrimaryServer, SecurePort } }, Password = SecurePassword };
     var toConfig = new ConfigurationOptions { EndPoints = { { PrimaryServer, PrimaryPort } } };
     using (var from = ConnectionMultiplexer.Connect(fromConfig))
     using (var to = ConnectionMultiplexer.Connect(toConfig))
     {
         RedisKey key = Me();
         var fromDb = from.GetDatabase();
         var toDb = to.GetDatabase();
         fromDb.KeyDelete(key);
         toDb.KeyDelete(key);
         fromDb.StringSet(key, "foo");
         var dest = to.GetEndPoints(true).Single();
         fromDb.KeyMigrate(key, dest);
         Assert.IsFalse(fromDb.KeyExists(key));
         Assert.IsTrue(toDb.KeyExists(key));
         string s = toDb.StringGet(key);
         Assert.AreEqual("foo", s);
     }
 }
예제 #16
0
 public void ConnectToAzure(int? port, bool ssl)
 {
     string name, password;
     GetAzureCredentials(out name, out password);
     var options = new ConfigurationOptions();
     if (port == null)
     {
         options.EndPoints.Add(name + ".redis.cache.windows.net");
     } else
     {
         options.EndPoints.Add(name + ".redis.cache.windows.net", port.Value);
     }
     options.Ssl = ssl;
     options.Password = password;
     Console.WriteLine(options);
     using(var connection = ConnectionMultiplexer.Connect(options))
     {
         var ttl = connection.GetDatabase().Ping();
         Console.WriteLine(ttl);
     }
 }
예제 #17
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateForm())
            {
                IConfigurationOptionsService cos = ServiceLocator.GetInstance<IConfigurationOptionsService>();
                ConfigurationOptions co = cos.GetConfiguration();

                if (co == null)
                    co = new ConfigurationOptions();

                co.ModemIPAddress = txtModemIPAddress.Text;
                co.ModemLogPageUrl = txtLogPageUrl.Text;
                co.ModemPassword = txtModemPassword.Text;
                co.ModemSignalPageUrl = txtSignalPageUrl.Text;
                co.ModemUsername = txtModemUsername.Text;
                co.MonitorAddress = txtMonitorAddress.Text;
                co.Profile = cboProfiles.SelectedItem.ToString();

                cos.SaveConfiguration(co);
                Close();
            }
        }
 public void AuthenticationFailureError()
 {
     string name, password;
     GetAzureCredentials(out name, out password);
     var options = new ConfigurationOptions();
     options.EndPoints.Add(name + ".redis.cache.windows.net");
     options.Ssl = true;
     options.Password = "";
     options.AbortOnConnectFail = false;
     using (var muxer = ConnectionMultiplexer.Connect(options))
     {
         muxer.ConnectionFailed += (object sender, ConnectionFailedEventArgs e) =>
         {
             Assert.That(e.FailureType, Is.EqualTo(ConnectionFailureType.AuthenticationFailure));
         };
         var ex = Assert.Throws<RedisConnectionException>(() => muxer.GetDatabase().Ping());
         var rde = (RedisConnectionException)ex.InnerException;
         Assert.That(rde.FailureType, Is.EqualTo(ConnectionFailureType.AuthenticationFailure));
         Assert.That(rde.InnerException.Message, Is.EqualTo("Error: NOAUTH Authentication required. Verify if the Redis password provided is correct."));
         //wait for a second  for connectionfailed event to fire
         Thread.Sleep(1000);
     }
 }
        public void SSLCertificateValidationError(bool isCertValidationSucceeded)
        {
            string name, password;
            GetAzureCredentials(out name, out password);
            var options = new ConfigurationOptions();
            options.EndPoints.Add(name + ".redis.cache.windows.net");
            options.Ssl = true;
            options.Password = password;
            options.CertificateValidation += (sender, cert, chain, errors) => { return isCertValidationSucceeded; };
            options.AbortOnConnectFail = false;

            using (var connection = ConnectionMultiplexer.Connect(options))
            {
                connection.ConnectionFailed += (object sender, ConnectionFailedEventArgs e) =>
                {
                    Assert.That(e.FailureType, Is.EqualTo(ConnectionFailureType.AuthenticationFailure));
                };
                if (!isCertValidationSucceeded)
                {
                    //validate that in this case it throws an certificatevalidation exception
                    var ex = Assert.Throws<RedisConnectionException>(() => connection.GetDatabase().Ping());
                    var rde = (RedisConnectionException)ex.InnerException;
                    Assert.That(rde.FailureType, Is.EqualTo(ConnectionFailureType.AuthenticationFailure));
                    Assert.That(rde.InnerException.Message, Is.EqualTo("The remote certificate is invalid according to the validation procedure."));
                }
                else
                {
                    Assert.DoesNotThrow(() => connection.GetDatabase().Ping());
                }

                //wait for a second for connectionfailed event to fire
                Thread.Sleep(1000);
            }


        }
        public void SaveConfiguration(Model.ConfigurationOptions configurationOptions)
        {
            using (CMWatcherEntities dbContainer = new CMWatcherEntities(RepositoryRegistry.EntityConntectionBuilder.ToString()))
            {
                if (configurationOptions.ConfigurationOptionId == 0)
                {
                    ConfigurationOptions co = new ConfigurationOptions();

                    co.ModemIPAddress = configurationOptions.ModemIPAddress;
                    co.ModemSignalPageUrl = configurationOptions.ModemSignalPageUrl;
                    co.ModemLogPageUrl = configurationOptions.ModemLogPageUrl;
                    co.ModemUsername = configurationOptions.ModemUsername;
                    co.ModemPassword = configurationOptions.ModemPassword;
                    co.MonitorAddress = configurationOptions.MonitorAddress;
                    co.Profile = configurationOptions.Profile;

                    dbContainer.AddToConfigurationOptions(co);
                }
                else
                {
                    var co = (from co1 in dbContainer.ConfigurationOptions
                                     where co1.ConfigurationOptionId == configurationOptions.ConfigurationOptionId
                                     select co1).First();

                    co.ModemIPAddress = configurationOptions.ModemIPAddress;
                    co.ModemSignalPageUrl = configurationOptions.ModemSignalPageUrl;
                    co.ModemLogPageUrl = configurationOptions.ModemLogPageUrl;
                    co.ModemUsername = configurationOptions.ModemUsername;
                    co.ModemPassword = configurationOptions.ModemPassword;
                    co.MonitorAddress = configurationOptions.MonitorAddress;
                    co.Profile = configurationOptions.Profile;
                }

                dbContainer.SaveChanges();
            }
        }
예제 #21
0
 private static void RegisterAuthoriazation(IServiceCollection serviceCollection, IConfiguration configuration)
 {
     serviceCollection.AddScoped <IUserClaimsPrincipalFactory <ApplicationUser>, AppClaimsPrincipalFactory>();
     serviceCollection.AddTransient <IJwtFactory, JwtFactory>();
     serviceCollection.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => ConfigurationOptions.JwtBearerOptions(options, configuration));
     serviceCollection.AddIdentity <ApplicationUser, ApplicationRole>(ConfigurationOptions.IdentityOptions).AddEntityFrameworkStores <NiisWebContextMigration>();
 }
 internal WrappedConfigurationOptions(string redisConnectionString, bool isDedicatedForAllChannel)
     : this(ConfigurationOptions.Parse(redisConnectionString), isDedicatedForAllChannel)
 {
 }
 partial void OnCreateReaderWriter(ConfigurationOptions configuration)
 {
     ownsSocketManager = configuration.SocketManager == null;
     socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads);
 }
예제 #24
0
        public ShardsCoordinator()
        {
            //load main stuff
            LogSetup.SetupLogger(-1);
            _log   = LogManager.GetCurrentClassLogger();
            _creds = new BotCredentials();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            _key = _creds.RedisKey();

            var conf = ConfigurationOptions.Parse(_creds.RedisOptions);

            _redis = ConnectionMultiplexer.Connect(conf);

            var imgCache = new RedisImagesCache(_redis, _creds);   //reload images into redis

            if (!imgCache.AllKeysExist().GetAwaiter().GetResult()) // but only if the keys don't exist. If images exist, you have to reload them manually
            {
                imgCache.Reload().GetAwaiter().GetResult();
            }
            else
            {
                _log.Info("Images are already present in redis. Use .imagesreload to force update if needed.");
            }

            //setup initial shard statuses
            _defaultShardState = new ShardComMessage()
            {
                ConnectionState = Discord.ConnectionState.Disconnected,
                Guilds          = 0,
                Time            = DateTime.UtcNow
            };
            var db = _redis.GetDatabase();

            //clear previous statuses
            db.KeyDelete(_key + "_shardstats");

            _shardProcesses = new Process[_creds.TotalShards];
            var shardIds = Enumerable.Range(1, _creds.TotalShards - 1)
                           .Shuffle()
                           .Prepend(0)
                           .ToArray();

            for (var i = 0; i < shardIds.Length; i++)
            {
                var id = shardIds[i];
                //add it to the list of shards which should be started
#if DEBUG
                if (id > 0)
                {
                    _shardStartQueue.Enqueue(id);
                }
                else
                {
                    _shardProcesses[id] = Process.GetCurrentProcess();
                }
#else
                _shardStartQueue.Enqueue(i);
#endif
                //set the shard's initial state in redis cache
                var msg = _defaultShardState.Clone();
                msg.ShardId = id;
                //this is to avoid the shard coordinator thinking that
                //the shard is unresponsive while starting up
                var delay = 45;
#if GLOBAL_NADEKO
                delay = 180;
#endif
                msg.Time = DateTime.UtcNow + TimeSpan.FromSeconds(delay * (id + 1));
                db.ListRightPush(_key + "_shardstats",
                                 JsonConvert.SerializeObject(msg),
                                 flags: CommandFlags.FireAndForget);
            }

            _curProcessId = Process.GetCurrentProcess().Id;

            //subscribe to shardcoord events
            var sub = _redis.GetSubscriber();

            //send is called when shard status is updated. Every 7.5 seconds atm
            sub.Subscribe(_key + "_shardcoord_send",
                          OnDataReceived,
                          CommandFlags.FireAndForget);

            //called to stop the shard, although the shard will start again when it finds out it's dead
            sub.Subscribe(_key + "_shardcoord_stop",
                          OnStop,
                          CommandFlags.FireAndForget);

            //called kill the bot
            sub.Subscribe(_key + "_die",
                          (ch, x) => Environment.Exit(0),
                          CommandFlags.FireAndForget);
        }
 public static WrappedConfigurationOptions CreateConfiguration(ConfigurationOptions options, bool isDedicatedForAllChannel = false)
 => new WrappedConfigurationOptions(options, isDedicatedForAllChannel);
예제 #26
0
    // This method gets called by the runtime. Use this method to add services to the container.
    public virtual IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc(options =>
        {
            options.EnableDetailedErrors = true;
        });

        RegisterAppInsights(services);

        services.AddControllers(options =>
        {
            options.Filters.Add(typeof(HttpGlobalExceptionFilter));
            options.Filters.Add(typeof(ValidateModelStateFilter));
        })     // Added for functional tests
        .AddApplicationPart(typeof(BasketController).Assembly)
        .AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Title       = "eShopOnContainers - Basket HTTP API",
                Version     = "v1",
                Description = "The Basket Service HTTP API"
            });

            options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Type  = SecuritySchemeType.OAuth2,
                Flows = new OpenApiOAuthFlows()
                {
                    Implicit = new OpenApiOAuthFlow()
                    {
                        AuthorizationUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"),
                        TokenUrl         = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"),
                        Scopes           = new Dictionary <string, string>()
                        {
                            { "basket", "Basket API" }
                        }
                    }
                }
            });

            options.OperationFilter <AuthorizeCheckOperationFilter>();
        });

        ConfigureAuthService(services);

        services.AddCustomHealthCheck(Configuration);

        services.Configure <BasketSettings>(Configuration);

        //By connecting here we are making sure that our service
        //cannot start until redis is ready. This might slow down startup,
        //but given that there is a delay on resolving the ip address
        //and then creating the connection it seems reasonable to move
        //that cost to startup instead of having the first request pay the
        //penalty.
        services.AddSingleton <ConnectionMultiplexer>(sp =>
        {
            var settings      = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
            var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

            return(ConnectionMultiplexer.Connect(configuration));
        });


        if (Configuration.GetValue <bool>("AzureServiceBusEnabled"))
        {
            services.AddSingleton <IServiceBusPersisterConnection>(sp =>
            {
                var serviceBusConnectionString = Configuration["EventBusConnection"];

                return(new DefaultServiceBusPersisterConnection(serviceBusConnectionString));
            });
        }
        else
        {
            services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
            {
                var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >();

                var factory = new ConnectionFactory()
                {
                    HostName = Configuration["EventBusConnection"],
                    DispatchConsumersAsync = true
                };

                if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                {
                    factory.UserName = Configuration["EventBusUserName"];
                }

                if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                {
                    factory.Password = Configuration["EventBusPassword"];
                }

                var retryCount = 5;
                if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                {
                    retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                }

                return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount));
            });
        }

        RegisterEventBus(services);


        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                              builder => builder
                              .SetIsOriginAllowed((host) => true)
                              .AllowAnyMethod()
                              .AllowAnyHeader()
                              .AllowCredentials());
        });
        services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient <IBasketRepository, RedisBasketRepository>();
        services.AddTransient <IIdentityService, IdentityService>();

        services.AddOptions();

        var container = new ContainerBuilder();

        container.Populate(services);

        return(new AutofacServiceProvider(container.Build()));
    }
예제 #27
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var postgresConnectionString =
                ConnectionStringUrlToResource(_configuration.GetValue <string>("DATABASE_URL")
                                              ?? throw new Exception("DATABASE_URL is null"));

            services.AddOptions();

            services.AddLogging();

            services.AddRouting(options => { options.LowercaseUrls = true; });

            if (_env.IsDevelopment())
            {
                services.AddDistributedMemoryCache();
            }
            else
            {
                services.AddStackExchangeRedisCache(x =>
                                                    x.Configuration = _configuration.GetValue <string>("REDISTOGO_URL"));
            }

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout         = TimeSpan.FromMinutes(50);
                options.Cookie.HttpOnly     = true;
                options.Cookie.Name         = ApiConstants.AuthenticationSessionCookieName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "oriental-rug-gallery-API", Version = "v1"
                });
            });

            services.AddMvc(x =>
            {
                x.ModelValidatorProviders.Clear();

                // Not need to have https
                x.RequireHttpsPermanent = false;

                // Allow anonymous for localhost
                if (_env.IsDevelopment())
                {
                    x.Filters.Add <AllowAnonymousFilter>();
                }
            }).AddNewtonsoftJson(x =>
            {
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                x.SerializerSettings.Converters.Add(new StringEnumConverter());
            }).AddRazorPagesOptions(x => { x.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); });

            services.AddWebMarkupMin(opt =>
            {
                opt.AllowMinificationInDevelopmentEnvironment = true;
                opt.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification()
            .AddHttpCompression();

            services.AddDbContext <EntityDbContext>(opt => opt.UseNpgsql(postgresConnectionString));

            services.AddIdentity <User, IdentityRole <int> >(x => { x.User.RequireUniqueEmail = true; })
            .AddEntityFrameworkStores <EntityDbContext>()
            .AddRoles <IdentityRole <int> >()
            .AddDefaultTokenProviders();

            // L2 EF cache
            if (_env.IsDevelopment())
            {
                EntityFrameworkCache.Initialize(new InMemoryCache());
            }
            else
            {
                var redisConfigurationOptions =
                    ConfigurationOptions.Parse(_configuration.GetValue <string>("REDISTOGO_URL"));

                // Important
                redisConfigurationOptions.AbortOnConnectFail = false;

                EntityFrameworkCache.Initialize(new RedisCache(redisConfigurationOptions));
            }

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x =>
            {
                x.Cookie.MaxAge = TimeSpan.FromMinutes(60);
            });

            // Re-Captcha config
            services.Configure <RecaptchaSettings>(_configuration.GetSection("RecaptchaSettings"));
            services.AddTransient <IRecaptchaService, RecaptchaService>();

            _container = new Container(config =>
            {
                config.For <DocumentStore>().Use(DocumentStore.For(y =>
                {
                    // Important as PLV8 is disabled on Heroku
                    y.PLV8Enabled = false;

                    y.Connection(postgresConnectionString);

                    y.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate;
                }));

                var(accessKeyId, secretAccessKey, url) = (
                    _configuration.GetRequiredValue <string>("CLOUDCUBE_ACCESS_KEY_ID"),
                    _configuration.GetRequiredValue <string>("CLOUDCUBE_SECRET_ACCESS_KEY"),
                    _configuration.GetRequiredValue <string>("CLOUDCUBE_URL")
                    );

                var prefix = new Uri(url).Segments.Skip(1).FirstOrDefault() ?? throw new Exception("S3 url is malformed");
                const string bucketName = "cloud-cube";

                // Generally bad practice
                var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

                // Create S3 client
                config.For <IAmazonS3>().Use(() => new AmazonS3Client(credentials, RegionEndpoint.USEast1));
                config.For <S3ServiceConfig>().Use(new S3ServiceConfig(bucketName, prefix));

                // Register stuff in container, using the StructureMap APIs...
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.Assembly("Api");
                    _.Assembly("Logic");
                    _.Assembly("Dal");
                    _.WithDefaultConventions();
                });

                // Populate the container using the service collection
                config.Populate(services);
            });

            _container.AssertConfigurationIsValid();

            return(_container.GetInstance <IServiceProvider>());
        }
예제 #28
0
        public RedisCacheManager(ConfigurationOptions cnnection = null)
        {
            _connection = cnnection;

            _db = Instance.GetDatabase();
        }
예제 #29
0
        public IServer GetServer(string configName = null, int endPointsIndex = 0)
        {
            var confOption = ConfigurationOptions.Parse(_connectionString);

            return(GetConnect().GetServer(confOption.EndPoints[endPointsIndex]));
        }
예제 #30
0
 protected BaseController(ISearchRepository searchRepo, IOptions <ConfigurationOptions> elasticIndexOptionsAccessor, IMemoryCache cache)
 {
     SearchRepo           = searchRepo;
     ConfigurationOptions = elasticIndexOptionsAccessor.Value;
     Cache = cache;
 }
예제 #31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region Grpc服务(待)
            services.AddGrpc(options =>
            {
                options.EnableDetailedErrors = true;
            });
            #endregion

            // 注册App监控(搁)
            RegisterAppInsights(services);

            #region MVC服务
            services.AddControllers(options =>
            {
                // 全局异常过滤器
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
                // 模型验证过滤器
                options.Filters.Add(typeof(ValidateModelStateFilter));
            })
            // 为了功能集成测试
            .AddApplicationPart(typeof(BasketController).Assembly)
            .AddNewtonsoftJson();
            #endregion

            #region Swagger
            services.AddSwaggerGen(options =>
            {
                //options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "eShopOnContainers - Basket HTTP API",
                    Version     = "v1",
                    Description = "The Basket Service HTTP API"
                });

                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type  = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow()
                        {
                            AuthorizationUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"),
                            TokenUrl         = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"),
                            Scopes           = new Dictionary <string, string>()
                            {
                                { "basket", "Basket API" }
                            }
                        }
                    }
                });


                // 开启加权小锁
                options.OperationFilter <AddResponseHeadersFilter>();
                options.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });
            #endregion

            // 配置认证服务
            ConfigureAuthService(services);

            // 自定义健康检测
            services.AddCustomHealthCheck(Configuration);

            // 获取配置数据
            services.Configure <BasketSettings>(Configuration);

            #region Redis
            // 配置启动Redis服务,虽然可能影响项目启动速度,但是不能在运行的时候报错,所以是合理的
            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var settings      = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
                var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });
            #endregion


            #region  务总线,Azure或RabbitMQ(搁)
            if (Configuration.GetValue <bool>("AzureServiceBusEnabled"))
            {
                services.AddSingleton <IServiceBusPersisterConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultServiceBusPersisterConnection> >();

                    var serviceBusConnectionString = Configuration["EventBusConnection"];
                    var serviceBusConnection       = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

                    return(new DefaultServiceBusPersisterConnection(serviceBusConnection, logger));
                });
            }
            else
            {
                services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >();

                    var factory = new ConnectionFactory()
                    {
                        HostName = Configuration["EventBusConnection"],
                        DispatchConsumersAsync = true
                    };

                    if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                    {
                        factory.UserName = Configuration["EventBusUserName"];
                    }

                    if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                    {
                        factory.Password = Configuration["EventBusPassword"];
                    }

                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                    {
                        retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                    }

                    return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount));
                });
            }
            #endregion

            // 注册事件总线(搁)
            // 有更新价格、订单生成两部分
            RegisterEventBus(services);

            #region 跨域
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .SetIsOriginAllowed((host) => true)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            #endregion

            // 仓储数据
            services.AddTransient <IBasketRepository, RedisBasketRepository>();

            #region 从Httpcontext中获取指定信息
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IIdentityService, IdentityService>();
            #endregion

            services.AddOptions();

            // Autofac容器,因为用的是webhost,不是host泛型宿主,所以可以这么写
            var container = new ContainerBuilder();
            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
예제 #32
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration      = hostingEnvironment.BuildConfiguration();

            // 请求代理配置
            Configure <ForwardedHeadersOptions>(options =>
            {
                configuration.GetSection("App:Forwarded").Bind(options);
                // 对于生产环境,为安全考虑需要在配置中指定受信任代理服务器
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            // 配置Ef
            Configure <AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });

            // 解决某些不支持类型的序列化
            Configure <AbpJsonOptions>(options =>
            {
                options.UseHybridSerializer = true;
            });
            // 中文序列化的编码问题
            Configure <AbpSystemTextJsonSerializerOptions>(options =>
            {
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            });

            Configure <KestrelServerOptions>(options =>
            {
                options.Limits.MaxRequestBodySize   = null;
                options.Limits.MaxRequestBufferSize = null;
            });

            Configure <AbpBlobStoringOptions>(options =>
            {
                options.Containers.ConfigureAll((containerName, containerConfiguration) =>
                {
                    containerConfiguration.UseFileSystem(fileSystem =>
                    {
                        fileSystem.BasePath = Path.Combine(Directory.GetCurrentDirectory(), "file-blob-storing");
                    });
                });
            });

            // 加解密
            Configure <AbpStringEncryptionOptions>(options =>
            {
                var encryptionConfiguration = configuration.GetSection("Encryption");
                if (encryptionConfiguration.Exists())
                {
                    options.DefaultPassPhrase = encryptionConfiguration["PassPhrase"] ?? options.DefaultPassPhrase;
                    options.DefaultSalt       = encryptionConfiguration.GetSection("Salt").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["Salt"])
                        : options.DefaultSalt;
                    options.InitVectorBytes = encryptionConfiguration.GetSection("InitVector").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["InitVector"])
                        : options.InitVectorBytes;
                }
            });

            // 自定义需要处理的异常
            Configure <AbpExceptionHandlingOptions>(options =>
            {
                //  加入需要处理的异常类型
                options.Handlers.Add <Volo.Abp.Data.AbpDbConcurrencyException>();
                options.Handlers.Add <AbpInitializationException>();
                options.Handlers.Add <ObjectDisposedException>();
                options.Handlers.Add <StackOverflowException>();
                options.Handlers.Add <OutOfMemoryException>();
                options.Handlers.Add <System.Data.Common.DbException>();
                options.Handlers.Add <Microsoft.EntityFrameworkCore.DbUpdateException>();
                options.Handlers.Add <System.Data.DBConcurrencyException>();
            });
            // 自定义需要发送邮件通知的异常类型
            Configure <AbpEmailExceptionHandlingOptions>(options =>
            {
                // 是否发送堆栈信息
                options.SendStackTrace = true;
                // 未指定异常接收者的默认接收邮件
                // 指定自己的邮件地址
                // options.DefaultReceiveEmail = "*****@*****.**";
            });

            Configure <AbpDistributedCacheOptions>(options =>
            {
                // 最好统一命名,不然某个缓存变动其他应用服务有例外发生
                options.KeyPrefix = "LINGYUN.Abp.Application";
                // 滑动过期30天
                options.GlobalCacheEntryOptions.SlidingExpiration = TimeSpan.FromDays(30);
                // 绝对过期60天
                options.GlobalCacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);
            });

            Configure <RedisCacheOptions>(options =>
            {
                var redisConfig = ConfigurationOptions.Parse(options.Configuration);
                options.ConfigurationOptions = redisConfig;
                options.InstanceName         = configuration["Redis:InstanceName"];
            });

            Configure <AbpVirtualFileSystemOptions>(options =>
            {
                options.FileSets.AddEmbedded <AppPlatformHttpApiHostModule>("LINGYUN.Platform");
            });

            // 多租户
            Configure <AbpMultiTenancyOptions>(options =>
            {
                options.IsEnabled = true;
            });

            Configure <AbpAuditingOptions>(options =>
            {
                options.ApplicationName = "Platform";
                // 是否启用实体变更记录
                var entitiesChangedConfig = configuration.GetSection("App:TrackingEntitiesChanged");
                if (entitiesChangedConfig.Exists() && entitiesChangedConfig.Get <bool>())
                {
                    options
                    .EntityHistorySelectors
                    .AddAllEntities();
                }
            });

            // Swagger
            context.Services.AddSwaggerGen(
                options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Platform API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description  = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Scheme       = "bearer",
                    Type         = SecuritySchemeType.Http,
                    BearerFormat = "JWT"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            // 支持本地化语言类型
            Configure <AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));

                options.Resources.AddDynamic();
            });

            Configure <AbpClaimsMapOptions>(options =>
            {
                options.Maps.TryAdd("name", () => AbpClaimTypes.UserName);
            });

            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority            = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience             = configuration["AuthServer:ApiName"];
            });

            if (!hostingEnvironment.IsDevelopment())
            {
                var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
                context.Services
                .AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "Platform-Protection-Keys");
            }
        }
        protected virtual ConnectionMultiplexer Create(
            string clientName    = null, int?syncTimeout           = null, bool?allowAdmin          = null, int?keepAlive  = null,
            int?connectTimeout   = null, string password           = null, string tieBreaker        = null, TextWriter log = null,
            bool fail            = true, string[] disabledCommands = null, string[] enabledCommands = null,
            bool checkConnect    = true, bool pause                = true, string failMessage = null,
            string channelPrefix = null, bool useSharedSocketManager = true, Proxy?proxy = null)
        {
            if (pause)
            {
                Thread.Sleep(500);       // get a lot of glitches when hammering new socket creations etc; pace it out a bit
            }
            string configuration = GetConfiguration();
            var    config        = ConfigurationOptions.Parse(configuration);

            if (disabledCommands != null && disabledCommands.Length != 0)
            {
                config.CommandMap = CommandMap.Create(new HashSet <string>(disabledCommands), false);
            }
            else if (enabledCommands != null && enabledCommands.Length != 0)
            {
                config.CommandMap = CommandMap.Create(new HashSet <string>(enabledCommands), true);
            }

            if (Debugger.IsAttached)
            {
                syncTimeout = int.MaxValue;
            }

            if (useSharedSocketManager)
            {
                config.SocketManager = socketManager;
            }
            if (channelPrefix != null)
            {
                config.ChannelPrefix = channelPrefix;
            }
            if (tieBreaker != null)
            {
                config.TieBreaker = tieBreaker;
            }
            if (password != null)
            {
                config.Password = string.IsNullOrEmpty(password) ? null : password;
            }
            if (clientName != null)
            {
                config.ClientName = clientName;
            }
            if (syncTimeout != null)
            {
                config.SyncTimeout = syncTimeout.Value;
            }
            if (allowAdmin != null)
            {
                config.AllowAdmin = allowAdmin.Value;
            }
            if (keepAlive != null)
            {
                config.KeepAlive = keepAlive.Value;
            }
            if (connectTimeout != null)
            {
                config.ConnectTimeout = connectTimeout.Value;
            }
            if (proxy != null)
            {
                config.Proxy = proxy.Value;
            }
            var watch = Stopwatch.StartNew();
            var task  = ConnectionMultiplexer.ConnectAsync(config, log ?? Console.Out);

            if (!task.Wait(config.ConnectTimeout >= (int.MaxValue / 2) ? int.MaxValue : config.ConnectTimeout * 2))
            {
                task.ContinueWith(x =>
                {
                    try
                    {
                        GC.KeepAlive(x.Exception);
                    }
                    catch
                    { }
                }, TaskContinuationOptions.OnlyOnFaulted);
                throw new TimeoutException("Connect timeout");
            }
            watch.Stop();
            Console.WriteLine("Connect took: " + watch.ElapsedMilliseconds + "ms");
            var muxer = task.Result;

            if (checkConnect)
            {
                if (!muxer.IsConnected)
                {
                    if (fail)
                    {
                        Assert.Fail(failMessage + "Server is not available");
                    }
                    Assert.Inconclusive(failMessage + "Server is not available");
                }
            }
            muxer.InternalError    += OnInternalError;
            muxer.ConnectionFailed += OnConnectionFailed;
            return(muxer);
        }
예제 #34
0
        private static void set_global_options(IList <string> args, ChocolateyConfiguration config, Container container)
        {
            ConfigurationOptions.parse_arguments_and_update_configuration(
                args,
                config,
                (option_set) =>
            {
                option_set
                .Add("d|debug",
                     "Debug - Show debug messaging.",
                     option => config.Debug = option != null)
                .Add("v|verbose",
                     "Verbose - Show verbose messaging.",
                     option => config.Verbose = option != null)
                .Add("acceptlicense|accept-license",
                     "AcceptLicense - Accept license dialogs automatically. Reserved for future use.",
                     option => config.AcceptLicense = option != null)
                .Add("y|yes|confirm",
                     "Confirm all prompts - Chooses affirmative answer instead of prompting. Implies --accept-license",
                     option =>
                {
                    config.PromptForConfirmation = option == null;
                    config.AcceptLicense         = option != null;
                })
                .Add("f|force",
                     "Force - force the behavior. Do not use force during normal operation - it subverts some of the smart behavior for commands.",
                     option => config.Force = option != null)
                .Add("noop|whatif|what-if",
                     "NoOp / WhatIf - Don't actually do anything.",
                     option => config.Noop = option != null)
                .Add("r|limitoutput|limit-output",
                     "LimitOutput - Limit the output to essential information",
                     option => config.RegularOutput = option == null)
                .Add("timeout=|execution-timeout=",
                     "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds.".format_with(config.CommandExecutionTimeoutSeconds.to_string()),
                     option =>
                {
                    int timeout = 0;
                    int.TryParse(option.remove_surrounding_quotes(), out timeout);
                    if (timeout > 0)
                    {
                        config.CommandExecutionTimeoutSeconds = timeout;
                    }
                })
                .Add("c=|cache=|cachelocation=|cache-location=",
                     "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
                     option => config.CacheLocation = option.remove_surrounding_quotes())
                .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build",
                     "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.",
                     option => config.AllowUnofficialBuild = option != null)
                .Add("failstderr|failonstderr|fail-on-stderr|fail-on-standard-error|fail-on-error-output",
                     "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.",
                     option => config.Features.FailOnStandardError = option != null)
                .Add("use-system-powershell",
                     "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.",
                     option => config.Features.UsePowerShellHost = option == null)
                ;
            },
                (unparsedArgs) =>
            {
                if (!string.IsNullOrWhiteSpace(config.CommandName))
                {
                    // save help for next menu
                    config.HelpRequested = false;
                }
            },
                () => { },
                () =>
            {
                var commandsLog = new StringBuilder();
                IEnumerable <ICommand> commands = container.GetAllInstances <ICommand>();
                foreach (var command in commands.or_empty_list_if_null())
                {
                    var attributes = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast <CommandForAttribute>();
                    foreach (var attribute in attributes.or_empty_list_if_null())
                    {
                        commandsLog.AppendFormat(" * {0} - {1}\n", attribute.CommandName, attribute.Description);
                    }
                }

                "chocolatey".Log().Info(@"This is a listing of all of the different things you can pass to choco.
");
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "Commands");
                "chocolatey".Log().Info(@"
{0}

Please run chocolatey with `choco command -help` for specific help on
 each command.
".format_with(commandsLog.ToString()));
                "chocolatey".Log().Info(ChocolateyLoggers.Important, @"How To Pass Options / Switches");
                "chocolatey".Log().Info(@"
You can pass options and switches in the following ways:

 * Unless stated otherwise, an option/switch should only be passed one
   time. Otherwise you may find weird/non-supported behavior.
 * `-`, `/`, or `--` (one character switches should not use `--`)
 * **Option Bundling / Bundled Options**: One character switches can be
   bundled. e.g. `-d` (debug), `-f` (force), `-v` (verbose), and `-y`
   (confirm yes) can be bundled as `-dfvy`.
 * NOTE: If `debug` or `verbose` are bundled with local options
   (not the global ones above), some logging may not show up until after
   the local options are parsed.
 * **Use Equals**: You can also include or not include an equals sign
   `=` between options and values.
 * **Quote Values**: When you need to quote an entire argument, such as
   when using spaces, please use a combination of double quotes and
   apostrophes (`""'value'""`). In cmd.exe you can just use double quotes
   (`""value""`) but in powershell.exe you should use backticks
   (`` `""value`"" ``) or apostrophes (`'value'`). Using the combination
   allows for both shells to work without issue, except for when the next
   section applies.
 * **Pass quotes in arguments**: When you need to pass quoted values to
   to something like a native installer, you are in for a world of fun. In
   cmd.exe you must pass it like this: `-ia ""/yo=""""Spaces spaces""""""`. In
   PowerShell.exe, you must pass it like this: `-ia '/yo=""""Spaces spaces""""'`.
   No other combination will work. In PowerShell.exe if you are on version
   v3+, you can try `--%` before `-ia` to just pass the args through as is,
   which means it should not require any special workarounds.
 * Options and switches apply to all items passed, so if you are
   installing multiple packages, and you use `--version=1.0.0`, choco
   is going to look for and try to install version 1.0.0 of every
   package passed. So please split out multiple package calls when
   wanting to pass specific options.
");
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "Default Options and Switches");
            });
        }
예제 #35
0
        public void RedisLabsSSL()
        {
            if (!File.Exists(RedisLabsSslHostFile)) Assert.Inconclusive();
            string hostAndPort = File.ReadAllText(RedisLabsSslHostFile);
            int timeout = 5000;
            if (Debugger.IsAttached) timeout *= 100;
            var options = new ConfigurationOptions
            {
                EndPoints = { hostAndPort },
                ConnectTimeout = timeout,
                AllowAdmin = true,
                CommandMap = CommandMap.Create(new HashSet<string> {
                    "subscribe", "unsubscribe", "cluster"
                }, false)
            };
            if (!Directory.Exists(Me())) Directory.CreateDirectory(Me());
#if LOGOUTPUT
            ConnectionMultiplexer.EchoPath = Me();
#endif
            options.Ssl = true;
            options.CertificateSelection += delegate {
                return new X509Certificate2(RedisLabsPfxPath, "");
            };
            RedisKey key = Me();
            using(var conn = ConnectionMultiplexer.Connect(options))
            {
                var db = conn.GetDatabase();
                db.KeyDelete(key);
                string s = db.StringGet(key);
                Assert.IsNull(s);
                db.StringSet(key, "abc");
                s = db.StringGet(key);
                Assert.AreEqual("abc", s);
                
                var latency = db.Ping();
                Console.WriteLine("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);

                using (var file = File.Create("RedisLabs.zip"))
                {
                    conn.ExportConfiguration(file);
                }
            }
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration      = hostingEnvironment.BuildConfiguration();

            // 请求代理配置
            Configure <ForwardedHeadersOptions>(options =>
            {
                configuration.GetSection("App:Forwarded").Bind(options);
                // 对于生产环境,为安全考虑需要在配置中指定受信任代理服务器
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            // 配置Ef
            Configure <AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
                //if (hostingEnvironment.IsDevelopment())
                //{
                //    options.PreConfigure(ctx =>
                //    {
                //        ctx.DbContextOptions.EnableDetailedErrors();
                //        ctx.DbContextOptions.EnableSensitiveDataLogging();
                //    });
                //}
            });

            // 加解密
            Configure <AbpStringEncryptionOptions>(options =>
            {
                var encryptionConfiguration = configuration.GetSection("Encryption");
                if (encryptionConfiguration.Exists())
                {
                    options.DefaultPassPhrase = encryptionConfiguration["PassPhrase"] ?? options.DefaultPassPhrase;
                    options.DefaultSalt       = encryptionConfiguration.GetSection("Salt").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["Salt"])
                        : options.DefaultSalt;
                    options.InitVectorBytes = encryptionConfiguration.GetSection("InitVector").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["InitVector"])
                        : options.InitVectorBytes;
                }
            });

            Configure <PermissionManagementOptions>(options =>
            {
                // Rename IdentityServer.Client.ManagePermissions
                // See https://github.com/abpframework/abp/blob/dev/modules/identityserver/src/Volo.Abp.PermissionManagement.Domain.IdentityServer/Volo/Abp/PermissionManagement/IdentityServer/AbpPermissionManagementDomainIdentityServerModule.cs
                options.ProviderPolicies[ClientPermissionValueProvider.ProviderName] =
                    LINGYUN.Abp.IdentityServer.AbpIdentityServerPermissions.Clients.ManagePermissions;
            });

            // 自定义需要处理的异常
            Configure <AbpExceptionHandlingOptions>(options =>
            {
                //  加入需要处理的异常类型
                options.Handlers.Add <Volo.Abp.Data.AbpDbConcurrencyException>();
                options.Handlers.Add <AbpInitializationException>();
                options.Handlers.Add <ObjectDisposedException>();
                options.Handlers.Add <StackOverflowException>();
                options.Handlers.Add <OutOfMemoryException>();
                options.Handlers.Add <System.Data.Common.DbException>();
                options.Handlers.Add <Microsoft.EntityFrameworkCore.DbUpdateException>();
                options.Handlers.Add <System.Data.DBConcurrencyException>();
            });
            // 自定义需要发送邮件通知的异常类型
            Configure <AbpEmailExceptionHandlingOptions>(options =>
            {
                // 是否发送堆栈信息
                options.SendStackTrace = true;
            });

            Configure <AbpAuditingOptions>(options =>
            {
                options.ApplicationName = "Identity-Server-Admin";
                // 是否启用实体变更记录
                var entitiesChangedConfig = configuration.GetSection("App:TrackingEntitiesChanged");
                if (entitiesChangedConfig.Exists() && entitiesChangedConfig.Get <bool>())
                {
                    options
                    .EntityHistorySelectors
                    .AddAllEntities();
                }
            });

            Configure <AbpDistributedCacheOptions>(options =>
            {
                // 最好统一命名,不然某个缓存变动其他应用服务有例外发生
                options.KeyPrefix = "LINGYUN.Abp.Application";
                // 滑动过期30天
                options.GlobalCacheEntryOptions.SlidingExpiration = TimeSpan.FromDays(30);
                // 绝对过期60天
                options.GlobalCacheEntryOptions.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60);
            });

            Configure <AbpDistributedEntityEventOptions>(options =>
            {
                options.AutoEventSelectors.AddNamespace("Volo.Abp.Identity");
                options.AutoEventSelectors.AddNamespace("Volo.Abp.IdentityServer");
            });

            Configure <RedisCacheOptions>(options =>
            {
                var redisConfig = ConfigurationOptions.Parse(options.Configuration);
                options.ConfigurationOptions = redisConfig;
                options.InstanceName         = configuration["Redis:InstanceName"];
            });

            Configure <AbpVirtualFileSystemOptions>(options =>
            {
                options.FileSets.AddEmbedded <AbpIdentityServerAdminHttpApiHostModule>("LINGYUN.Abp.IdentityServer4");
            });

            // 多租户
            Configure <AbpMultiTenancyOptions>(options =>
            {
                options.IsEnabled = true;
            });

            var tenantResolveCfg = configuration.GetSection("App:Domains");

            if (tenantResolveCfg.Exists())
            {
                Configure <AbpTenantResolveOptions>(options =>
                {
                    var domains = tenantResolveCfg.Get <string[]>();
                    foreach (var domain in domains)
                    {
                        options.AddDomainTenantResolver(domain);
                    }
                });
            }

            // Swagger
            context.Services.AddSwaggerGen(
                options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "IdentityServer4 API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description  = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Scheme       = "bearer",
                    Type         = SecuritySchemeType.Http,
                    BearerFormat = "JWT"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            // 支持本地化语言类型
            Configure <AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));

                options.Resources
                .Get <IdentityResource>()
                .AddVirtualJson("/LINGYUN/Abp/IdentityServer4/Localization");
            });

            Configure <AbpClaimsMapOptions>(options =>
            {
                options.Maps.TryAdd("name", () => AbpClaimTypes.UserName);
            });

            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority            = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience             = configuration["AuthServer:ApiName"];
            });

            if (!hostingEnvironment.IsDevelopment())
            {
                var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
                context.Services
                .AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "BackendAdmin-Protection-Keys");
            }
        }
        public virtual void Load(ConfigurationOptions options, string projectDirectory = null)
        {
            var configurationSourceRoot = Configuration as IConfigurationSourceRoot;
            if (configurationSourceRoot == null)
            {
                throw new ConfigurationException(Texts.Configuration_failed_spectacularly);
            }

            var toolsDirectory = configurationSourceRoot.Get(Constants.Configuration.ToolsDirectory);

            // add system config
            var fileName = Path.Combine(toolsDirectory, configurationSourceRoot.Get(Constants.Configuration.SystemConfigFileName));
            if (!File.Exists(fileName))
            {
                throw new ConfigurationException(Texts.System_configuration_file_not_found, fileName);
            }

            configurationSourceRoot.AddJsonFile(fileName);

            // add command line
            if ((options & ConfigurationOptions.IncludeCommandLine) == ConfigurationOptions.IncludeCommandLine)
            {
                AddCommandLine(configurationSourceRoot);
            }

            // add environment variables
            if ((options & ConfigurationOptions.IncludeEnvironment) == ConfigurationOptions.IncludeEnvironment)
            {
                configurationSourceRoot.AddEnvironmentVariables();
            }

            // set project directory
            if (projectDirectory != null)
            {
                configurationSourceRoot.Set(Constants.Configuration.ProjectDirectory, projectDirectory);
            }
            else
            {
                projectDirectory = configurationSourceRoot.GetString(Constants.Configuration.ProjectDirectory);
            }

            // add project config file - scconfig.json
            var projectConfigFileName = PathHelper.Combine(projectDirectory, configurationSourceRoot.Get(Constants.Configuration.ProjectConfigFileName));
            if (File.Exists(projectConfigFileName))
            {
                configurationSourceRoot.AddFile(projectConfigFileName);
            }
            else if (Directory.GetFiles(projectDirectory).Any() || Directory.GetDirectories(projectDirectory).Any())
            {
                // no config file, but project directory has files, so let's try the default project config file
                projectConfigFileName = PathHelper.Combine(toolsDirectory, "files\\project.noconfig\\scconfig.json");
                if (File.Exists(projectConfigFileName))
                {
                    configurationSourceRoot.AddFile(projectConfigFileName);
                }
            }

            // add project role config - scconfig.role.*.json
            var projectRole = configurationSourceRoot.GetString("project-role");
            if (!string.IsNullOrEmpty(projectRole))
            {
                var projectRoleConfig = Path.Combine(toolsDirectory, $"files\\project.roles\\scconfig.role.{projectRole}.json");
                if (File.Exists(projectRoleConfig))
                {
                    configurationSourceRoot.AddFile(projectRoleConfig);
                }
            }

            var machineConfigFileName = Path.GetFileNameWithoutExtension(projectConfigFileName) + "." + Environment.MachineName + ".json";

            // add module configs (ignore machine config - it will be added last) - scconfig.[module].json 
            if ((options & ConfigurationOptions.IncludeModuleConfig) == ConfigurationOptions.IncludeModuleConfig)
            {
                foreach (var moduleFileName in Directory.GetFiles(projectDirectory, "scconfig.*.json").OrderBy(f => f))
                {
                    if (!string.Equals(moduleFileName, machineConfigFileName, StringComparison.OrdinalIgnoreCase))
                    {
                        configurationSourceRoot.AddFile(moduleFileName);
                    }
                }
            }

            // add machine level config file - scconfig.[machine name].json
            if ((options & ConfigurationOptions.IncludeMachineConfig) == ConfigurationOptions.IncludeMachineConfig)
            {
                if (File.Exists(machineConfigFileName))
                {
                    configurationSourceRoot.AddFile(machineConfigFileName);
                }
            }

            // add user config file - scconfig.json.user
            if ((options & ConfigurationOptions.IncludeUserConfig) == ConfigurationOptions.IncludeUserConfig)
            {
                var userConfigFileName = projectConfigFileName + ".user";
                if (File.Exists(userConfigFileName))
                {
                    configurationSourceRoot.AddFile(userConfigFileName, ".json");
                }
            }

            // add config file specified on the command line: /config myconfig.xml
            if ((options & ConfigurationOptions.IncludeCommandLineConfig) == ConfigurationOptions.IncludeCommandLineConfig)
            {
                var configName = configurationSourceRoot.Get(Constants.Configuration.CommandLineConfig);

                if (!string.IsNullOrEmpty(configName))
                {
                    var configFileName = PathHelper.Combine(projectDirectory, configName);
                    if (File.Exists(configFileName))
                    {
                        configurationSourceRoot.AddFile(configFileName);
                    }
                    else
                    {
                        throw new ConfigurationException(Texts.Config_file_not_found__ + configFileName);
                    }
                }
            }
        }
예제 #38
0
        public void RedisLabsEnvironmentVariableClientCertificate(bool setEnv)
        {
            try
            {
                Skip.IfNoConfig(nameof(TestConfig.Config.RedisLabsSslServer), TestConfig.Current.RedisLabsSslServer);
                Skip.IfNoConfig(nameof(TestConfig.Config.RedisLabsPfxPath), TestConfig.Current.RedisLabsPfxPath);

                if (setEnv)
                {
                    Environment.SetEnvironmentVariable("SERedis_ClientCertPfxPath", TestConfig.Current.RedisLabsPfxPath);
                    Environment.SetEnvironmentVariable("SERedis_IssuerCertPath", "redislabs_ca.pem");
                    // check env worked
                    Assert.Equal(TestConfig.Current.RedisLabsPfxPath, Environment.GetEnvironmentVariable("SERedis_ClientCertPfxPath"));
                    Assert.Equal("redislabs_ca.pem", Environment.GetEnvironmentVariable("SERedis_IssuerCertPath"));
                }
                int timeout = 5000;
                if (Debugger.IsAttached)
                {
                    timeout *= 100;
                }
                var options = new ConfigurationOptions
                {
                    EndPoints      = { { TestConfig.Current.RedisLabsSslServer, TestConfig.Current.RedisLabsSslPort } },
                    ConnectTimeout = timeout,
                    AllowAdmin     = true,
                    CommandMap     = CommandMap.Create(new HashSet <string> {
                        "subscribe", "unsubscribe", "cluster"
                    }, false)
                };

                if (!Directory.Exists(Me()))
                {
                    Directory.CreateDirectory(Me());
                }
#if LOGOUTPUT
                ConnectionMultiplexer.EchoPath = Me();
#endif
                options.Ssl = true;
                RedisKey key = Me();
                using (var conn = ConnectionMultiplexer.Connect(options))
                {
                    if (!setEnv)
                    {
                        Assert.True(false, "Could not set environment");
                    }

                    var db = conn.GetDatabase();
                    db.KeyDelete(key, CommandFlags.FireAndForget);
                    string s = db.StringGet(key);
                    Assert.Null(s);
                    db.StringSet(key, "abc");
                    s = db.StringGet(key);
                    Assert.Equal("abc", s);

                    var latency = db.Ping();
                    Log("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);

                    using (var file = File.Create("RedisLabs.zip"))
                    {
                        conn.ExportConfiguration(file);
                    }
                }
            }
            catch (RedisConnectionException ex)
            {
                if (setEnv || ex.FailureType != ConnectionFailureType.UnableToConnect)
                {
                    throw;
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("SERedis_ClientCertPfxPath", null);
            }
        }
예제 #39
0
 public Runner(IDichotomyService service, ConfigurationOptions config)
 {
     _serviceBase = service;
     _config = config;
 }
 public void Add(string redisConnectionString, bool isDedicatedForAllChannel = false)
 => Add(ConfigurationOptions.Parse(redisConnectionString), isDedicatedForAllChannel);
 partial void OnCreateReaderWriter(ConfigurationOptions configuration)
 {
     this.ownsSocketManager = configuration.SocketManager == null;
     this.socketManager = configuration.SocketManager ?? new SocketManager(ClientName);
 }
예제 #42
0
 public RedisAggregateCache(ConfigurationOptions configuration, TextWriter log = null)
 {
     // Postpone connection until needed.
     _connection = new Lazy <ConnectionMultiplexer>(()
                                                    => ConnectionMultiplexer.Connect(configuration, log));
 }
예제 #43
0
 public Startup WithConfiguration(ConfigurationOptions options)
 {
     ConfigurationOptions = options;
     return this;
 }
예제 #44
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
                options.Filters.Add(typeof(ValidateModelStateFilter));
            }).AddControllersAsServices();

            ConfigureAuthService(services);

            services.AddHealthChecks(checks =>
            {
                checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok")),
                                         TimeSpan.Zero  //No cache for this HealthCheck, better just for demos
                                         );
            });

            services.Configure <BasketSettings>(Configuration);

            //By connecting here we are making sure that our service
            //cannot start until redis is ready. This might slow down startup,
            //but given that there is a delay on resolving the ip address
            //and then creating the connection it seems reasonable to move
            //that cost to startup instead of having the first request pay the
            //penalty.
            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var settings      = sp.GetRequiredService <IOptions <BasketSettings> >().Value;
                var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Info
                {
                    Title          = "Basket HTTP API",
                    Version        = "v1",
                    Description    = "The Basket Service HTTP API",
                    TermsOfService = "Terms Of Service"
                });

                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "implicit",
                    AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",
                    TokenUrl         = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",
                    Scopes           = new Dictionary <string, string>()
                    {
                        { "basket", "Basket API" }
                    }
                });

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <IBasketRepository, RedisBasketRepository>();
            services.AddTransient <IIdentityService, IdentityService>();

            services.AddOptions();

            var containerBuilder = new ContainerBuilder();

            containerBuilder.Populate(services);

            // NServiceBus
            var container = RegisterEventBus(containerBuilder);

            return(new AutofacServiceProvider(container));
        }
 internal WrappedConfigurationOptions(ConfigurationOptions options, bool isDedicatedForAllChannel)
 {
     Options = options;
     IsDedicatedForAllChannel = isDedicatedForAllChannel;
 }
 public void Add(ConfigurationOptions configuration, bool isDedicatedForAllChannel = false)
 => Configurations.Add(new WrappedConfigurationOptions(configuration, isDedicatedForAllChannel));
        public static IConfigurationSourceRoot RegisterConfiguration([NotNull] this Startup startup, [NotNull] string projectDirectory, ConfigurationOptions options)
        {
            var toolsDirectory = Path.Combine(projectDirectory, "sitecore.tools");

            return RegisterConfiguration(startup, toolsDirectory, projectDirectory, options);
        }
예제 #48
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddControllers();

            services.AddDbContext <DataContext>(
                optionsBuilder => optionsBuilder.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))
                );
            services.AddDbContext <IdentityDataContext>(
                optionsBuilder => optionsBuilder.UseNpgsql(configuration.GetConnectionString("IdentityConnection"))
                );

            services.AddSingleton <IConnectionMultiplexer>(serviceProvider =>
            {
                var configurationOptions = ConfigurationOptions.Parse(configuration.GetConnectionString("RedisConnection"));
                return(ConnectionMultiplexer.Connect(configurationOptions));
            });
            services.AddSingleton <ICacheService, CacheService>();

            var builder = services.AddIdentityCore <AppUser>();

            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddEntityFrameworkStores <IdentityDataContext>();
            builder.AddSignInManager <SignInManager <AppUser> >();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(bearerOptions =>
                          bearerOptions.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Token:Key"])),
                ValidIssuer      = configuration["Token:Issuer"],
                ValidateIssuer   = true,
                ValidateAudience = false
            }
                          );

            services.AddScoped(typeof(IGenericService <>), typeof(GenericService <>));
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <ICartService, CartService>();
            services.AddScoped <IJWTTokenService, JWTTokenService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            services.AddAutoMapper(typeof(MappingProfiles));

            services.Configure <ApiBehaviorOptions>(options =>
                                                    options.InvalidModelStateResponseFactory = actionContext =>
            {
                var errors = actionContext.ModelState
                             .Where(error => error.Value.Errors.Count > 0)
                             .SelectMany(kvp => kvp.Value.Errors)
                             .Select(modelError => modelError.ErrorMessage)
                             .ToArray();

                var errorResponse = new APIValidationErrorResponse {
                    Errors = errors
                };

                return(new BadRequestObjectResult(errorResponse));
            }
                                                    );

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "SkynER API", Version = "v1"
                });

                var securitySchema = new OpenApiSecurityScheme
                {
                    Description = "JWT Auth Bearer Scheme",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.Http,
                    Scheme      = "bearer",
                    Reference   = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id   = "Bearer"
                    }
                };

                options.AddSecurityDefinition("Bearer", securitySchema);

                var securityRequirement = new OpenApiSecurityRequirement
                {
                    { securitySchema, new [] { "Bearer" } }
                };

                options.AddSecurityRequirement(securityRequirement);
            });

            services.AddCors(options =>
                             options.AddPolicy("CorsPolicy", policy =>
                                               policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200")
                                               ));
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration      = hostingEnvironment.BuildConfiguration();

            // 请求代理配置
            Configure <ForwardedHeadersOptions>(options =>
            {
                configuration.GetSection("App:Forwarded").Bind(options);
                // 对于生产环境,为安全考虑需要在配置中指定受信任代理服务器
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            // 配置Ef
            Configure <AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });

            // 解决某些不支持类型的序列化
            Configure <AbpJsonOptions>(options =>
            {
                // See: https://docs.abp.io/en/abp/4.0/Migration-Guides/Abp-4_0#always-use-the-newtonsoft-json
                options.UseHybridSerializer = false;
            });
            // 中文序列化的编码问题
            //Configure<AbpSystemTextJsonSerializerOptions>(options =>
            //{
            //    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            //});

            // 加解密
            Configure <AbpStringEncryptionOptions>(options =>
            {
                var encryptionConfiguration = configuration.GetSection("Encryption");
                if (encryptionConfiguration.Exists())
                {
                    options.DefaultPassPhrase = encryptionConfiguration["PassPhrase"] ?? options.DefaultPassPhrase;
                    options.DefaultSalt       = encryptionConfiguration.GetSection("Salt").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["Salt"])
                        : options.DefaultSalt;
                    options.InitVectorBytes = encryptionConfiguration.GetSection("InitVector").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["InitVector"])
                        : options.InitVectorBytes;
                }
            });

            Configure <AbpExceptionHandlingOptions>(options =>
            {
                //  加入需要处理的异常类型
                options.Handlers.Add <Volo.Abp.Data.AbpDbConcurrencyException>();
                options.Handlers.Add <AbpInitializationException>();
                options.Handlers.Add <ObjectDisposedException>();
                options.Handlers.Add <StackOverflowException>();
                options.Handlers.Add <OutOfMemoryException>();
                options.Handlers.Add <System.Data.Common.DbException>();
                options.Handlers.Add <Microsoft.EntityFrameworkCore.DbUpdateException>();
                options.Handlers.Add <System.Data.DBConcurrencyException>();
            });

            Configure <AbpVirtualFileSystemOptions>(options =>
            {
                options.FileSets.AddEmbedded <AbpMessageServiceHttpApiHostModule>("LINGYUN.Abp.MessageService");
            });

            // 多租户
            Configure <AbpMultiTenancyOptions>(options =>
            {
                options.IsEnabled = true;
            });

            var tenantResolveCfg = configuration.GetSection("App:Domains");

            if (tenantResolveCfg.Exists())
            {
                Configure <AbpTenantResolveOptions>(options =>
                {
                    var domains = tenantResolveCfg.Get <string[]>();
                    foreach (var domain in domains)
                    {
                        options.AddDomainTenantResolver(domain);
                    }
                });
            }

            Configure <AbpDistributedCacheOptions>(options =>
            {
                // 最好统一命名,不然某个缓存变动其他应用服务有例外发生
                options.KeyPrefix = "LINGYUN.Abp.Application";
                // 滑动过期30天
                options.GlobalCacheEntryOptions.SlidingExpiration = TimeSpan.FromDays(30);
                // 绝对过期60天
                options.GlobalCacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);
            });

            Configure <RedisCacheOptions>(options =>
            {
                var redisConfig = ConfigurationOptions.Parse(options.Configuration);
                options.ConfigurationOptions = redisConfig;
                options.InstanceName         = configuration["Redis:InstanceName"];
            });

            // Swagger
            context.Services.AddSwaggerGen(
                options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "MessageService API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description  = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Scheme       = "bearer",
                    Type         = SecuritySchemeType.Http,
                    BearerFormat = "JWT"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            context.Services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    builder
                    .WithOrigins(
                        configuration["App:CorsOrigins"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray()
                        )
                    .WithAbpExposedHeaders()
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });

            Configure <HangfireDashboardRouteOptions>(options =>
            {
                if (configuration.GetSection("Hangfire:Dashboard:WhiteList").Exists())
                {
                    options.WithWhite(
                        configuration["Hangfire:Dashboard:WhiteList"]
                        .Split(",", StringSplitOptions.RemoveEmptyEntries)
                        .Select(o => o.RemovePostFix("/"))
                        .ToArray());
                }

                options.WithOrigins(
                    configuration["App:CorsOrigins"]
                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
                    .Select(o => o.RemovePostFix("/"))
                    .ToArray()
                    );
            });

            // 支持本地化语言类型
            Configure <AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));

                options.Resources
                .Get <MessageServiceResource>()
                .AddVirtualJson("/Localization/HttpApiHost");
            });

            Configure <AbpClaimsMapOptions>(options =>
            {
                options.Maps.TryAdd("name", () => AbpClaimTypes.UserName);
            });

            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority            = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience             = configuration["AuthServer:ApiName"];
            });

            if (!hostingEnvironment.IsDevelopment())
            {
                var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
                context.Services
                .AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "MessageService-Protection-Keys");
            }
        }
예제 #50
0
        public void RedisLabsEnvironmentVariableClientCertificate(bool setEnv)
        {
            try
            {
                if (setEnv)
                {
                    Environment.SetEnvironmentVariable("SERedis_ClientCertPfxPath", RedisLabsPfxPath);
                }
                if (!File.Exists(RedisLabsSslHostFile)) Assert.Inconclusive();
                string hostAndPort = File.ReadAllText(RedisLabsSslHostFile);
                int timeout = 5000;
                if (Debugger.IsAttached) timeout *= 100;
                var options = new ConfigurationOptions
                {
                    EndPoints = { hostAndPort },
                    ConnectTimeout = timeout,
                    AllowAdmin = true,
                    CommandMap = CommandMap.Create(new HashSet<string> {
                    "subscribe", "unsubscribe", "cluster"
                }, false)
                };
                if (!Directory.Exists(Me())) Directory.CreateDirectory(Me());
#if LOGOUTPUT
            ConnectionMultiplexer.EchoPath = Me();
#endif
                options.Ssl = true;
                RedisKey key = Me();
                using (var conn = ConnectionMultiplexer.Connect(options))
                {
                    if (!setEnv) Assert.Fail();

                    var db = conn.GetDatabase();
                    db.KeyDelete(key);
                    string s = db.StringGet(key);
                    Assert.IsNull(s);
                    db.StringSet(key, "abc");
                    s = db.StringGet(key);
                    Assert.AreEqual("abc", s);

                    var latency = db.Ping();
                    Console.WriteLine("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);

                    using (var file = File.Create("RedisLabs.zip"))
                    {
                        conn.ExportConfiguration(file);
                    }
                }
            }
            catch(RedisConnectionException ex)
            {
                if(setEnv || ex.FailureType != ConnectionFailureType.UnableToConnect)
                {
                    throw;
                }
            }
            finally
            {
                Environment.SetEnvironmentVariable("SERedis_ClientCertPfxPath", null);
            }

        }
예제 #51
0
파일: Program.cs 프로젝트: DemureCW/Miki
        public async Task LoadDiscord()
        {
            StackExchangeCachePool pool = new StackExchangeCachePool(
                new ProtobufSerializer(),
                ConfigurationOptions.Parse(Global.Config.RedisConnectionString)
                );

            Global.Client = new Bot(Global.Config.AmountShards, pool, new ClientInformation()
            {
                Name       = "Miki",
                Version    = "0.6.2",
                ShardCount = Global.Config.ShardCount,
                DatabaseConnectionString = Global.Config.ConnString,
                Token = Global.Config.Token
            }, Global.Config.RabbitUrl.ToString());

            EventSystem eventSystem = new EventSystem(new EventSystemConfig()
            {
                Developers        = Global.Config.DeveloperIds,
                ErrorEmbedBuilder = new EmbedBuilder()
                                    .SetTitle($"🚫 Something went wrong!")
                                    .SetColor(new Color(1.0f, 0.0f, 0.0f))
            });

            eventSystem.MessageFilter.AddFilter(new BotFilter());
            eventSystem.MessageFilter.AddFilter(new UserFilter());

            Global.Client.Attach(eventSystem);
            ConfigurationManager mg = new ConfigurationManager();

            var commandMap = new Framework.Events.CommandMap();

            commandMap.OnModuleLoaded += (module) =>
            {
                mg.RegisterType(module.GetReflectedInstance());
            };

            var handler = new SimpleCommandHandler(commandMap);

            handler.AddPrefix(">", true, true);
            handler.AddPrefix("miki.");

            var sessionHandler = new SessionBasedCommandHandler();
            var messageHandler = new MessageListener();

            eventSystem.AddCommandHandler(sessionHandler);
            eventSystem.AddCommandHandler(messageHandler);
            eventSystem.AddCommandHandler(handler);

            commandMap.RegisterAttributeCommands();
            commandMap.Install(eventSystem, Global.Client);

            if (!string.IsNullOrWhiteSpace(Global.Config.SharpRavenKey))
            {
                Global.ravenClient = new SharpRaven.RavenClient(Global.Config.SharpRavenKey);
            }

            handler.OnMessageProcessed += async(cmd, msg, time) =>
            {
                await Task.Yield();

                Log.Message($"{cmd.Name} processed in {time}ms");
            };

            Global.Client.Client.MessageCreate += Bot_MessageReceived;;

            Global.Client.Client.GuildJoin  += Client_JoinedGuild;
            Global.Client.Client.GuildLeave += Client_LeftGuild;
            Global.Client.Client.UserUpdate += Client_UserUpdated;
        }
예제 #52
0
        public void ConnectToSSLServer(bool useSsl, bool specifyHost)
        {
            string host = null;
            
            const string path = @"D:\RedisSslHost.txt"; // because I choose not to advertise my server here!
            if (File.Exists(path)) host = File.ReadLines(path).First();
            if (string.IsNullOrWhiteSpace(host)) Assert.Inconclusive("no ssl host specified at: " + path);

            var config = new ConfigurationOptions
            {
                CommandMap = CommandMap.Create( // looks like "config" is disabled
                    new Dictionary<string, string>
                    {
                        { "config", null },
                        { "cluster", null }
                    }
                ),
                EndPoints = { { host } },
                AllowAdmin = true,
                SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000
            };
            if(useSsl)
            {
                config.Ssl = useSsl;
                if (specifyHost)
                {
                    config.SslHost = host;
                }
                config.CertificateValidation += (sender, cert, chain, errors) =>
                {
                    Console.WriteLine("errors: " + errors);
                    Console.WriteLine("cert issued to: " + cert.Subject);
                    return true; // fingers in ears, pretend we don't know this is wrong
                };
            }

            var configString = config.ToString();
            Console.WriteLine("config: " + configString);
            var clone = ConfigurationOptions.Parse(configString);
            Assert.AreEqual(configString, clone.ToString(), "config string");

            using(var log = new StringWriter())
            using (var muxer = ConnectionMultiplexer.Connect(config, log))
            {
                Console.WriteLine("Connect log:");
                Console.WriteLine(log);
                Console.WriteLine("====");
                muxer.ConnectionFailed += OnConnectionFailed;
                muxer.InternalError += OnInternalError;
                var db = muxer.GetDatabase();
                db.Ping();
                using (var file = File.Create("ssl-" + useSsl + "-" + specifyHost + ".zip"))
                {
                    muxer.ExportConfiguration(file);
                }
                RedisKey key = "SE.Redis";

                const int AsyncLoop = 2000;
                // perf; async
                db.KeyDelete(key, CommandFlags.FireAndForget);
                var watch = Stopwatch.StartNew();
                for (int i = 0; i < AsyncLoop; i++)
                {
                    db.StringIncrement(key, flags: CommandFlags.FireAndForget);
                }
                // need to do this inside the timer to measure the TTLB
                long value = (long)db.StringGet(key);
                watch.Stop();
                Assert.AreEqual(AsyncLoop, value);
                Console.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}",
                    AsyncLoop,
                    (long)watch.ElapsedMilliseconds,
                    (long)(AsyncLoop / watch.Elapsed.TotalSeconds),
                    value);

                // perf: sync/multi-threaded
                TestConcurrent(db, key, 30, 10);
                //TestConcurrent(db, key, 30, 20);
                //TestConcurrent(db, key, 30, 30);
                //TestConcurrent(db, key, 30, 40);
                //TestConcurrent(db, key, 30, 50);
            }
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration      = hostingEnvironment.BuildConfiguration();

            // 配置Ef
            Configure <AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });

            // 加解密
            Configure <AbpStringEncryptionOptions>(options =>
            {
                var encryptionConfiguration = configuration.GetSection("Encryption");
                if (encryptionConfiguration.Exists())
                {
                    options.DefaultPassPhrase = encryptionConfiguration["PassPhrase"] ?? options.DefaultPassPhrase;
                    options.DefaultSalt       = encryptionConfiguration.GetSection("Salt").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["Salt"])
                        : options.DefaultSalt;
                    options.InitVectorBytes = encryptionConfiguration.GetSection("InitVector").Exists()
                        ? Encoding.ASCII.GetBytes(encryptionConfiguration["InitVector"])
                        : options.InitVectorBytes;
                }
            });

            Configure <AbpDistributedCacheOptions>(options =>
            {
                // 最好统一命名,不然某个缓存变动其他应用服务有例外发生
                options.KeyPrefix = "LINGYUN.Abp.Application";
                // 滑动过期30天
                options.GlobalCacheEntryOptions.SlidingExpiration = TimeSpan.FromDays(30);
                // 绝对过期60天
                options.GlobalCacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(60);
            });

            Configure <RedisCacheOptions>(options =>
            {
                var redisConfig = ConfigurationOptions.Parse(options.Configuration);
                options.ConfigurationOptions = redisConfig;
                options.InstanceName         = configuration["Redis:InstanceName"];
            });

            // 多租户
            Configure <AbpMultiTenancyOptions>(options =>
            {
                options.IsEnabled = false;
            });

            Configure <AbpAuditingOptions>(options =>
            {
                options.ApplicationName = "ApiGateWay-Admin";
                // 是否启用实体变更记录
                var entitiesChangedConfig = configuration.GetSection("App:TrackingEntitiesChanged");
                if (entitiesChangedConfig.Exists() && entitiesChangedConfig.Get <bool>())
                {
                    options
                    .EntityHistorySelectors
                    .AddAllEntities();
                }
            });

            //Configure<AbpTenantResolveOptions>(options =>
            //{
            //    options.TenantResolvers.Insert(0, new AuthorizationTenantResolveContributor());
            //});

            // Swagger
            context.Services.AddSwaggerGen(
                options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ApiGateway API", Version = "v1"
                });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description  = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name         = "Authorization",
                    In           = ParameterLocation.Header,
                    Scheme       = "bearer",
                    Type         = SecuritySchemeType.Http,
                    BearerFormat = "JWT"
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            // 支持本地化语言类型
            Configure <AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
            });

            Configure <AbpClaimsMapOptions>(options =>
            {
                options.Maps.TryAdd("name", () => AbpClaimTypes.UserName);
            });

            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority            = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience             = configuration["AuthServer:ApiName"];
            });

            if (!hostingEnvironment.IsDevelopment())
            {
                var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
                context.Services
                .AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "ApiGatewayAdmin-Protection-Keys");
            }

            Configure <AbpAutoMapperOptions>(options =>
            {
                options.AddProfile <ApiGatewayHttpApiHostAutoMapperProfile>(validate: true);
            });
        }
예제 #54
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //add the AutoMapper service:
            //define in it the location of the Mapping profile we want using typeof()
            //the mapping profile we created is in API Project -> Helper folder
            services.AddAutoMapper(typeof(MappingProfiles));



            services.AddControllers();



            //add the DbContext service, while using sqlite, with the configured connection string in appsettings.Development.json
            //   services.AddDbContext<StoreContext>(x => x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
            //also, add the second context we have, AppIdentityContext:
            //   services.AddDbContext<AppIdentityDbContext>(x => {x.UseSqlite(_config.GetConnectionString("IdentityConnection"));});

            /*
             * and since we have 2 contexts now !
             * 1-the one we created in video 17 for the products, brands ,... tables and we called it StoreContext
             * 2-the one we have just created, to hold the identity tables, and we called it AppIdentityDbContext
             * so we have 2 databases, with 2 conenctionstrings  !
             */
            //the above services uses sqlite DB which we used during development,
            //now rewritting those to use postgresql which will be used in our final development stages and production env:
            services.AddDbContext <StoreContext>(x => x.UseNpgsql(_config.GetConnectionString("DefaultConnection")));
            services.AddDbContext <AppIdentityDbContext>(x => { x.UseNpgsql(_config.GetConnectionString("IdentityConnection")); });



            //add the service of Redis:
            //we installed Redis package in the Infrastructure Project which will communicate with it,
            //we will add this service as a singleton service,
            //just like how we used StoreContext (an application DBcontext which we created in the Infrastructure project using EntityFramework)
            //to communicate with the sql DB, we use here a nearly equal concept which is called "IConnectionMultiplexer" but it is already provided by Redis and we do not create it.
            //we used here also a connection string called "Redis" which is existed in our appsettings.json ("Redis": "localhost")
            services.AddSingleton <IConnectionMultiplexer>
            (
                c =>
            {
                var configuration = ConfigurationOptions.Parse(_config.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(configuration));
            }
            );
            //and we used Redis to store customers' baskets and in it basket items.
            //we used for that IBasketRepository and BasketRepository so we need to register these here:
            //we added that in the ApplicationServicesExtensions in the middleware folder,
            //and got that returned in the below sesrvices.AddApplicationServices().



            //bring the service written in the Extentions folder -> ApplicationServicesExtensions class:
            //(we wrote those services there to empty more space in here)
            services.AddApplicationServices();
            //bring the service written in the Extentions folder -> IdentityServiceExtensions:
            //(we wrote those services there to empty more space in here)
            services.AddIdentityServices(_config);
            //pass the above _config property which is of type IConfiguration
            //which allows us to read the appSettings.Development.json and appSettings.json files



            services.AddSwaggerDocumentation();



            //Configure CORS:
            //enable (CORS))Cross origin Resource sharing support on our API so Angular developer can work on what we are returning from our API
            //so we send an appropriate header in our responses to our Anguler clients (API Consumers)
            //it is a mechanism that's used to tell browsers to give a web application running at one origin an access to selected resources from a different origin
            //,and for security reasons, browsers restrict cross origin  HTTP requests initiated from javascript.
            //So if we want to see our results coming back from the API in the browser then we're going to need to send back across origin resource sharing header to enable that to happen.
            services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200"); }); });
            //we specified the link where our angular client will be coming from
            //and basically we are telling our client application if it is running on an unsecure port, we will not return a header that is going to allow the browser to display the returned data
            //then add its middleware below
        }
예제 #55
0
 public void SSLHostInferredFromEndpoints() {
     var options = new ConfigurationOptions() {
         EndPoints = { 
                       { "mycache.rediscache.windows.net", 15000},
                       { "mycache.rediscache.windows.net", 15001 },
                       { "mycache.rediscache.windows.net", 15002 },
                     }
         };
     options.Ssl = true;
     Assert.True(options.SslHost == "mycache.rediscache.windows.net");
     options = new ConfigurationOptions() {
         EndPoints = { 
                       { "121.23.23.45", 15000},
                     }
     };
     Assert.True(options.SslHost == null);
 }
예제 #56
0
        public static ConnectionMultiplexer CreateDefault(
            TextWriter output,
            string clientName    = null, int?syncTimeout           = null, bool?allowAdmin          = null, int?keepAlive  = null,
            int?connectTimeout   = null, string password           = null, string tieBreaker        = null, TextWriter log = null,
            bool fail            = true, string[] disabledCommands = null, string[] enabledCommands = null,
            bool checkConnect    = true, string failMessage        = null,
            string channelPrefix = null, Proxy?proxy               = null,
            string configuration = null, bool logTransactionData   = true,

            [CallerMemberName] string caller = null)
        {
            StringWriter localLog = null;

            if (log == null)
            {
                log = localLog = new StringWriter();
            }
            try
            {
                var config = ConfigurationOptions.Parse(configuration);
                if (disabledCommands != null && disabledCommands.Length != 0)
                {
                    config.CommandMap = CommandMap.Create(new HashSet <string>(disabledCommands), false);
                }
                else if (enabledCommands != null && enabledCommands.Length != 0)
                {
                    config.CommandMap = CommandMap.Create(new HashSet <string>(enabledCommands), true);
                }

                if (Debugger.IsAttached)
                {
                    syncTimeout = int.MaxValue;
                }

                if (channelPrefix != null)
                {
                    config.ChannelPrefix = channelPrefix;
                }
                if (tieBreaker != null)
                {
                    config.TieBreaker = tieBreaker;
                }
                if (password != null)
                {
                    config.Password = string.IsNullOrEmpty(password) ? null : password;
                }
                if (clientName != null)
                {
                    config.ClientName = clientName;
                }
                else if (caller != null)
                {
                    config.ClientName = caller;
                }
                if (syncTimeout != null)
                {
                    config.SyncTimeout = syncTimeout.Value;
                }
                if (allowAdmin != null)
                {
                    config.AllowAdmin = allowAdmin.Value;
                }
                if (keepAlive != null)
                {
                    config.KeepAlive = keepAlive.Value;
                }
                if (connectTimeout != null)
                {
                    config.ConnectTimeout = connectTimeout.Value;
                }
                if (proxy != null)
                {
                    config.Proxy = proxy.Value;
                }
                var watch = Stopwatch.StartNew();
                var task  = ConnectionMultiplexer.ConnectAsync(config, log);
                if (!task.Wait(config.ConnectTimeout >= (int.MaxValue / 2) ? int.MaxValue : config.ConnectTimeout * 2))
                {
                    task.ContinueWith(x =>
                    {
                        try
                        {
                            GC.KeepAlive(x.Exception);
                        }
                        catch
                        { }
                    }, TaskContinuationOptions.OnlyOnFaulted);
                    throw new TimeoutException("Connect timeout");
                }
                watch.Stop();
                if (output != null)
                {
                    Log(output, "Connect took: " + watch.ElapsedMilliseconds + "ms");
                }
                var muxer = task.Result;
                if (checkConnect && (muxer == null || !muxer.IsConnected))
                {
                    // If fail is true, we throw.
                    Assert.False(fail, failMessage + "Server is not available");
                    Skip.Inconclusive(failMessage + "Server is not available");
                }
                if (output != null)
                {
                    muxer.MessageFaulted += (msg, ex, origin) =>
                    {
                        output?.WriteLine($"Faulted from '{origin}': '{msg}' - '{(ex == null ? "(null)" : ex.Message)}'");
                        if (ex != null && ex.Data.Contains("got"))
                        {
                            output?.WriteLine($"Got: '{ex.Data["got"]}'");
                        }
                    };
                    muxer.Connecting += (e, t) => output?.WriteLine($"Connecting to {Format.ToString(e)} as {t}");
                    if (logTransactionData)
                    {
                        muxer.TransactionLog += msg => output?.WriteLine("tran: " + msg);
                    }
                    muxer.InfoMessage  += msg => output?.WriteLine(msg);
                    muxer.Resurrecting += (e, t) => output?.WriteLine($"Resurrecting {Format.ToString(e)} as {t}");
                    muxer.Closing      += complete => output?.WriteLine(complete ? "Closed" : "Closing...");
                }
                return(muxer);
            }
            catch
            {
                if (localLog != null)
                {
                    output?.WriteLine(localLog.ToString());
                }
                throw;
            }
        }
예제 #57
0
 public FileManager(Instance instance)
 {
     _instance = instance ?? throw new ArgumentNullException(nameof(instance));
     _config   = _instance.Config;
 }
예제 #58
0
 public RedisService(ConfigurationOptions opts)
 {
     connection = ConnectionMultiplexer.Connect(opts);
     db         = connection.GetDatabase();
 }
예제 #59
0
        public async Task ConnectToSSLServer(bool useSsl, bool specifyHost)
        {
            var    server   = TestConfig.Current.SslServer;
            int?   port     = TestConfig.Current.SslPort;
            string password = "";
            bool   isAzure  = false;

            if (string.IsNullOrWhiteSpace(server) && useSsl)
            {
                // we can bounce it past azure instead?
                server   = TestConfig.Current.AzureCacheServer;
                password = TestConfig.Current.AzureCachePassword;
                port     = null;
                isAzure  = true;
            }
            Skip.IfNoConfig(nameof(TestConfig.Config.SslServer), server);

            var config = new ConfigurationOptions
            {
                AllowAdmin  = true,
                SyncTimeout = Debugger.IsAttached ? int.MaxValue : 5000,
                Password    = password,
            };
            var map = new Dictionary <string, string>
            {
                ["config"] = null // don't rely on config working
            };

            if (!isAzure)
            {
                map["cluster"] = null;
            }
            config.CommandMap = CommandMap.Create(map);
            if (port != null)
            {
                config.EndPoints.Add(server, port.Value);
            }
            else
            {
                config.EndPoints.Add(server);
            }

            if (useSsl)
            {
                config.Ssl = useSsl;
                if (specifyHost)
                {
                    config.SslHost = server;
                }
                config.CertificateValidation += (sender, cert, chain, errors) =>
                {
                    Log("errors: " + errors);
                    Log("cert issued to: " + cert.Subject);
                    return(true); // fingers in ears, pretend we don't know this is wrong
                };
            }

            var configString = config.ToString();

            Log("config: " + configString);
            var clone = ConfigurationOptions.Parse(configString);

            Assert.Equal(configString, clone.ToString());

            using (var log = new StringWriter())
                using (var muxer = ConnectionMultiplexer.Connect(config, log))
                {
                    Log("Connect log:");
                    lock (log)
                    {
                        Log(log.ToString());
                    }
                    Log("====");
                    muxer.ConnectionFailed += OnConnectionFailed;
                    muxer.InternalError    += OnInternalError;
                    var db = muxer.GetDatabase();
                    await db.PingAsync().ForAwait();

                    using (var file = File.Create("ssl-" + useSsl + "-" + specifyHost + ".zip"))
                    {
                        muxer.ExportConfiguration(file);
                    }
                    RedisKey key = "SE.Redis";

                    const int AsyncLoop = 2000;
                    // perf; async
                    await db.KeyDeleteAsync(key).ForAwait();

                    var watch = Stopwatch.StartNew();
                    for (int i = 0; i < AsyncLoop; i++)
                    {
                        try
                        {
                            await db.StringIncrementAsync(key, flags : CommandFlags.FireAndForget).ForAwait();
                        }
                        catch (Exception ex)
                        {
                            Log($"Failure on i={i}: {ex.Message}");
                            throw;
                        }
                    }
                    // need to do this inside the timer to measure the TTLB
                    long value = (long)await db.StringGetAsync(key).ForAwait();

                    watch.Stop();
                    Assert.Equal(AsyncLoop, value);
                    Log("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}",
                        AsyncLoop,
                        (long)watch.ElapsedMilliseconds,
                        (long)(AsyncLoop / watch.Elapsed.TotalSeconds),
                        value);

                    // perf: sync/multi-threaded
                    // TestConcurrent(db, key, 30, 10);
                    //TestConcurrent(db, key, 30, 20);
                    //TestConcurrent(db, key, 30, 30);
                    //TestConcurrent(db, key, 30, 40);
                    //TestConcurrent(db, key, 30, 50);
                }
        }
예제 #60
0
        private static void set_global_options(IList <string> args, ChocolateyConfiguration config)
        {
            ConfigurationOptions.parse_arguments_and_update_configuration(
                args,
                config,
                (option_set) =>
            {
                option_set
                .Add("d|debug",
                     "Debug - Run in Debug Mode.",
                     option => config.Debug = option != null)
                .Add("v|verbose",
                     "Verbose - See verbose messaging.",
                     option => config.Verbose = option != null)
                .Add("acceptlicense|accept-license",
                     "AcceptLicense - Accept license dialogs automatically.",
                     option => config.AcceptLicense = option != null)
                .Add("y|yes|confirm",
                     "Confirm all prompts - Chooses default answer instead of prompting. Implies --accept-license",
                     option =>
                {
                    config.PromptForConfirmation = option == null;
                    config.AcceptLicense         = option != null;
                })
                .Add("f|force",
                     "Force - force the behavior",
                     option => config.Force = option != null)
                .Add("noop|whatif|what-if",
                     "NoOp - Don't actually do anything.",
                     option => config.Noop = option != null)
                .Add("r|limitoutput|limit-output",
                     "LimitOuptut - Limit the output to essential information",
                     option => config.RegularOuptut = option == null)
                .Add("execution-timeout=",
                     "CommandExecutionTimeoutSeconds - Override the default execution timeout in the configuration of {0} seconds.".format_with(config.CommandExecutionTimeoutSeconds.to_string()),
                     option => config.CommandExecutionTimeoutSeconds = int.Parse(option))
                .Add("c=|cache=|cachelocation=|cache-location=",
                     "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
                     option => config.CacheLocation = option)
                .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build",
                     "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.",
                     option => config.AllowUnofficialBuild = option != null)
                ;
            },
                (unparsedArgs) =>
            {
                if (!string.IsNullOrWhiteSpace(config.CommandName))
                {
                    // save help for next menu
                    config.HelpRequested = false;
                }
            },
                () => { },
                () =>
            {
                var commandsLog = new StringBuilder();
                foreach (var command in Enum.GetValues(typeof(CommandNameType)).Cast <CommandNameType>())
                {
                    commandsLog.AppendFormat(" * {0}\n", command.get_description_or_value());
                }

                "chocolatey".Log().Info(@"This is a listing of all of the different things you can pass to choco.
");
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "Commands");
                "chocolatey".Log().Info(@"
{1}

Please run chocolatey with `choco command -help` for specific help on 
 each command.
".format_with(config.Information.ChocolateyVersion, commandsLog.ToString()));
                "chocolatey".Log().Info(ChocolateyLoggers.Important, @"How To Pass Options / Switches");
                "chocolatey".Log().Info(@"
You can pass options and switches in the following ways:

 * `-` - except for normal switches (not 1 character) when using option
   blending, see below.
 * `--` - except for one character switches
 * `/`
 * ""Option Blending / Blended Options"": One character switches can be 
   blended. e.g. `-d` (debug), `-f` (force), `-v` (verbose), and `-y` 
   (confirm yes) can be blended as `-dfvy`, but you must use `--` for 
   all other normal options/switches e.g. `--version` instead of 
   `-version`. If you don't do this, you may have unintended results.
 * ""Use Equals"": You can also include or not include an equals sign 
   `=` between options and values. And quote the values.
 * Options and switches apply to all items passed, so if you are 
   installing multiple packages, and you use `--version=1.0.0`, it is 
   going to look for and try to install version 1.0.0 of every package 
   passed. So please split out multiple package calls when wanting to 
   pass specific options.
 * When you need to quote things, such as when using spaces in option 
   values, please use single quote marks ('). In cmd.exe, you can also 
   use double double quotes (i.e. """"yo""""). This is due to the hand 
   off to PowerShell - seems to strip off the outer set of quotes. 
   TODO: TEST THIS, MAY NOT BE RELEVANT NOW.
");
                "chocolatey".Log().Info(ChocolateyLoggers.Important, "Default Options and Switches");
            });
        }