Пример #1
0
        public override void Configure(Container container)
        {
            Plugins.Add(new RazorFormat());

            container.Register(new DataSource());

            container.Register<IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider) {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

            using (var db = container.Resolve<IDbConnectionFactory>().Open())
            {
                db.CreateTableIfNotExists<Rockstar>();
                db.Insert(Rockstar.SeedData);
            }

            JsConfig.EmitCamelCaseNames = true;

            //Register Typed Config some services might need to access
            var appSettings = new AppSettings();

            //Register a external dependency-free 
            container.Register<ICacheClient>(new MemoryCacheClient());
            //Configure an alt. distributed persistent cache that survives AppDomain restarts. e.g Redis
            //container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));

            //Enable Authentication an Registration
            ConfigureAuth(container);

            //Create your own custom User table
            using (var db = container.Resolve<IDbConnectionFactory>().Open())
                db.DropAndCreateTable<UserTable>();
        }
Пример #2
0
		public override void Configure(Container container)
		{
			//Signal advanced web browsers what HTTP Methods you accept
			base.SetConfig(new HostConfig
			{
                DebugMode = true,
			});

            container.Register<IAppSettings>(new AppSettings());

            var appSettings = container.Resolve<IAppSettings>();

            container.Register(c => new ExampleConfig(c.Resolve<IAppSettings>()));
			var appConfig = container.Resolve<ExampleConfig>();

			container.Register<IDbConnectionFactory>(c => 
				new OrmLiteConnectionFactory(
					appConfig.ConnectionString.MapAbsolutePath(), 
					SqliteOrmLiteDialectProvider.Instance));

			if (appSettings.Get("PerformTestsOnInit", false))
			{
				log.Debug("Performing database tests...");
				DatabaseTest(container.Resolve<IDbConnectionFactory>());
			}
		}
Пример #3
0
        public override void Configure(Container container)
        {
            JsConfig.EmitCamelCaseNames = true;
            var appSettings = new TextFileSettings("~/appSettings.txt".MapHostAbsolutePath(), ":");

            container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
                appSettings.Get("database"),
                SqlServerDialect.Provider));

            container.Register(x => new Log4NetFactory(true));
            LogManager.LogFactory = container.Resolve<Log4NetFactory>();
            container.Register<ILog>(x => LogManager.GetLogger(GetType()));

            AwsAccessKey = appSettings.Get("awsAccessKey");
            AwsSecretKey = appSettings.Get("awsSecretKey");

            Plugins.Add(new CorsFeature());

            using (var db = container.Resolve<IDbConnectionFactory>().Open())
            {
                db.CreateTableIfNotExists<LinkUrls>();
                db.CreateTableIfNotExists<LinkImages>();
            }

            Routes.Add<FindLinkUrl>("/urls/{Id}", "GET")
                .Add<FindLinkUrl>("/urls", "GET")
                .Add<AddLinkUrl>("/urls", "POST")
                .Add<StartGetImages>("/start", "GET");
        }
		public override void Configure(Container container)
		{
			//Signal advanced web browsers what HTTP Methods you accept
			base.SetConfig(new EndpointHostConfig
			{
				GlobalResponseHeaders =
				{
					{ "Access-Control-Allow-Origin", "*" },
					{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
				},
                WsdlServiceNamespace = "http://www.servicestack.net/types",
				WsdlServiceTypesNamespace = "http://www.servicestack.net/types",
			});

			container.Register<IResourceManager>(new ConfigurationResourceManager());

			var appSettings = container.Resolve<IResourceManager>();

			container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));
			var appConfig = container.Resolve<ExampleConfig>();

			container.Register<IDbConnectionFactory>(c => 
				new OrmLiteConnectionFactory(
					appConfig.ConnectionString.MapAbsolutePath(), 
					SqliteOrmLiteDialectProvider.Instance));

			if (appSettings.Get("PerformTestsOnInit", false))
			{
				log.Debug("Performing database tests...");
				DatabaseTest(container.Resolve<IDbConnectionFactory>());
			}
		}
Пример #5
0
        public override void Configure(Container container)
        {
            //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
            base.SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                    {
                        { "Access-Control-Allow-Origin", "*" },
                        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                    },
            });

            container.Register<IResourceManager>(new ConfigurationResourceManager());
            container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));

            var appConfig = container.Resolve<ExampleConfig>();

            container.Register<IDbConnectionFactory>(c =>
                new OrmLiteConnectionFactory(
                    appConfig.ConnectionString.MapHostAbsolutePath(),
                    SqliteOrmLiteDialectProvider.Instance));

            ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());

            //The MemoryCacheClient is a great way to get started with caching; nothing external to setup.
            container.Register<ICacheClient>(c => new MemoryCacheClient());

            //If you give Redis a try, you won't be disappointed. This however requires Redis to be installed.
            //container.Register<ICacheClient>(c => new BasicRedisClientManager());

            log.InfoFormat("AppHost Configured: {0}", DateTime.Now);
        }
Пример #6
0
        public override void Configure(Container container)
        {
            //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
            base.SetConfig(new HostConfig
            {
                DebugMode = true,
            });

            Plugins.Add(new CorsFeature());

            container.Register<IAppSettings>(new AppSettings());
            container.Register(c => new ExampleConfig(c.Resolve<IAppSettings>()));

            var appConfig = container.Resolve<ExampleConfig>();

            container.Register<IDbConnectionFactory>(c =>
                new OrmLiteConnectionFactory(
                    appConfig.ConnectionString.MapHostAbsolutePath(),
                    SqliteOrmLiteDialectProvider.Instance));

            ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());

            //If you give Redis a try, you won't be disappointed. This however requires Redis to be installed.
            //container.Register<ICacheClient>(c => new BasicRedisClientManager());

            log.InfoFormat("AppHost Configured: {0}", DateTime.Now);
        }
Пример #7
0
		public override void Configure(Container container)
		{
			//Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
			base.SetConfig(new EndpointHostConfig
			{
				GlobalResponseHeaders =
					{
						{ "Access-Control-Allow-Origin", "*" },
						{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
					},
			});

			container.Register<IResourceManager>(new ConfigurationResourceManager());

			container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));
			var appConfig = container.Resolve<ExampleConfig>();

			container.Register<IDbConnectionFactory>(c =>
				new OrmLiteConnectionFactory(
					appConfig.ConnectionString.MapHostAbsolutePath(),
					SqliteOrmLiteDialectProvider.Instance));

			ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());


			//register different cache implementations depending on availability
			const bool hasRedis = false;
			if (hasRedis)
				container.Register<ICacheClient>(c => new BasicRedisClientManager());
			else
				container.Register<ICacheClient>(c => new MemoryCacheClient());


			log.InfoFormat("AppHost Configured: " + DateTime.Now);
		}
Пример #8
0
        public StatusItemBurritoDayView(Container container)
        {
            this.menu = new NSMenu();

            this.menu.AddItem(this.refreshMenuItem);
            this.menu.AddItem(this.launchMenuItem);

            this.menu.AddItem(NSMenuItem.SeparatorItem);

            this.menu.AddItem(this.durationMenuItem);
            this.menu.AddItem(this.locationMenuItem);

            this.menu.AddItem(this.separatorMenuItem);;

            this.menu.AddItem(this.dismissMenuitem);
            this.menu.AddItem(this.quitMenuItem);

            this.launchMenuItem.Activated += delegate {
                var handler = this.urlActivated;
                if (handler != null)
                {
                    handler(this, "http://isitburritoday.com");
                }
            };
            this.quitMenuItem.Activated += (sender, e) =>
                NSApplication.SharedApplication.Terminate(sender as NSObject);

            this.presenters = new IDisposable[]
            {
                container.Resolve<BurritoDayPresenter, IBurritoDayView>(this),
                container.Resolve<UrlActivationPresenter, IUrlActivationView>(this),
            };
        }
Пример #9
0
        public App()
        {
            Container = new Container();

            Container.Register<ICache>(new DevNullCacheProvider());
            Container.Register<IRequestHandler>(new WebClientRequestHandler());
            Container.Register<IExportHandler>(new OaiPmhXmlHandler());
            Container.Register<IScraper>(new JsonScraper(Container.Resolve<IRequestHandler>()/*, new ScrapeConfig { EnableParallelProcessing = true }*/)
            {
                Cache = Container.Resolve<ICache>(),
                ExportHandler = Container.Resolve<IExportHandler>()
            });
        }
        public void ConstructFactoryPopulatesLocalControllerAndExternalControllerByDefault()
        {
            var container = new Container();
            var factory = new FunqControllerFactory(container, typeof(ExternalController).Assembly);
            
            // test we can still resolve the local one (by default)
            var testController = container.Resolve<LocalController>();
            Assert.That(testController, Is.Not.Null);

            // test we can resolve the external controller (via params assembly)
            var externalController = container.Resolve<ExternalController>();
            Assert.That(externalController, Is.Not.Null);
        }
        public override void Configure(Container container)
        {
            container.RegisterAutoWired<EmailProvider>();
            container.RegisterAutoWired<FacebookGateway>();
            container.RegisterAutoWired<TwitterGateway>();
            
            Plugins.Add(new RazorFormat());
            Plugins.Add(new RequestLogsFeature());

            var appSettings = new AppSettings();
            Plugins.Add(new AuthFeature(() => new CustomSession(), 
                new IAuthProvider[] {
                    new CredentialsAuthProvider(appSettings), 
                    new TwitterAuthProvider(appSettings),
                    new FacebookAuthProvider(appSettings), 
                }));

            container.Register<IRedisClientsManager>(new PooledRedisClientManager("localhost:6379"));
            container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient());

            container.Register<IDbConnectionFactory>(
                new OrmLiteConnectionFactory("~/App_Data/db.sqlite".MapHostAbsolutePath(), 
                    SqliteDialect.Provider) {
                        ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                    });

            //Store User Data into above OrmLite database
            container.Register<IAuthRepository>(c => 
                new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));

            //If using and RDBMS to persist UserAuth, we must create required tables
            var authRepo = container.Resolve<IAuthRepository>();
            authRepo.InitSchema();

            //Register MQ Service
            var mqService = new RedisMqServer(container.Resolve<IRedisClientsManager>());
            container.Register<IMessageService>(mqService);
            container.Register(mqService.MessageFactory);

            mqService.RegisterHandler<SMessage>(ServiceController.ExecuteMessage);
            mqService.RegisterHandler<CallFacebook>(ServiceController.ExecuteMessage);
            mqService.RegisterHandler<EmailMessage>(ServiceController.ExecuteMessage);
            mqService.RegisterHandler<PostStatusTwitter>(ServiceController.ExecuteMessage);

            mqService.Start();

            if (appSettings.Get("ResetAllOnStartUp", false))
            {
                ResetAll(container, (OrmLiteAuthRepository)authRepo);
            }
        }
Пример #12
0
        public override void Configure(Container container)
        {
            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new RazorFormat());
            Plugins.Add(new RequestLogsFeature());

            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(ContactsServices).Assembly);

            Plugins.Add(new AutoQueryFeature());

            container.Register<IDbConnectionFactory>(
                c => new OrmLiteConnectionFactory("~/db.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider) {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

            using (var db = container.Resolve<IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable<Email>();
                db.DropAndCreateTable<Contact>();
                ContactsServices.AddCustomers(db);
            }

            UseDbEmailer(container);
            //UseSmtpEmailer(container); //Uncomment to use SMTP instead

            //ConfigureRabbitMqServer(container); //Uncomment to start accepting requests via Rabbit MQ
        }
Пример #13
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        /// <param name="container"></param>
        public override void Configure(Container container)
        {
            JsConfig.EmitCamelCaseNames = true;

            Plugins.Add(new ServerEventsFeature());

            SetConfig(new HostConfig
            {
                DebugMode                      = AppSettings.Get("DebugMode", false),
                DefaultContentType             = MimeTypes.Json,
                AddRedirectParamsToQueryString = true,
            });

            CustomErrorHttpHandlers.Remove(HttpStatusCode.Forbidden);

            //Register all Authentication methods you want to enable for this web app.
            Plugins.Add(new AuthFeature(
                            () => new AuthUserSession(),
                            new IAuthProvider[] {
                new TwitterAuthProvider(AppSettings)       //Sign-in with Twitter
            }));

            container.RegisterAutoWiredAs <MemoryChatHistory, IChatHistory>();

            var redisHost = AppSettings.GetString("RedisHost");

            if (redisHost != null)
            {
                container.Register <IRedisClientsManager>(new RedisManagerPool(redisHost));

                container.Register <IServerEvents>(c =>
                                                   new RedisServerEvents(c.Resolve <IRedisClientsManager>()));
                container.Resolve <IServerEvents>().Start();
            }
        }
Пример #14
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory();

            SetConfig(new HostConfig
            {
                DebugMode = true,
                EmbeddedResourceSources = { Assembly.GetExecutingAssembly() },
            });

            Plugins.Add(new RazorFormat
            {
                LoadFromAssemblies = { typeof(RockstarsService).Assembly }
            });
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());

            container.Register<IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

            using (var db = container.Resolve<IDbConnectionFactory>().OpenDbConnection())
            {
                db.CreateTableIfNotExists<Rockstar>();
                db.InsertAll(RockstarsService.SeedData);
            }

            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
            this.CustomErrorHttpHandlers[HttpStatusCode.Unauthorized] = new RazorHandler("/login");
        }
Пример #15
0
        /// <summary>
        /// The configure.
        /// </summary>
        /// <param name="container">
        /// The container.
        /// </param>
        public override void Configure(Container container)
        {
            container.Register<ContentDao<Models.Content>>(dao => new InMemoryContentDao());
            container.Register<IContentConfiguration>(constants => new ContentConfiguration());

            container.Register<IEnumerable<ResponseHydrator<ContentRequest, ContentResponse>>>(responseHydrationTasks =>
                new List<ResponseHydrator<ContentRequest, ContentResponse>>
                    {
                        new PopulateContentByCategoryIdResponseHydrator(container.Resolve<ContentDao<Models.Content>>(), container.Resolve<IContentConfiguration>()),
                        new PopulateContentByIdResponseHydrator(container.Resolve<ContentDao<Models.Content>>(), container.Resolve<IContentConfiguration>())
                    });

            Routes.Add<ContentRequest>("/ContentService/");
            Routes.Add<ContentRequest>("/ContentService/{ContentId}");
            Routes.Add<ContentRequest>("/ContentService/Category/{CategoryId}");
        }
Пример #16
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            Container = new Container();

            Container.Register<ICache>(new DevNullCacheProvider());
            Container.Register<IRequestHandler>(new WebClientRequestHandler());
            Container.Register<IExportHandler>(new OaiPmhXmlHandler());
            Container.Register<IScraper>(new JsonScraper(Container.Resolve<IRequestHandler>())
            {
                Cache = Container.Resolve<ICache>(),
                ExportHandler = Container.Resolve<IExportHandler>()
            });
        }
Пример #17
0
		public override void Configure(Container container)
		{
			JsConfig.DateHandler = JsonDateHandler.ISO8601;	

			container.Register<IDbConnectionFactory>(c =>
				new OrmLiteConnectionFactory(
					"~/App_Data/db.sqlite".MapHostAbsolutePath(),
					SqliteOrmLiteDialectProvider.Instance));

			var resetMovies = container.Resolve<ResetMoviesService>();
			resetMovies.Post(null);

			Routes
			  .Add<Movie>("/movies")
			  .Add<Movie>("/movies/{Id}")
			  .Add<Movies>("/movies")
			  .Add<Movies>("/movies/genres/{Genre}");

			SetConfig(new EndpointHostConfig
			{
				GlobalResponseHeaders = {
						{ "Access-Control-Allow-Origin", "*" },
						{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
						{ "Access-Control-Allow-Headers", "Content-Type, X-Requested-With" },
					},
					//EnableFeatures = onlyEnableFeatures,
					//DebugMode = true, //Show StackTraces for easier debugging
			});

		}
Пример #18
0
        public override void Configure(Container container)
        {
            Plugins.Add(new RegistrationFeature());
            Plugins.Add (
                new AuthFeature
                (
                    () => new AuthUserSession(),
                    new IAuthProvider[]
                    {
                        new BasicAuthProvider(),
                        new CustomCredentialsAuthProvider()
                    }
                ) {HtmlRedirect = "/common/login" }
            );
            Plugins.Add(new RazorFormat());

            SetConfig(new EndpointHostConfig {
                DefaultContentType = ContentType.Json,
                CustomHttpHandlers = {
                    { HttpStatusCode.NotFound, new RazorHandler("/notfound") }
                }
            });

            container.Register<IRedisClientsManager>(new PooledRedisClientManager("localhost:6379"));
            UserRepository = new RedisAuthRepository(container.Resolve<IRedisClientsManager>());
            container.Register<IUserAuthRepository>(UserRepository);
        }
Пример #19
0
 //Create missing tables
 void SetUpDb(Container container)
 {
     var dbFactory = container.Resolve<IDbConnectionFactory> ();
     using (IDbConnection db = dbFactory.Open ()) {
         db.CreateTableIfNotExists<Value> ();
     }
 }
Пример #20
0
        public void Test_Get_EventService_Returns_Response()
        {    //TODO this Test sucks
            //Arrange
            //Set up the Service I want to Test
            var eventService = new EventService {
                Repository = TestContainer.Resolve <IEventRepository>()
            };
            string testFromDate = DateTime.Now.AddHours(-1).ToString(Global_Const.DATE_FORMAT);
            var    testEvents   = new Events {
                From = testFromDate
            };
            //Act
            // Call on the Service
            EventRecordListResponse response = (EventRecordListResponse)eventService.Get(testEvents);
            var eventRecords = response.EventRecords;

            //Assert
            Assert.IsNotNull(response, "Response from Eventservice is null");

            Assert.IsInstanceOfType(response, typeof(EventRecordListResponse), "Returns the wrong list type");
            List <IEventRecord> eventRList = (List <IEventRecord>)response.EventRecords;
            int evRlCount = eventRList.Count;

            Assert.IsTrue(evRlCount == 20, "There should be 20 item in the event test list");
        }
Пример #21
0
            //Configure ServiceStack Authentication and CustomUserSession
            private void ConfigureAuth(Funq.Container container)
            {
                Routes
                .Add <Auth>("/auth")
                .Add <Auth>("/auth/{provider}")
                .Add <Registration>("/register");

                var appSettings = new AppSettings();

                AuthFeature.Init(this, () => new CustomUserSession(),
                                 new IAuthProvider[] {
                    new CredentialsAuthProvider(appSettings),
                    new FacebookAuthProvider(appSettings),
                    new TwitterAuthProvider(appSettings),
                    new BasicAuthProvider(appSettings),
                });

                RegistrationFeature.Init(this);

                container.Register <IUserAuthRepository>(c =>
                                                         new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

                var authRepo = (OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>();

                if (new AppSettings().Get("Recr	eateTables", true))
                {
                    authRepo.DropAndReCreateTables();
                }
                else
                {
                    authRepo.CreateMissingTables();
                }
            }
Пример #22
0
        public static void Configure(Container container, PhoneApplicationFrame root)
        {
            container.Register<IJiraService>(c => new JiraService{Store = c.Resolve<IDocumentStore>()});
            container.Register<IScheduler>(c => new Scheduler());

            container.Register(c => new SignInCommandHandler{Bus = c.Resolve<IBus>()});
            container.Register(c => new SyncHandler{Bus = c.Resolve<IBus>(), Jira = c.Resolve<IJiraService>()});
            container.Register(
                c => new SyncProjectHandler
                    {
                        Bus = c.Resolve<IBus>(),
                        Store = c.Resolve<IDocumentStore>(),
                        Jira = c.Resolve<IJiraService>(),
                        Scheduler = c.Resolve<IScheduler>()
                    });
            container.Register(c => new SyncNewlyDiscoveredProjectsByDefaultHandler {Bus = c.Resolve<IBus>()});

            container.Register(c => new ProfileLoggedInEventHandler { Store = c.Resolve<IDocumentStore>() });

            var bus = container.Resolve<IBus>();

            bus.RegisterHandler<SignInCommandHandler, SignInCommand>();
            bus.RegisterHandler<SyncHandler, ApplicationLoadedEvent>();
            bus.RegisterHandler<ProfileLoggedInEventHandler, LoggedInEvent>();
            bus.RegisterHandler<SyncHandler, LoggedInEvent>();
            bus.RegisterHandler<SyncProjectHandler, ProjectsDiscoveredEvent>();
            bus.RegisterHandler<SyncProjectHandler, SyncProjectCommand>();
            bus.RegisterHandler<SyncNewlyDiscoveredProjectsByDefaultHandler, DiscoveredNewProjectEvent>();
        }
Пример #23
0
            //Configure ServiceStack Authentication and CustomUserSession
            private void ConfigureAuth(Funq.Container container)
            {
                Routes
                .Add <Register>("/register");

                var appSettings = new AppSettings();

                Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                            new IAuthProvider[] {
                    new CredentialsAuthProvider(appSettings),
                    new FacebookAuthProvider(appSettings),
                    new TwitterAuthProvider(appSettings),
                    new GoogleOpenIdOAuthProvider(appSettings),
                    new OpenIdOAuthProvider(appSettings),
                    new DigestAuthProvider(appSettings),
                    new BasicAuthProvider(appSettings),
                }));

                Plugins.Add(new RegistrationFeature());

                container.Register <IAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

                var authRepo = (OrmLiteAuthRepository)container.Resolve <IAuthRepository>();

                if (new AppSettings().Get("RecreateTables", true))
                {
                    authRepo.DropAndReCreateTables();
                }
                else
                {
                    authRepo.InitSchema();
                }
            }
 public void ConstructFactoryPopulatesLocalControllerByDefault()
 {
     var container = new Container();
     var factory = new FunqControllerFactory(container);
     var testController = container.Resolve<LocalController>();
     Assert.That(testController, Is.Not.Null);
 }
Пример #25
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory();

            JsConfig.EmitCamelCaseNames = true;
            JsConfig.IncludeNullValues = true;
            JsConfig.ExcludeTypeInfo = true;

            SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                {
                    { "Cache-Control", "no-cache" }
                },
                DefaultContentType = ContentType.Json,
                MapExceptionToStatusCode =
                {
                    { typeof(VariableResourceNotFoundException), 404 }, // not found
                    { typeof(MissingCommandParameterException), 400 }, // bad request
                }
            });

            container.Register<ILog>(x => LogManager.LogFactory.GetLogger("win-driver"));
            container.Register<IElementRepository>(new ElementRepository());
            container.Register<ISessionRepository>(new SessionRepository());
            container.Register<IAutomationService>(new UIAutomationService(container.Resolve<IElementRepository>()));
        }
        public override void Configure(Container container)
        {
            JsConfig.EmitCamelCaseNames = true;
            Plugins.Add(new SwaggerFeature());
            var manager = new InsteonManager(insteonSource);
            container.Register(manager);
            var settingsProvider = new SettingsProvider(new RoamingAppDataStorage("Insteon"));
            var mySettings = settingsProvider.GetSettings<SmartThingsSettings>();

            container.Register(mySettings);

            manager.Network.Devices.DeviceStatusChanged += (sender, data) =>
            {
                logger.DebugFormat("{0}:{1}", data.Device.Address, data.DeviceStatus);
                var settings = container.Resolve<SmartThingsSettings>();
                var cb = new SmartThingsCallbacks(settings);
                cb.PushDeviceStatusUpdate(data.Device, data.DeviceStatus);
            };

            GlobalResponseFilters.Add((req, res, dto) =>
            {

                res.AddHeader("X-Insteon", ServiceName);

            });

            manager.Connect();

        }
Пример #27
0
        // Configure the container with the necessary routes for your ServiceStack application.
        public override void Configure(Container container)
        {
            // setup event logger
            registerEventLogLogging(container);

            // setup email notifications with defaults
            registerNotifications(container);

            // determine datastore method
            #if MEMORYSTORAGE
            registerInMemoryStore(container);
            #else
            registerSqlDataStore(container);

            #endif
            // setup repositories with defaults if they don't exist
            container.Resolve<IRepositories>().SetUp();

            Plugins.Add(new SessionFeature());

            SetConfig(new EndpointHostConfig
            {
                // only serve api requests from /api/
                ServiceStackHandlerFactoryPath = "api",
                ReturnsInnerException = true,
                DefaultContentType = ContentType.Json,
                EnableFeatures = Feature.Json | Feature.Metadata //Feature.Xml | Feature.Html
            });
        }
Пример #28
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var container = new Container();
            Tepeyac.Funq.Registry.Register(container);

            container.Register<IFiber>("GuiFiber", c => c.Resolve<IFiber>());
            /*
            container.Register<IFiber>("GuiFiber", c =>
            {
                var executor =
                    c.Resolve<IExecutor>() ??
                    new Executor();
                var invoke = new SynchronizeInvoke(new WindowsFormsSynchronizationContext());
                var fiber = new FormFiber(invoke, executor);
                fiber.Start();

                return fiber;
            });
             */

            container.Register<IBurritoDayView>(c =>
                new BurritoDayView(c));

            container.Resolve<IBurritoDayView>();
            Application.Run();
        }
Пример #29
0
        public override void Configure(Container container)
        {
            JsConfig.EmitCamelCaseNames = true;
            Plugins.Add(new RazorFormat());

            //Comment out 2 lines below to change to use local FileSystem instead of S3
            var s3Client = new AmazonS3Client(AwsConfig.AwsAccessKey, AwsConfig.AwsSecretKey, RegionEndpoint.USEast1);
            VirtualFiles = new S3VirtualPathProvider(s3Client, AwsConfig.S3BucketName, this);

            container.Register<IPocoDynamo>(c => new PocoDynamo(AwsConfig.CreateAmazonDynamoDb()));
            var db = container.Resolve<IPocoDynamo>();
            db.RegisterTable<Todos.Todo>();
            db.RegisterTable<EmailContacts.Email>();
            db.RegisterTable<EmailContacts.Contact>();
            db.InitSchema();

            //AWS Auth
            container.Register<ICacheClient>(new DynamoDbCacheClient(db, initSchema:true));
            container.Register<IAuthRepository>(new DynamoDbAuthRepository(db, initSchema:true));
            Plugins.Add(CreateAuthFeature());

            //EmailContacts
            ConfigureSqsMqServer(container);
            ConfigureEmailer(container);
            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(EmailContacts.CreateContact).Assembly);
        }
        public void should_be_able_to_get_service_impl()
        {
            var c = new Container();
            c.EasyRegister<IFoo, Foo>();

            Assert.IsInstanceOf<Foo>(c.Resolve<IFoo>());
        }
Пример #31
0
        public static void Configure(PhoneApplicationFrame rootFrame)
        {
            DocumentStore = new DocumentStore();
            Container = new Container();

            Container.Register<IDocumentStore>(c => new DocumentStore());
            Container.Register<IBus>(c => new Bus(c));

            Container.Register(c => new ActivityNewActivityHandler { Bus = c.Resolve<IBus>(), DocumentStore = DocumentStore });
            Container.Register(c => new TestModeActivatedHandler { Bus = c.Resolve<IBus>() });
            Container.Register(c => new ActivateTestModeHandler { Bus = c.Resolve<IBus>() });
            Container.Register(c => new ClearCacheHandler { DocumentStore = c.Resolve<IDocumentStore>() });
            Container.Register(c => new Contexts.Review.Domain.ClearCacheHandler { DocumentStore = c.Resolve<IDocumentStore>() });

            var bus = Container.Resolve<IBus>();

            bus.RegisterHandler<ActivityNewActivityHandler, NewActivityEvent>();
            bus.RegisterHandler<TestModeActivatedHandler, TestModeActivatedEvent>();
            bus.RegisterHandler<ActivateTestModeHandler, ActivateCommand>();
            bus.RegisterHandler<Contexts.Settings.ClearCacheHandler, ClearCacheCommand>();
            bus.RegisterHandler<Contexts.Review.Domain.ClearCacheHandler, ClearCacheCommand>();

            Contexts.Import.Module.Configure(Container);
            Contexts.Import.ModuleUi.Configure(Container, rootFrame);

            Contexts.Review.Module.Confiure(Container);
        }
Пример #32
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        /// <param name="container"></param>
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new DebugLogFactory();

            OracleDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();

            container.Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(ConfigUtils.GetAppSetting("connectionString"), OracleOrmLiteDialectProvider.Instance));

            using (var db = container.Resolve<IDbConnectionFactory>().OpenDbConnection())
            {
                db.CreateTableIfNotExists<Campaign>();
            }


            OrmLiteConfig.InsertFilter = (dbCmd, row) =>
            {
                var auditRow = row as IAudit;
                if (auditRow == null) return;
                var now = SystemClock.Instance.Now;
                var milliseconds = now.Ticks / NodaConstants.TicksPerMillisecond;
                auditRow.CreatedDate = auditRow.ModifiedDate = milliseconds;
            };
            OrmLiteConfig.UpdateFilter = (dbCmd, row) =>
            {
                var auditRow = row as IAudit;
                if (auditRow == null) return;
                var now = SystemClock.Instance.Now;
                var milliseconds = now.Ticks / NodaConstants.TicksPerMillisecond;
                auditRow.ModifiedDate = milliseconds;
            };
        }
Пример #33
0
        public override void Configure(Container container)
        {
            if (EnableRazor)
                Plugins.Add(new RazorFormat());

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new RequestInfoFeature());
            Plugins.Add(new RequestLogsFeature());
            Plugins.Add(new ServerEventsFeature());

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(AutoValidationValidator).Assembly);


            container.Register<IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

            using (var db = container.Resolve<IDbConnectionFactory>().OpenDbConnection())
            {
                db.DropAndCreateTable<Rockstar>(); //Create table if not exists
                db.Insert(Rockstar.SeedData); //Populate with seed data
            }

            SetConfig(new HostConfig {
                AdminAuthSecret = "secret",
                DebugMode = true,
            });
        }
Пример #34
0
        public override void Configure(Container container)
        {
            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new RazorFormat());
            Plugins.Add(new RequestLogsFeature());

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(ContactsServices).Assembly);

            container.Register<IDbConnectionFactory>(
                c => new OrmLiteConnectionFactory("db.sqlite", SqliteDialect.Provider) {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

            using (var db = container.Resolve<IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable<Email>();
                db.DropAndCreateTable<Contact>();

                db.Insert(new Contact { Name = "Kurt Cobain", Email = "*****@*****.**", Age = 27 });
                db.Insert(new Contact { Name = "Jimi Hendrix", Email = "*****@*****.**", Age = 27 });
                db.Insert(new Contact { Name = "Michael Jackson", Email = "*****@*****.**", Age = 50 });
            }

            UseDbEmailer(container);
            //UseSmtpEmailer(container); //Uncomment to use SMTP instead

            //ConfigureRabbitMqServer(container); //Uncomment to start accepting requests via Rabbit MQ
        }
        public void Test_that_GetByTimeFilter_Returns_a_sorted_list_when_Several_servers()
        {
            //Arrange
            TestContainer.Register <IAppConfig>(new AppConfig_Mock()); // We are using test config for this tests.
            IEventRepository testRep = TestContainer.Resolve <IEventRepository>();

            testRep.Config = TestContainer.Resolve <IAppConfig>();
            DateTime fromTime = DateTime.Now.AddDays(-1);
            DateTime toTime   = DateTime.Now;
            //Act
            List <IEventRecord> eventList = testRep.GetByTimeFilter(fromTime, toTime, Global_Const.MAXGETROWS, Global_Const.TIMEOUT_S);
            //Check that it is sorted descending. Previous should always be bigger if sorted descending
            DateTime prevEv      = DateTime.MaxValue;
            bool     isNewBigger = false;
            int      i           = 0;

            foreach (EventRecord ev in eventList)
            {
                var newEventRec = ev.TimeGenerated;
                isNewBigger = (newEventRec > prevEv);  //The new item in the list should never be bigger.
                i++;
                if (isNewBigger)
                {
                    break;
                }
                prevEv = newEventRec;
            }
            //Assert
            Assert.IsTrue(eventList.Any(), "There should be some events last day");
            Assert.IsFalse(isNewBigger, "Sorting sucks. Is not sorted descending");
        }
Пример #36
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Funq.Container container)
        {
            //Register Redis Client Manager singleton in ServiceStack's built-in Func IOC
            container.Register(s => new RepositoryFactories());
            container.Register <IRepositoryProvider>(c => new RepositoryProvider(c.TryResolve <RepositoryFactories>())).ReusedWithin(ReuseScope.None);
            container.Register <IOpfcUow>(c => new OpfcUow(c.TryResolve <IRepositoryProvider>())).ReusedWithin(ReuseScope.None);

            container.Register(s => new ServiceFactories(s.Resolve <IOpfcUow>())).ReusedWithin(ReuseScope.None);
            container.Register <IServiceProvider>(c => new ServiceProvider(c.TryResolve <ServiceFactories>())).ReusedWithin(ReuseScope.None);
            container.Register <IServiceUow>(c => new ServiceUow(c.TryResolve <IServiceProvider>())).ReusedWithin(ReuseScope.None);

            container.Register <ITask>(t => new CompositeTask(new AutoMapperConfigTask()));
            container.Resolve <ITask>().Execute();
        }
Пример #37
0
        public override void Configure(Funq.Container container)
        {
            container.Register <IAuthProvider>((c) => new AuthProvider());

            Routes
            .Add <GetDataRequest>("/GetData");


            this.RequestFilters.Add((req, res, dto) =>
            {
                //if (!req.IsSecureConnection)
                //{
                //    res.StatusCode = 401;
                //    res.Close();
                //}

                if (req.Headers["Authorization"] != null)
                {
                    const string key   = "Bearer ";
                    string accessToken = null;

                    var header = req.Headers["Authorization"];
                    if (header.StartsWith(key))
                    {
                        accessToken = header.Substring(key.Length);
                    }

                    if (string.IsNullOrWhiteSpace(accessToken))
                    {
                        res.StatusCode = 401;
                        res.Close();
                    }

                    //Lookup

                    var provider = container.Resolve <IAuthProvider>();

                    if (!provider.UserIsValid(accessToken))
                    {
                        res.StatusCode = 401;
                        res.Close();
                    }
                }
            });
        }
Пример #38
0
        protected virtual void StartThread(string subscribeToChannelName, Action <string, string> onMessage)
        {
            ThreadPool.QueueUserWorkItem(x =>
            {
                using (var redisConsumer = Container.Resolve <IRedisClientsManager>().GetClient())
                    using (var subscription = redisConsumer.CreateSubscription())
                    {
                        subscription.OnSubscribe = channel =>
                        {
                            Console.WriteLine("listening for orders on channel {0}", channel);
                        };
                        subscription.OnUnSubscribe = channel =>
                        {
                            Console.WriteLine("UnSubscribed from '{0}'", channel);
                        };

                        subscription.OnMessage = onMessage;

                        subscription.SubscribeToChannels(subscribeToChannelName); //blocking
                    }
            });
        }
Пример #39
0
        private static void InitialDbTables(Funq.Container container, OrmLiteAuthRepository <UserAccount, UserAccountDetail> userRepository)
        {
            string hash, salt;

            new SaltedHash().GetHashAndSaltString("password1", out hash, out salt);

            userRepository.DropAndReCreateTables();
            using (var dbConnection = container.Resolve <IDbConnectionFactory>().OpenDbConnection())
            {
                dbConnection.CreateTable <Bill>(true);
                dbConnection.CreateTable <Invoice>(true);
                dbConnection.CreateTable <AddressBranching>(true);
                dbConnection.CreateTable <Address>(true);
                dbConnection.CreateTable <Company>(true);
                dbConnection.CreateTable <Category>(true);
            }
            userRepository.CreateUserAuth(new UserAccount
            {
                UserName = "******",
                Password = hash,
                FullName = "Cheng Zhang",
                Email    = "*****@*****.**",
                Salt     = salt,
                Roles    = new List <string> {
                    RoleNames.Admin
                },
                Permissions = new List <string> {
                    "Get"
                },
                CreatedDate     = DateTime.Now,
                Create_On       = DateTime.Now,
                LastLoginTime   = DateTime.Now,
                Last_Updated_By = 0,
                Last_Updated_On = DateTime.Now
            }, "password1");
        }
Пример #40
0
        /// <summary>
        /// Configure the given container with the
        /// registrations provided by the funqlet.
        /// </summary>
        /// <param name="container">Container to register.</param>
        public override void Configure(Funq.Container container)
        {
            ServiceStack.OrmLite.OrmLiteConfig.CommandTimeout = 60;
            WebEas.Log.WebEasNLogLogger.Application           = "PFE";
            base.Configure(container);

            // new EnumSerializerConfigurator().WithAssemblies(new List<Assembly> { typeof(HierarchyNode).Assembly }).WithNullableEnumSerializers().Configure();

            this.SetConfig(new HostConfig
            {
                WsdlServiceNamespace = "http://schemas.dcom.sk/private/Egov/pfe/1.0",
                SoapServiceName      = "EsamPfe",
#if DEBUG || DEVELOP || INT || ITP
                DebugMode      = true,
                EnableFeatures = Feature.All.Remove(this.disableFeaturesDebug),
#else
                DebugMode      = false,
                EnableFeatures = Feature.All.Remove(this.disableFeatures),
#endif
                DefaultContentType = MimeTypes.Json,
                AllowJsonpRequests = true,
#if DEVELOPCRM
                WebHostUrl = "https://esam-crm.datalan.sk/esam/api/pfe"
#endif
            });

#if !DEBUG
            container.Register <IMessageService>(c => new RedisMqServer(c.Resolve <IRedisClientsManager>()));
            container.Resolve <IMessageService>().RegisterHandler <WebEas.ServiceModel.Dto.LongOperationStatus>(m =>
            {
                using (var redisClient = base.Resolve <IRedisClientsManager>().GetClient())
                {
                    var longOperationStatus = m.GetBody();
                    ProcessLongOperationStatus(longOperationStatus, redisClient, base.Resolve <IServerEvents>());
                }
                return(null);
            });

            container.Resolve <IMessageService>().Start();
#endif
            container.RegisterAutoWiredAs <CfeRepository, IRepositoryBase>("cfe").ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWiredAs <BdsRepository, IRepositoryBase>("bds").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<DapRepository, IRepositoryBase>("dap").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<DmsRepository, IRepositoryBase>("dms").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<FinRepository, IRepositoryBase>("fin").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<OsaRepository, IRepositoryBase>("osa").ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWiredAs <RegRepository, IRepositoryBase>("reg").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<RzpRepository, IRepositoryBase>("rzp").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<UctRepository, IRepositoryBase>("uct").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<VykRepository, IRepositoryBase>("vyk").ReusedWithin(ReuseScope.Request);
            //container.RegisterAutoWiredAs<MajRepository, IRepositoryBase>("maj").ReusedWithin(ReuseScope.Request);
            container.AddScoped <IPfeRepository, PfeRepository>();

            var mse = new ServerEventsFeature()
            {
                LimitToAuthenticatedUsers    = true,
                NotifyChannelOfSubscriptions = false,
                OnCreated = (sub, req) => {
                    var session = req.SessionAs <EsamSession>();
                    if (!session.IsAuthenticated)
                    {
                        return;
                    }
                    if (session.Roles != null)
                    {
                        var key    = "SynchronizaciaDAPToast:" + session.TenantId + ":" + session.UserId;
                        var showed = GetCacheClient().Get <bool>(key);
                        if (!showed)
                        {
                            if (session.Roles.Any(x => x.StartsWith("DAP") || x.StartsWith("FIN") || x.StartsWith("UCT")))
                            {
                                var repository = HostContext.Resolve <IPfeRepository>();
                                repository.Session = session;
                                var eSAMRezim = repository.GetNastavenieI("cfe", "eSAMRezim");
                                var isoZdroj  = repository.GetNastavenieI("cfe", "ISOZdroj");

                                if (repository.GetNastavenieB("cfe", "PohladavkyDAP") && (eSAMRezim == 1 || isoZdroj > 0))
                                {
                                    var datumSynchro = repository.GetNastavenieT("dap", "SynchronizaciaDAP");
                                    if (datumSynchro.HasValue)
                                    {
                                        sub.ConnectArgs["SynchronizaciaDAP"] = datumSynchro.Value.ToString("o");
                                    }
                                    GetCacheClient().Set(key, true, DateTime.Today.AddDays(1));
                                }
                            }
                        }
                    }
                },

                /*
                 * TODO: Synchronizacia s ISO
                 * OnSubscribe = (sub) =>
                 * {
                 *  if (sub.UserId == "00000000-0000-0000-0000-000000000002")
                 *  {
                 *      var subSessionKey = SessionFeature.GetSessionKey(sub.SessionId);
                 *      var subSession = HostContext.Cache.Get<EsamSession>(subSessionKey);
                 *      var syncManager = new IsoSynchronizationManager(Resolve<IServerEvents>(), Resolve<IRedisClientsManager>());
                 *      syncManager.ProcessQueue(subSession.TenantId);
                 *  }
                 * }*/
            };

            Plugins.Add(mse);
        }
Пример #41
0
        public override void Configure(Funq.Container container)
        {
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new ConcordAPI.ServiceInterface.ConcordyaBasicAuthProvider()     //Sign-in with Basic Auth
            }));

            Plugins.Add(new RegistrationFeature());
            //Plugins.Add(new AutoQueryFeature { MaxLimit = 100 });

            container.Register <ICacheClient>(new MemoryCacheClient());

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(
                                                          new AppSettings().Get(
                                                              "ConcordAPI.Properties.Settings.LocalSQLConnectionString",
                                                              db_conn_string), SqlServerDialect.Provider));

            //container.Resolve
            var userRepository = new OrmLiteAuthRepository <UserAccount, UserAccountDetail>(container.Resolve <IDbConnectionFactory>());

            container.Register <IUserAuthRepository>(userRepository);
            InitialDbTables(container, userRepository);
        }
Пример #42
0
        public void GetMemberList()
        {
            SqlConnection con;                      // connection variables
            SqlCommand    com;
            DateTime      localDate = DateTime.Now; // date now for loot logging date


            try   // connect to clash API
            {
                Console.WriteLine();
                Console.Write("Connecting to Clash API...");
                // set clash api connection token
                string         token     = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImFlNjY2YzJmLWUyNGQtNGUwZS1hNzU5LTcyZjU4NjRjODY5NSIsImlhdCI6MTUzMDMxMTE3Niwic3ViIjoiZGV2ZWxvcGVyLzA5MGJlMzBlLWFhNjEtN2Y0YS1iMjY1LTk3Mjg1NmEzZDVhOSIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjE4LjE5MS4xMjcuODgiLCI3NS4xMzQuOTYuNDciXSwidHlwZSI6ImNsaWVudCJ9XX0.3-S8KOl2DjyO9dhPq4aNjfpyc3Mfei6a_YevQXV0btVU_-d6bJO1pBfuM-7LEtYN5ypXrjAyY5nDjtrHdbJBuQ";
                Funq.Container container = CocCore.Instance(token).Container;  // build new container with api token

                ICocCoreClans clansCore = container.Resolve <ICocCoreClans>(); // CoCNET interface config to clans

                Console.WriteLine("     Connection Established!");

                try  // fetch loot data
                {
                    Console.WriteLine();
                    Console.Write("Fetching member details...");

                    var clan = clansCore.GetClans("#99L9R088"); //get JSON data for clan tag

                    foreach (var obj in clan.MemberList)        // loop through each members details
                    {
                        Member member = new Member();
                        member.Tag               = obj.Tag;
                        member.Name              = obj.Name;
                        member.ExpLevel          = obj.ExpLevel;
                        member.LeagueID          = obj.League.Id;
                        member.LeagueName        = obj.League.Name;
                        member.LeagueIcon        = obj.League.IconUrls["small"];
                        member.Trophies          = obj.Trophies;
                        member.Role              = obj.Role;
                        member.ClanRank          = obj.ClanRank;
                        member.Donations         = obj.Donations;
                        member.DonationsReceived = obj.DonationsReceived;
                        member.LocalDate         = localDate;
                        myMemberList.Add(member);
                    }
                    //Console.WriteLine();
                    Console.WriteLine("     Member details fetched!");
                }
                catch (Exception e)
                {
                    Console.WriteLine();
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Failed to fetch data");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Failed to connect to API");
            }

            Console.WriteLine();
            //Console.WriteLine();

            /*
             * foreach (var member in myMemberList)
             * {
             *  Console.WriteLine(member.Name);
             * }
             */

            try
            {
                using (con = new SqlConnection(Properties.Settings.Default.newLootConStr)) // new sql connection using the db connection string
                {
                    Console.Write("Establishing db connection...");
                    con.Open();     // open db for use
                    Console.WriteLine("     Connected to db!");

                    foreach (var member in myMemberList)
                    {
                        //Console.WriteLine();
                        Console.Write("Creating sql command...");
                        // build sql insert command with loot values

                        using (com = new SqlCommand("AddMemberDetails", con))
                        {
                            com.CommandType = CommandType.StoredProcedure;

                            com.Parameters.AddWithValue("@tag", member.Tag);                             // add values to sql command
                            com.Parameters.AddWithValue("@name", member.Name);                           // add values to sql command
                            com.Parameters.AddWithValue("@expLevel", member.ExpLevel);                   // add values to sql command
                            com.Parameters.AddWithValue("@leagueID", member.LeagueID);                   // add values to sql command
                            com.Parameters.AddWithValue("@leagueName", member.LeagueName);               // add values to sql command
                            com.Parameters.AddWithValue("@leagueIcon", member.LeagueIcon);               // add values to sql command
                            com.Parameters.AddWithValue("@trophies", member.Trophies);                   // add values to sql command
                            com.Parameters.AddWithValue("@role", member.Role);                           // add values to sql command
                            com.Parameters.AddWithValue("@clanRank", member.ClanRank);                   // add values to sql command
                            com.Parameters.AddWithValue("@donations", member.Donations);                 // add values to sql command
                            com.Parameters.AddWithValue("@donationsReceived", member.DonationsReceived); // add values to sql command
                            com.Parameters.AddWithValue("@dateNow", member.LocalDate);                   // add values to sql command

                            Console.WriteLine("     Values added to sql command!");
                            try
                            {
                                //Console.WriteLine();
                                Console.Write("Inserting " + member.Name + " member into db...");
                                com.ExecuteNonQuery();  // execute INSERT command
                                Console.WriteLine("     " + member.Name + " successfully inserted to db!");
                            }
                            catch (SqlException e)
                            {
                                Console.WriteLine();
                                Console.WriteLine(e.Message);
                                Console.WriteLine("Failed to insert data to db");
                            }
                        }
                    }
                    con.Close();
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Failed to connect to db");
            }


            Console.WriteLine();
            Console.WriteLine("Operation Complete");
        }
Пример #43
0
        public void GetClanDetails()
        {
            SqlConnection con;                      // connection variables
            SqlCommand    com;
            DateTime      localDate = DateTime.Now; // date now for loot logging date


            try   // connect to clash API
            {
                Console.Write("Connecting to Clash API...");
                // set clash api connection token
                string         token     = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImFlNjY2YzJmLWUyNGQtNGUwZS1hNzU5LTcyZjU4NjRjODY5NSIsImlhdCI6MTUzMDMxMTE3Niwic3ViIjoiZGV2ZWxvcGVyLzA5MGJlMzBlLWFhNjEtN2Y0YS1iMjY1LTk3Mjg1NmEzZDVhOSIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjE4LjE5MS4xMjcuODgiLCI3NS4xMzQuOTYuNDciXSwidHlwZSI6ImNsaWVudCJ9XX0.3-S8KOl2DjyO9dhPq4aNjfpyc3Mfei6a_YevQXV0btVU_-d6bJO1pBfuM-7LEtYN5ypXrjAyY5nDjtrHdbJBuQ";
                Funq.Container container = CocCore.Instance(token).Container;  // build new container with api token

                ICocCoreClans clansCore = container.Resolve <ICocCoreClans>(); // CoCNET interface config to clans

                Console.WriteLine(" Connection Established!");

                try  // fetch loot data
                {
                    Console.Write("Fetching clan details...");

                    var clan = clansCore.GetClans("#99L9R088");   //get JSON data for clan tag

                    tag              = clan.Tag;
                    name             = clan.Name;
                    badgeUrls        = clan.BadgeUrls["large"];
                    clanLevel        = clan.ClanLevel;
                    clanPoints       = clan.ClanPoints;
                    members          = clan.Members;
                    warWinStreak     = clan.WarWinStreak;
                    warWins          = clan.WarWins;
                    description      = clan.Decsription;
                    type             = clan.Type;
                    requiredTrophies = clan.RequiredTrophies;
                    warFrequency     = clan.WarFrequency;


                    Console.WriteLine("Clan details fetched!");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Failed to fetch data");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Failed to connect to API");
            }


            try
            {
                using (con = new SqlConnection(Properties.Settings.Default.newLootConStr)) // new sql connection using the db connection string
                {
                    Console.Write("Establishing db connection...");
                    con.Open();     // open db for use
                    Console.WriteLine(" Connected to db!");

                    Console.Write("Creating sql command...");
                    // build sql insert command with loot values
                    using (com = new SqlCommand("AddClanDetails", con))
                    {
                        com.CommandType = CommandType.StoredProcedure;

                        com.Parameters.AddWithValue("@tag", tag);  // add values to sql command
                        com.Parameters.AddWithValue("@name", name);
                        com.Parameters.AddWithValue("@badgeUrls", badgeUrls);
                        com.Parameters.AddWithValue("@clanLevel", clanLevel);
                        com.Parameters.AddWithValue("@clanPoints", clanPoints);
                        com.Parameters.AddWithValue("@members", members);
                        com.Parameters.AddWithValue("@warWinStreak", warWinStreak);
                        com.Parameters.AddWithValue("@warWins", warWins);
                        com.Parameters.AddWithValue("@description", description);
                        com.Parameters.AddWithValue("@type", type);
                        com.Parameters.AddWithValue("@requiredTrophies", requiredTrophies);
                        com.Parameters.AddWithValue("@warFrequency", warFrequency);
                        com.Parameters.AddWithValue("@dateNow", localDate);

                        Console.WriteLine("Values added to sql command!");
                        try
                        {
                            Console.Write("Inserting data into db...");
                            com.ExecuteNonQuery();  // execute INSERT command
                            Console.WriteLine(" Loot data successfully inserted to db!");
                            con.Close();
                        }
                        catch (SqlException e)
                        {
                            Console.WriteLine(e.Message);
                            Console.WriteLine("Failed to insert data to db");
                        }
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Failed to connect to db");
            }

            Console.WriteLine();
            Console.WriteLine("Operation Complete");
        }
Пример #44
0
        public void GetLootRecords()
        {
            SqlConnection con;                      // connection variables
            SqlCommand    com;
            DateTime      localDate = DateTime.Now; // date now for loot logging date

            try                                     // connect to clash API
            {
                Console.Write("Connecting to Clash API...");
                // set clash api connection token
                string          token       = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImFlNjY2YzJmLWUyNGQtNGUwZS1hNzU5LTcyZjU4NjRjODY5NSIsImlhdCI6MTUzMDMxMTE3Niwic3ViIjoiZGV2ZWxvcGVyLzA5MGJlMzBlLWFhNjEtN2Y0YS1iMjY1LTk3Mjg1NmEzZDVhOSIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjE4LjE5MS4xMjcuODgiLCI3NS4xMzQuOTYuNDciXSwidHlwZSI6ImNsaWVudCJ9XX0.3-S8KOl2DjyO9dhPq4aNjfpyc3Mfei6a_YevQXV0btVU_-d6bJO1pBfuM-7LEtYN5ypXrjAyY5nDjtrHdbJBuQ";
                Funq.Container  container   = CocCore.Instance(token).Container;     // build new container with api token
                ICocCorePlayers playersCore = container.Resolve <ICocCorePlayers>(); // CoCNET interface config to players core
                Console.WriteLine(" Connection Established!");

                try  // fetch loot data
                {
                    Console.Write("Fetching loot data...");
                    var player = playersCore.GetPlayer("#98QGLCJCR");                               //get JSON data for player tag
                    totalGold   = player.Achievements.Find(x => x.Name == "Gold Grab").Value;       // fetch gold grab achievement
                    totalElixer = player.Achievements.Find(x => x.Name == "Elixir Escapade").Value; // fetch elixer escapade achievement
                    totalDark   = player.Achievements.Find(x => x.Name == "Heroic Heist").Value;    // fetch elixer escapade achievement
                    trophies    = player.Trophies;                                                  // fetch player trophies
                    Console.WriteLine(" Loot data fetched!");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Failed to fetch data");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Failed to connect to API");
            }


            Console.WriteLine();
            Console.WriteLine("Fetched Loot Data to be logged - " + localDate.ToString());
            Console.WriteLine("Total gold value: " + totalGold.ToString());
            Console.WriteLine("Total elixer value: " + totalElixer.ToString());
            Console.WriteLine("Total dark value: " + totalDark.ToString());
            Console.WriteLine("Total trophies value: " + trophies.ToString());
            Console.WriteLine();

            try
            {
                using (con = new SqlConnection(Properties.Settings.Default.newLootConStr)) // new sql connection using the db connection string
                {
                    Console.Write("Establishing db connection...");
                    con.Open();     // open db for use
                    Console.WriteLine(" Connected to db!");

                    Console.Write("Creating sql command...");
                    // build sql insert command with loot values
                    using (com = new SqlCommand("INSERT INTO LootRecords(dateNow, gold, elixer, dark, trophies) VALUES(" +
                                                "@dateNow, @gold, @elixer, @dark, @trophies)", con))
                    {
                        com.Parameters.AddWithValue("dateNow", localDate);  // add values to sql command
                        com.Parameters.AddWithValue("gold", totalGold);
                        com.Parameters.AddWithValue("elixer", totalElixer);
                        com.Parameters.AddWithValue("dark", totalDark);
                        com.Parameters.AddWithValue("trophies", trophies);
                        Console.WriteLine("Values added to sql command!");
                        try
                        {
                            Console.Write("Inserting data into db...");
                            com.ExecuteNonQuery();  // execute INSERT command
                            Console.WriteLine(" Loot data successfully inserted to db!");
                            con.Close();
                        }
                        catch (SqlException e)
                        {
                            Console.WriteLine(e.Message);
                            Console.WriteLine("Failed to insert data to db");
                        }
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Failed to connect to db");
            }

            Console.WriteLine();
            Console.WriteLine("Operation Complete");
        }