public void Clear_only_clears_cache()
        {
            using (var db = ConnectionString.OpenDbConnection())
            using (var dbCmd = db.CreateCommand())
            {
                dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(false);

                var cacheClient = new MemoryCacheClient();

                var ormCache = new OrmLitePersistenceProviderCache(cacheClient, db);

                var row = ModelWithFieldsOfDifferentTypes.Create(1);

                ormCache.Store(row);

                var cacheKey = row.CreateUrn();

                var dbRow = dbCmd.GetById<ModelWithFieldsOfDifferentTypes>(row.Id);
                var cacheRow = cacheClient.Get<ModelWithFieldsOfDifferentTypes>(cacheKey);

                ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                ModelWithFieldsOfDifferentTypes.AssertIsEqual(cacheRow, row);

                ormCache.Clear<ModelWithFieldsOfDifferentTypes>(row.Id);

                dbRow = dbCmd.GetById<ModelWithFieldsOfDifferentTypes>(row.Id);
                cacheRow = cacheClient.Get<ModelWithFieldsOfDifferentTypes>(cacheKey);

                ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                Assert.IsNull(cacheRow);
            }
        }
        public void Store_sets_and_updates_both_cache_and_db()
        {
            using (var db = ConnectionString.OpenDbConnection())
                using (var dbCmd = db.CreateCommand())
                {
                    dbCmd.CreateTable <ModelWithFieldsOfDifferentTypes>(false);

                    var cacheClient = new MemoryCacheClient();

                    var ormCache = new OrmLitePersistenceProviderCache(cacheClient, db);

                    var row = ModelWithFieldsOfDifferentTypes.Create(1);

                    ormCache.Store(row);

                    var cacheKey = row.CreateUrn();
                    var dbRow    = dbCmd.GetById <ModelWithFieldsOfDifferentTypes>(row.Id);
                    var cacheRow = cacheClient.Get <ModelWithFieldsOfDifferentTypes>(cacheKey);

                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(cacheRow, row);

                    row.Name = "UpdatedName";
                    ormCache.Store(row);

                    dbRow    = dbCmd.GetById <ModelWithFieldsOfDifferentTypes>(row.Id);
                    cacheRow = cacheClient.Get <ModelWithFieldsOfDifferentTypes>(cacheKey);

                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(cacheRow, row);
                }
        }
Exemple #3
0
            public override void Configure(Funq.Container container)
            {
                Routes
                    .Add<Hello>("/hello")
                    .Add<Hello>("/hello/{Name}");
                helloService = container.Resolve<HelloService>();

                AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {new BasicAuthProvider(), new TwitterAuthProvider(new AppSettings()),});
                //authFeature.HtmlRedirect
                Plugins.Add(authFeature);
                MemoryCacheClient memoryCacheClient = new MemoryCacheClient();
                container.Register<ICacheClient>(memoryCacheClient);

                var userRepository = new InMemoryAuthRepository();
                container.Register<IUserAuthRepository>(userRepository);

                string hash;
                string salt;
                string password = "******";
                new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
                userRepository.CreateUserAuth(
                    new UserAuth {
                        Id = 1,
                        DisplayName = "JoeUser",
                        Email = "*****@*****.**",
                        UserName = "******",
                        FirstName = "Joe",
                        LastName = "User",
                        PasswordHash = hash,
                        Salt = salt,
                    }, password);
                //IHttpResult authenticationRequired = helloService.AuthenticationRequired(); // ????
            }
Exemple #4
0
        public override void InitializeCache()
        {
            var mcc = new MemoryCacheClient();

            SimpleContainer.RegisterInstance <MemoryCacheClient>(mcc);
            SimpleContainer.RegisterInstance <ICacheClient>(mcc);
        }
        public void Clear_only_clears_cache()
        {
            using (var db = ConnectionString.OpenDbConnection())
                using (var dbCmd = db.CreateCommand())
                {
                    dbCmd.CreateTable <ModelWithFieldsOfDifferentTypes>(false);

                    var cacheClient = new MemoryCacheClient();

                    var ormCache = new OrmLitePersistenceProviderCache(cacheClient, db);

                    var row = ModelWithFieldsOfDifferentTypes.Create(1);

                    ormCache.Store(row);

                    var cacheKey = row.CreateUrn();

                    var dbRow    = dbCmd.GetById <ModelWithFieldsOfDifferentTypes>(row.Id);
                    var cacheRow = cacheClient.Get <ModelWithFieldsOfDifferentTypes>(cacheKey);

                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(cacheRow, row);

                    ormCache.Clear <ModelWithFieldsOfDifferentTypes>(row.Id);

                    dbRow    = dbCmd.GetById <ModelWithFieldsOfDifferentTypes>(row.Id);
                    cacheRow = cacheClient.Get <ModelWithFieldsOfDifferentTypes>(cacheKey);

                    ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                    Assert.IsNull(cacheRow);
                }
        }
 public void SetupFixture()
 {
     HttpContext.Current = null; //This needs to be cleared because EmbeddableDocumentStore will try to set a virtual directory via HttpContext.Current.Request.ApplicationPath, which is null
     Cache = new MemoryCacheClient();
     StructureMap.ObjectFactory.Inject(typeof(ICacheClient), Cache);
     AutomapperConfig.CreateMappings();
     if (RouteTable.Routes == null || RouteTable.Routes.Count == 0)
         RouteConfig.RegisterRoutes(RouteTable.Routes);
 }
Exemple #7
0
        public virtual void SetupFixture()
        {
            Cache = new MemoryCacheClient();
            ObjectFactory.Inject(typeof(ICacheClient), Cache);

            Db         = ObjectFactory.GetInstance <IDbConnection>();
            Generator  = new Generator(Db);
            Terminator = new Terminator(Db);
        }
Exemple #8
0
        public virtual void SetupFixture()
        {
            Cache = new MemoryCacheClient();
            ObjectFactory.Inject(typeof(ICacheClient), Cache);

            Db = ObjectFactory.GetInstance<IDbConnection>();
            Generator = new Generator(Db);
            Terminator = new Terminator(Db);
        }
        public virtual void SetupFixture()
        {
            HttpContext.Current = null; //This needs to be cleared because EmbeddableDocumentStore will try to set a virtual directory via HttpContext.Current.Request.ApplicationPath, which is null
            Store = new EmbeddableDocumentStore { RunInMemory = true }.Initialize();
            ((DocumentStore) Store).RegisterListener(new ForceNonStaleQueryListener());
            IndexCreation.CreateIndexes(typeof(User).Assembly, Store);
            StructureMap.ObjectFactory.Inject(typeof(IDocumentStore), Store);
            RavenConfig.Bootstrap();

            Cache = new MemoryCacheClient();
            StructureMap.ObjectFactory.Inject(typeof(ICacheClient), Cache);
            AutomapperConfig.CreateMappings();
            if (RouteTable.Routes == null || RouteTable.Routes.Count == 0)
                RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
        public override void Configure(Container container)
        {
            //Configure cache client - we're just going to use
            // another memory cache client instance for session storage
            ICacheClient fallbackCacheClient = new MemoryCacheClient();
            ICacheClient sessionCacheClient  = new MemoryCacheClient();

            IRoutedCacheClient routedCacheClient = new DefaultRoutedCacheClient(fallbackCacheClient);

            routedCacheClient.PushServiceStackSessionCacheClient(sessionCacheClient);

            container.Register <ICacheClient>(routedCacheClient);
            container.Register <ICacheClientExtended>(routedCacheClient);

            //Register session feature
            Plugins.Add(new SessionFeature());
        }
Exemple #11
0
        public static void Configure(ServiceStackHost appHost, Container container)
        {
            var appSettings = new AppSettings();

            var auth = new AuthFeature(() => new CustomUserSession(),
                                       new IAuthProvider[]
            {
                new CustomBasicAuthProvider(),
                new CredentialsAuthProvider(appSettings)
                {
                    SessionExpiry = TimeSpan.FromMinutes(30)
                }
            },
                                       "/login")
            {
                GenerateNewSessionCookiesOnAuthentication = false,
            };

            appHost.Plugins.Add(auth);

            IUserAuthRepository authRepository = new InMemoryAuthRepository();
            ICacheClient        cacheClient    = new MemoryCacheClient();

            var testUser = authRepository.CreateUserAuth(new UserAuth {
                Email = "*****@*****.**"
            }, "a");


            //IoC registrations
            container.Register(cacheClient);
            container.Register(authRepository);


            var hostConfig = new HostConfig
            {
#if DEBUG || STAGING || UAT
                DebugMode = true,
#endif
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    MimeTypes.Csv
                },
            };


            appHost.SetConfig(hostConfig);
        }
 /// <summary>
 /// 清理指定缓存
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public JsonResult _ClearCache(string name)
 {
     try
     {
         if (!string.IsNullOrEmpty(name))
         {
             var cache = MemoryCacheClient.GetInstance(name);
             if (cache != null)
             {
                 cache.RemoveAll();
             }
         }
         return(Json(AjaxResult.Success(name + ":清理完成!")));
     }
     catch (Exception e)
     {
         return(Json(AjaxResult.Error(name + ":清理失败,原因:" + e.Message)));
     }
 }
        public override int Run(string[] remainingArguments)
        {
            ICacheClient client = new MemoryCacheClient();
            var api = new TeamCityApi(new CachingThreadSafeAuthenticatedRestClient(new MemoryCacheClient(), _serverName, _teamCityAuthToken), client);

            var buildPackageCache = string.IsNullOrEmpty(_buildPackageCacheFile) ? null : new PackageBuildMappingCache(_buildPackageCacheFile);

            var issueDetailResolver = new IssueDetailResolver(CreateExternalIssueResolvers());

            var resolver = new AggregateBuildDeltaResolver(api, issueDetailResolver, new PackageChangeComparator(), buildPackageCache, new ConcurrentBag<NuGetPackageChange>());
            _changeManifest = string.IsNullOrEmpty(_buildType)
                ? resolver.CreateChangeManifestFromBuildTypeName(_projectName, _buildName,_referenceBuild, _from, _to, _useBuildSystemIssueResolution, _recurse, _branchName)
                : resolver.CreateChangeManifestFromBuildTypeId(_buildType, _referenceBuild, _from, _to, _useBuildSystemIssueResolution, _recurse, _branchName);

            OutputChanges(CreateOutputRenderers(), new List<Action<string>> {Console.Write, a =>
                {
                    if (!string.IsNullOrEmpty(_outputFileName))
                        File.WriteAllText(_outputFileName, a);
                }});
            return 0;
        }
 /// <summary>
 /// 清理所有缓存
 /// </summary>
 /// <returns></returns>
 public JsonResult _ClearAll()
 {
     try
     {
         //清理所有缓存空间
         var allCaches = MemoryCacheClient.GetAllInstanceName();
         foreach (var name in allCaches)
         {
             var cache = MemoryCacheClient.GetInstance(name);
             if (cache != null)
             {
                 cache.RemoveAll();
             }
         }
         return(Json(AjaxResult.Success("清理全部完成!")));
     }
     catch (Exception e)
     {
         return(Json(AjaxResult.Error("清理全部失败,原因:" + e.Message)));
     }
 }
        public override void Configure(Container container)
        {
            // Set global headers
            SetConfig(
                new EndpointHostConfig
                {
                    GlobalResponseHeaders =
                    {
                        {"Access-Control-Allow-Origin", "*"},
                        {"Access-Control-Allow-Method", "GET, OPTIONS"}
                    },
                    EnableFeatures = Feature.All.Remove(Feature.All).Add(Feature.Xml | Feature.Json),
                }
            );

            // -- Example where every request is intercepted to return HttpStatusCode.Gone
            //ResponseFilters.Add((request, response, item) =>{
            //    response.StatusCode = (int)HttpStatusCode.Gone;
            //});

            // Register Dependencies
            // Example where I have set up an instance of a repository that reads from a db here
            // container.Register<IDbRepository<Artist>>(new ArtistDbRepository(new DatabaseQuery()));

            container.Register<IDbRepository<Artist>>(new ArtistWrapperRepository());
            container.Register<IDbRepository<Release>>(new ReleaseWrapperRepository());

            // -- Example setup of a redis cache client here
            // var cacheClient = new RedisClient("localhost", 6379);
            var cacheClient = new MemoryCacheClient();
            container.Register<ICacheClient>(cacheClient);

            // Register "routes"
            Routes
                .Add<Artist>("/artist/details")
                .Add<Artist>("/artist/details/{Id}")
                .Add<Release>("/release/details")
                .Add<Release>("/release/details/{ReleaseId}");
        }
Exemple #16
0
            public override void Configure(Funq.Container container)
            {
                Routes
                .Add <Hello>("/hello")
                .Add <Hello>("/hello/{Name}");
                helloService = container.Resolve <HelloService>();

                AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(), new TwitterAuthProvider(new AppSettings()), });

                //authFeature.HtmlRedirect
                Plugins.Add(authFeature);
                MemoryCacheClient memoryCacheClient = new MemoryCacheClient();

                container.Register <ICacheClient>(memoryCacheClient);

                var userRepository = new InMemoryAuthRepository();

                container.Register <IUserAuthRepository>(userRepository);

                string hash;
                string salt;
                string password = "******";

                new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
                userRepository.CreateUserAuth(
                    new UserAuth {
                    Id           = 1,
                    DisplayName  = "JoeUser",
                    Email        = "*****@*****.**",
                    UserName     = "******",
                    FirstName    = "Joe",
                    LastName     = "User",
                    PasswordHash = hash,
                    Salt         = salt,
                }, password);
                //IHttpResult authenticationRequired = helloService.AuthenticationRequired(); // ????
            }
Exemple #17
0
        public override ServiceStackHost Init()
        {
            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.DefaultConnectionLimit = 1000;

            var conf = NLog.Config.ConfigurationItemFactory.Default;

            conf.LayoutRenderers.RegisterDefinition("logsdir", typeof(LogsDir));
            conf.LayoutRenderers.RegisterDefinition("Instance", typeof(Library.Logging.Instance));
            NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration($"{AppDomain.CurrentDomain.BaseDirectory}/logging.config");

            LogManager.LogFactory = new global::ServiceStack.Logging.NLogger.NLogFactory();
            AppDomain.CurrentDomain.UnhandledException   += UnhandledExceptionTrapper;
            AppDomain.CurrentDomain.FirstChanceException += ExceptionTrapper;
            NServiceBus.Logging.LogManager.Use <NServiceBus.NLogFactory>();


            IRedisClientsManager redisClient = null;
            ICacheClient         cacheClient;
            IServerEvents        serverEvents;
            var connectionString = ConfigurationManager.ConnectionStrings["Redis"];

            if (connectionString == null)
            {
                cacheClient  = new MemoryCacheClient();
                serverEvents = new MemoryServerEvents
                {
                    IdleTimeout = TimeSpan.FromSeconds(30),
                    NotifyChannelOfSubscriptions = false
                };
            }
            else
            {
                redisClient  = new BasicRedisClientManager(connectionString.ConnectionString);
                cacheClient  = new RedisClientManagerCacheClient(redisClient);
                serverEvents = new RedisServerEvents(redisClient)
                {
                    Timeout = TimeSpan.FromSeconds(30),
                    NotifyChannelOfSubscriptions = false,
                };
            }

            IDbConnectionFactory sql = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
            var connectionStringSql  = ConfigurationManager.ConnectionStrings["SQL"];

            if (connectionStringSql != null)
            {
                sql = new OrmLiteConnectionFactory(connectionStringSql.ConnectionString, SqlServer2012Dialect.Provider)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                };
            }

            var pulse  = ConfigureDemo();
            var rabbit = ConfigureRabbit();

            ConfigureMetrics();


            _container = new Container(x =>
            {
                if (redisClient != null)
                {
                    x.For <IRedisClientsManager>().Use(redisClient);
                }

                x.For <IDbConnectionFactory>().Use(sql);
                x.For <ISubscriptionStorage>().Use <MssqlStorage>();


                x.For <IManager>().Use <Manager>();
                x.For <IFuture>().Use <Future>().Singleton();
                x.For <ICacheClient>().Use(cacheClient);
                x.For <IServerEvents>().Use(serverEvents);
                x.For <ISubscriptionManager>().Use <SubscriptionManager>().Singleton();
                x.For <IDemo>().Use(pulse);
                x.For <IConnection>().Use(rabbit);


                x.Scan(y =>
                {
                    y.TheCallingAssembly();
                    y.AssembliesFromApplicationBaseDirectory((assembly) => assembly.FullName.StartsWith("Presentation.ServiceStack"));

                    y.WithDefaultConventions();
                    y.AddAllTypesOf <ISetup>();
                    y.AddAllTypesOf <ICommandMutator>();

                    y.ConnectImplementationsToTypesClosing(typeof(Q.IChange <,>));
                });
            });

            // Do this before bus starts
            InitiateSetup();
            SetupApplication().Wait();

            var bus = InitBus().Result;

            _container.Configure(x => x.For <IMessageSession>().Use(bus).Singleton());

            return(base.Init());
        }
Exemple #18
0
 /// <summary>
 /// 默认Default缓存空间
 /// </summary>
 public BaseCacheStorage()
 {
     _cache = MemoryCacheClient.GetInstance(CacheArea);
 }
Exemple #19
0
 /// <summary>
 /// 自定义缓存空间
 /// </summary>
 /// <param name="name"></param>
 public BaseCacheStorage(string name)
 {
     _cache = MemoryCacheClient.GetInstance(name);
 }
Exemple #20
0
 public MemoryCacheProvider(int?maxDurationSeconds = null)
 {
     this.client = new MemoryCacheClient(maxDurationSeconds);
 }
 public void TestFixtureTearDown()
 {
     cache.Dispose();
     cache = null;
 }
 public void TestFixtureSetUp()
 {
     cache = new MemoryCacheClient();
 }
        public void Store_sets_and_updates_both_cache_and_db()
        {
            using (var db = ConnectionString.OpenDbConnection())
            using (var dbCmd = db.CreateCommand())
            {
                dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(false);

                var cacheClient = new MemoryCacheClient();

                var ormCache = new OrmLitePersistenceProviderCache(cacheClient, db);

                var row = ModelWithFieldsOfDifferentTypes.Create(1);

                ormCache.Store(row);

                var cacheKey = row.CreateUrn();
                var dbRow = dbCmd.GetById<ModelWithFieldsOfDifferentTypes>(row.Id);
                var cacheRow = cacheClient.Get<ModelWithFieldsOfDifferentTypes>(cacheKey);

                ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                ModelWithFieldsOfDifferentTypes.AssertIsEqual(cacheRow, row);

                row.Name = "UpdatedName";
                ormCache.Store(row);

                dbRow = dbCmd.GetById<ModelWithFieldsOfDifferentTypes>(row.Id);
                cacheRow = cacheClient.Get<ModelWithFieldsOfDifferentTypes>(cacheKey);

                ModelWithFieldsOfDifferentTypes.AssertIsEqual(dbRow, row);
                ModelWithFieldsOfDifferentTypes.AssertIsEqual(cacheRow, row);
            }
        }
 public void TestFixtureTearDown()
 {
     cache.Dispose();
     cache = null;
 }
 public void TestFixtureSetUp()
 {
     cache = new MemoryCacheClient();
 }
Exemple #26
0
        public override ServiceStackHost Init()
        {
            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.DefaultConnectionLimit = 1000;

            var conf = NLog.Config.ConfigurationItemFactory.Default;

            conf.LayoutRenderers.RegisterDefinition("logsdir", typeof(LogsDir));
            conf.LayoutRenderers.RegisterDefinition("Domain", typeof(Library.Logging.Domain));
            NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration($"{AppDomain.CurrentDomain.BaseDirectory}/logging.config");

            LogManager.LogFactory = new global::ServiceStack.Logging.NLogger.NLogFactory();
            AppDomain.CurrentDomain.UnhandledException   += UnhandledExceptionTrapper;
            AppDomain.CurrentDomain.FirstChanceException += ExceptionTrapper;
            NServiceBus.Logging.LogManager.Use <NServiceBus.NLogFactory>();


            IRedisClientsManager redisClient = null;
            ICacheClient         cacheClient;
            IServerEvents        serverEvents;
            var connectionString = ConfigurationManager.ConnectionStrings["Redis"];

            if (connectionString == null)
            {
                cacheClient  = new MemoryCacheClient();
                serverEvents = new MemoryServerEvents
                {
                    IdleTimeout = TimeSpan.FromSeconds(30),
                    NotifyChannelOfSubscriptions = false
                };
            }
            else
            {
                redisClient  = new BasicRedisClientManager(connectionString.ConnectionString);
                cacheClient  = new RedisClientManagerCacheClient(redisClient);
                serverEvents = new RedisServerEvents(redisClient)
                {
                    Timeout = TimeSpan.FromSeconds(30),
                    NotifyChannelOfSubscriptions = false,
                };
            }

            IDbConnectionFactory sql = null;
            var connectionStringSQL  = ConfigurationManager.ConnectionStrings["SQL"];

            if (connectionStringSQL != null)
            {
                sql = new OrmLiteConnectionFactory(connectionStringSQL.ConnectionString, SqlServer2012Dialect.Provider)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                };
            }



            _container = new Container(x =>
            {
                if (redisClient != null)
                {
                    x.For <IRedisClientsManager>().Use(redisClient);
                }
                if (sql != null)
                {
                    x.For <IDbConnectionFactory>().Use(sql);
                    x.For <ISubscriptionStorage>().Use <MSSQLStorage>();
                }
                else
                {
                    x.For <ISubscriptionStorage>().Use <MemoryStorage>();
                }

                x.For <IManager>().Use <Manager>();
                x.For <IFuture>().Use <Future>().Singleton();
                x.For <ICacheClient>().Use(cacheClient);
                x.For <IServerEvents>().Use(serverEvents);
                x.For <ISubscriptionManager>().Use <SubscriptionManager>().Singleton();

                x.Scan(y =>
                {
                    AllAssemblies.Matching("Presentation.ServiceStack").ToList().ForEach(a => y.Assembly(a));

                    y.WithDefaultConventions();
                    y.AddAllTypesOf <ISetup>();
                });
            });

            // Do this before bus starts
            InitiateSetup();
            SetupApplication();

            var config = new BusConfiguration();

            Logger.Info("Initializing Service Bus");
            config.LicensePath(ConfigurationManager.AppSettings["license"]);

            var endpoint = ConfigurationManager.AppSettings["endpoint"];

            if (string.IsNullOrEmpty(endpoint))
            {
                endpoint = "application.servicestack";
            }

            config.EndpointName(endpoint);

            config.EnableInstallers();
            config.UsePersistence <InMemoryPersistence>();
            config.UseContainer <StructureMapBuilder>(c => c.ExistingContainer(_container));

            config.DisableFeature <Sagas>();
            config.DisableFeature <SecondLevelRetries>();
            // Important to not subscribe to messages as we receive them from the event store
            config.DisableFeature <AutoSubscribe>();

            config.UseTransport <RabbitMQTransport>()
            .CallbackReceiverMaxConcurrency(36)
            .UseDirectRoutingTopology()
            .ConnectionStringName("RabbitMq");

            config.Transactions().DisableDistributedTransactions();
            //config.DisableDurableMessages();

            config.UseSerialization <NewtonsoftSerializer>();

            config.EnableFeature <Aggregates.Feature>();



            if (Logger.IsDebugEnabled)
            {
                config.Pipeline.Register <LogIncomingRegistration>();
            }

            var bus = Bus.Create(config).Start();

            _container.Configure(x => x.For <IBus>().Use(bus).Singleton());

            return(base.Init());
        }
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new Log4NetFactory(true);

            container.Register(_dbConnectionFactory);
            var basicAuthProvider = new BasicAuthProvider();

            container.Register(basicAuthProvider);

            Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { basicAuthProvider, }, SystemConstants.LoginUrl));

            var userRepo = new OrmLiteAuthRepository(_dbConnectionFactory);

            container.Register <IAuthRepository>(userRepo);

            var cacheClient = new MemoryCacheClient();

            container.Register(cacheClient);

            var currencyTypeRepository = new CurrencyTypeRepository {
                DbConnectionFactory = _dbConnectionFactory
            };
            var transactionTypeRepository = new TransactionTypeRepository {
                DbConnectionFactory = _dbConnectionFactory
            };
            var transactionStatusTypeRepository = new TransactionStatusTypeRepository {
                DbConnectionFactory = _dbConnectionFactory
            };
            var transactionNotificationStatusTypeRepository = new TransactionNotificationStatusTypeRepository {
                DbConnectionFactory = _dbConnectionFactory
            };
            var transactionRepository = new TransactionRepository {
                DbConnectionFactory = _dbConnectionFactory
            };

            var currencyTypeLogic = new CurrencyTypeLogic {
                Repository = currencyTypeRepository
            };
            var transactionTypeLogic = new TransactionTypeLogic {
                Repository = transactionTypeRepository
            };
            var transactionStatusTypeLogic = new TransactionStatusTypeLogic {
                Repository = transactionStatusTypeRepository
            };
            var transactionNotificationStatusTypeLogic = new TransactionNotificationStatusTypeLogic {
                Repository = transactionNotificationStatusTypeRepository
            };
            var transactionLogic = new TransactionLogic {
                Repository = transactionRepository
            };

            container.Register <IRest <CurrencyType, GetCurrencyTypes> >(currencyTypeLogic);
            container.Register <IRest <TransactionType, GetTransactionTypes> >(transactionTypeLogic);
            container.Register <IRest <TransactionStatusType, GetTransactionStatusTypes> >(transactionStatusTypeLogic);
            container.Register <IRest <TransactionNotificationStatusType, GetTransactionNotificationStatusTypes> >(transactionNotificationStatusTypeLogic);
            container.Register <IRest <Transaction, GetTransactions> >(transactionLogic);

            CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => pathInfo.StartsWith("/favicon.ico") ? new FavIconHandler() : null);

            var redisLocation = ConfigurationManager.AppSettings["ReddisService"];

            Container.Register <IRedisClientsManager>(new PooledRedisClientManager(redisLocation));
            var mqService         = new RedisMqServer(container.Resolve <IRedisClientsManager>());
            var messagingHandlers = new MessageService {
                Log = new Logger(typeof(MessageService).Name)
            };


            Func <IMessage, IMessage> filterSecureRequests = (message) =>
            {
                /*
                 * var tag = message.Tag;
                 *
                 * if (string.IsNullOrWhiteSpace(tag))
                 *  return message;
                 *
                 * if (tag.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase))
                 * {
                 *  var creds = Encoding.UTF8.GetString(Convert.FromBase64String(tag.Substring(5)));
                 *
                 *  var i = creds.IndexOf(':');
                 *  var userName = creds.Substring(0, i);
                 *  var userPass = creds.Substring(i + 1);
                 *
                 *
                 *  if (userName != SystemConstants.AllowedUser || userPass != SystemConstants.AllowedPass)
                 *  {
                 *      message.Tag = null;
                 *      return message;
                 *  }
                 *
                 *  _currentSessionGuid = Guid.NewGuid();
                 *  var sessionKey = userName + "/" + _currentSessionGuid.ToString("N");
                 *
                 *  SessionContext = new SessionContext { SessionKey = sessionKey, Username = userName };
                 *  container.Register(SessionContext);
                 *  message.Tag = sessionKey;
                 *  return message;
                 * }
                 *
                 * message.Tag = null;*/

                return(message);
            };

            mqService.RequestFilter = filterSecureRequests;


            Func <IMessage <Transaction>, PostResponse <Transaction> > handlePostTransactions = (message) =>
            {
                var service = new TransactionWebService {
                    Logic = transactionLogic
                };
                var request = new BasicRequest {
                    Message = message, Dto = message.GetBody()
                };
                var response = new BasicResponse(request);

                //userRepo.TryAuthenticate()

                service.SessionFactory.GetOrCreateSession(request, response);
                var session = service.GetSession();



                session.UserName = "******";


                var results = new PostResponse <Transaction> {
                    Result = (Transaction)service.Post(message.GetBody())
                };
                return(results);
            };


            // Dto Get Operations

            mqService.RegisterHandler <GetCurrencyTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), currencyTypeLogic));
            mqService.RegisterHandler <GetTransactions>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionLogic));
            mqService.RegisterHandler <GetTransactionStatusTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionStatusTypeLogic));
            mqService.RegisterHandler <GetTransactionNotificationStatusTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionNotificationStatusTypeLogic));
            mqService.RegisterHandler <GetTransactionTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionTypeLogic));

            // Dto Post Operations
            mqService.RegisterHandler <CurrencyType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), currencyTypeLogic.Post));

            mqService.RegisterHandler <Transaction>(handlePostTransactions);
            mqService.RegisterHandler <TransactionStatusType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), transactionStatusTypeLogic.Post));
            mqService.RegisterHandler <TransactionNotificationStatusType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), transactionNotificationStatusTypeLogic.Post));
            mqService.RegisterHandler <TransactionType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), transactionTypeLogic.Post));

            // Dto Put Opertations
            mqService.RegisterHandler <DeleteCurrencyType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), currencyTypeLogic));
            mqService.RegisterHandler <DeleteTransaction>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionLogic));
            mqService.RegisterHandler <DeleteTransactionStatusType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionStatusTypeLogic));
            mqService.RegisterHandler <DeleteTransactionNotificationStatusType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionNotificationStatusTypeLogic));
            mqService.RegisterHandler <DeleteTransactionType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionTypeLogic));

            mqService.Start();
        }
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new Log4NetFactory(true);

            container.Register(_dbConnectionFactory);
            var basicAuthProvider = new BasicAuthProvider();
            container.Register(basicAuthProvider);

            Plugins.Add(new AuthFeature( () => new AuthUserSession(), new IAuthProvider[] {basicAuthProvider, }, SystemConstants.LoginUrl ));

            var userRepo = new OrmLiteAuthRepository(_dbConnectionFactory);
            container.Register<IAuthRepository>(userRepo);

            var cacheClient = new MemoryCacheClient();
            container.Register(cacheClient);

            var currencyTypeRepository = new CurrencyTypeRepository { DbConnectionFactory = _dbConnectionFactory };
            var transactionTypeRepository = new TransactionTypeRepository { DbConnectionFactory = _dbConnectionFactory };
            var transactionStatusTypeRepository = new TransactionStatusTypeRepository { DbConnectionFactory = _dbConnectionFactory };
            var transactionNotificationStatusTypeRepository = new TransactionNotificationStatusTypeRepository { DbConnectionFactory = _dbConnectionFactory };
            var transactionRepository = new TransactionRepository { DbConnectionFactory = _dbConnectionFactory };

            var currencyTypeLogic = new CurrencyTypeLogic { Repository = currencyTypeRepository };
            var transactionTypeLogic = new TransactionTypeLogic { Repository = transactionTypeRepository };
            var transactionStatusTypeLogic = new TransactionStatusTypeLogic { Repository = transactionStatusTypeRepository };
            var transactionNotificationStatusTypeLogic = new TransactionNotificationStatusTypeLogic { Repository = transactionNotificationStatusTypeRepository };
            var transactionLogic = new TransactionLogic {Repository = transactionRepository};

            container.Register<IRest<CurrencyType, GetCurrencyTypes>>(currencyTypeLogic);
            container.Register<IRest<TransactionType, GetTransactionTypes>>(transactionTypeLogic);
            container.Register<IRest<TransactionStatusType, GetTransactionStatusTypes>>(transactionStatusTypeLogic);
            container.Register<IRest<TransactionNotificationStatusType, GetTransactionNotificationStatusTypes>>(transactionNotificationStatusTypeLogic);
            container.Register<IRest<Transaction, GetTransactions>>(transactionLogic);

            CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => pathInfo.StartsWith("/favicon.ico") ? new FavIconHandler() : null);

            var redisLocation = ConfigurationManager.AppSettings["ReddisService"];
            Container.Register<IRedisClientsManager>(new PooledRedisClientManager(redisLocation));
            var mqService = new RedisMqServer(container.Resolve<IRedisClientsManager>());
            var messagingHandlers = new MessageService { Log = new Logger(typeof(MessageService).Name) };

            Func<IMessage, IMessage> filterSecureRequests = (message) =>
            {
                /*
                var tag = message.Tag;

                if (string.IsNullOrWhiteSpace(tag))
                    return message;

                if (tag.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase))
                {
                    var creds = Encoding.UTF8.GetString(Convert.FromBase64String(tag.Substring(5)));

                    var i = creds.IndexOf(':');
                    var userName = creds.Substring(0, i);
                    var userPass = creds.Substring(i + 1);

                    if (userName != SystemConstants.AllowedUser || userPass != SystemConstants.AllowedPass)
                    {
                        message.Tag = null;
                        return message;
                    }

                    _currentSessionGuid = Guid.NewGuid();
                    var sessionKey = userName + "/" + _currentSessionGuid.ToString("N");

                    SessionContext = new SessionContext { SessionKey = sessionKey, Username = userName };
                    container.Register(SessionContext);
                    message.Tag = sessionKey;
                    return message;
                }

                message.Tag = null;*/

                return message;
            };

            mqService.RequestFilter = filterSecureRequests;

            Func<IMessage<Transaction>, PostResponse<Transaction>> handlePostTransactions = (message) =>
            {
                var service = new TransactionWebService { Logic = transactionLogic };
                var request = new BasicRequest {Message = message, Dto = message.GetBody()};
                var response = new BasicResponse(request);

                //userRepo.TryAuthenticate()

                service.SessionFactory.GetOrCreateSession(request, response);
                var session = service.GetSession();

                session.UserName = "******";

                var results = new PostResponse<Transaction> {Result = (Transaction) service.Post(message.GetBody())};
                return results;
            };

            // Dto Get Operations

            mqService.RegisterHandler<GetCurrencyTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), currencyTypeLogic));
            mqService.RegisterHandler<GetTransactions>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionLogic));
            mqService.RegisterHandler<GetTransactionStatusTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionStatusTypeLogic));
            mqService.RegisterHandler<GetTransactionNotificationStatusTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionNotificationStatusTypeLogic));
            mqService.RegisterHandler<GetTransactionTypes>(m => messagingHandlers.MessagingGetWrapper(m.GetBody(), transactionTypeLogic));

            // Dto Post Operations
            mqService.RegisterHandler<CurrencyType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), currencyTypeLogic.Post));

            mqService.RegisterHandler<Transaction>(handlePostTransactions);
            mqService.RegisterHandler<TransactionStatusType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), transactionStatusTypeLogic.Post));
            mqService.RegisterHandler<TransactionNotificationStatusType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), transactionNotificationStatusTypeLogic.Post));
            mqService.RegisterHandler<TransactionType>(m => messagingHandlers.MessagingPostRequest(m.GetBody(), transactionTypeLogic.Post));

            // Dto Put Opertations
            mqService.RegisterHandler<DeleteCurrencyType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), currencyTypeLogic));
            mqService.RegisterHandler<DeleteTransaction>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionLogic));
            mqService.RegisterHandler<DeleteTransactionStatusType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionStatusTypeLogic));
            mqService.RegisterHandler<DeleteTransactionNotificationStatusType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionNotificationStatusTypeLogic));
            mqService.RegisterHandler<DeleteTransactionType>(m => messagingHandlers.MessagingDeleteWrapper(m.GetBody(), transactionTypeLogic));

            mqService.Start();
        }