Ejemplo n.º 1
0
        public void CheckCookie()
        {
            var bootstrapper = new CustomBootstrapper();
            var browser      = new Browser(bootstrapper);

            var response = browser.Get("http://127.0.0.1/Poll/Register");
            var obj      = JObject.Parse(response.Body.AsString()).ToObject <dynamic>();

            var sessionCookie = response.Cookies.FirstOrDefault(x => x.Name == "nancy_long_poll_session_id");

            Assert.IsNotNull(sessionCookie);

            var sessionId = sessionCookie.Value;

            Assert.IsFalse(string.IsNullOrWhiteSpace(sessionId));

            response = browser.Get("http://127.0.0.1/Poll/Register");
            obj      = JObject.Parse(response.Body.AsString()).ToObject <dynamic>();

            sessionCookie = response.Cookies.FirstOrDefault(x => x.Name == "nancy_long_poll_session_id");
            Assert.IsNotNull(sessionCookie);
            var sessionId2 = sessionCookie.Value;

            Assert.IsFalse(string.IsNullOrWhiteSpace(sessionId));
            Assert.AreEqual(sessionId, sessionId2);
        }
        /// <summary>
        /// Extension to bind the request body of the Nancy Context.
        /// </summary>
        /// <typeparam name="T">The object type to be binded</typeparam>
        /// <param name="bootstrapper">The custom bootstrapper to be extended</param>
        /// <param name="ctx">The Nancy Context</param>
        /// <returns>The request object</returns>
        public static T BindRequest <T>(this CustomBootstrapper bootstrapper, NancyContext ctx)
        {
            var requestObject = default(T);

            var requestBody = RequestStream.FromStream(ctx.Request.Body).AsString();

            requestObject = JsonConvert.DeserializeObject <T>(requestBody);

            return(requestObject);
        }
        public static CustomBootstrapper CreateCustomBootstrapper(IIpAddress environment)
        {
            var bootstrapper = new CustomBootstrapper(with =>
            {
                with.Module <IpModule>();
                with.Dependency(environment);
            });

            return(bootstrapper);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            Bootstrapper bootstrapper = new CustomBootstrapper();
            bootstrapper.Start(typeof(CustomBootstrapper).Assembly);

            using (ICrowHttpHost host = CrowHost.ConfigureHost(CrowCore.Container).Host<IDataBusiness>().Start())
            {
                Console.WriteLine("Press enter to stop application.");
                Console.Read();
            }
        }
Ejemplo n.º 5
0
        public void Should_be_able_to_get_root()
        {
            // Given
            var bootstrapper = new CustomBootstrapper();
            var browser      = new Browser(bootstrapper);

            // When
            var result = browser.Get("/", with => with.HttpRequest());

            // Then
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
Ejemplo n.º 6
0
        public void Should_be_able_to_get_a_cms_item_by_key_and_date_and_time()
        {
            // Given
            var bootstrapper = new CustomBootstrapper();
            var browser      = new Browser(bootstrapper);

            // When
            var result = browser.Get("/cms/Homepage_Title_Background/201210202245/", with => with.HttpRequest());

            // Then
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
Ejemplo n.º 7
0
        public void Should_be_able_to_fail_a_get_on_a_random_key()
        {
            // Given
            var bootstrapper = new CustomBootstrapper();
            var browser      = new Browser(bootstrapper);

            // When
            var result = browser.Get(string.Concat("/cms/", DateTime.Now.Millisecond, "/"),
                                     with => with.HttpRequest());

            // Then
            Assert.Equal(HttpStatusCode.Gone, result.StatusCode);
        }
        /// <summary>
        /// Extension to bind the response contents of the Nancy Context.
        /// </summary>
        /// <typeparam name="T">The object type to be binded</typeparam>
        /// <param name="bootstrapper">The custom bootstrapper to be extended</param>
        /// <param name="ctx">The Nancy Context</param>
        /// <returns>The response object</returns>
        public static T BindResponse <T>(this CustomBootstrapper bootstrapper, NancyContext ctx)
        {
            var responseObject = default(T);

            using (var memory = new MemoryStream())
            {
                ctx.Response.Contents.Invoke(memory);

                var json = Encoding.UTF8.GetString(memory.ToArray());
                responseObject = JsonConvert.DeserializeObject <T>(json);
            }

            return(responseObject);
        }
Ejemplo n.º 9
0
        protected override void ConfigureIoc(IContainerBuilder builder)
        {
            // core
            CustomBootstrapper.Configure(builder);

            builder.Singleton <IosAppInfoService, IAppInfoService>();

            builder.Singleton <StoryboardDialogsService, IDialogsService>();
            builder.Singleton <IosExtendedDialogsService, IExtendedDialogsService>();

            // permissions
            builder.Singleton <PermissionsService, IPermissionsService>();
            builder.Singleton <PermissionsManager, IPermissionsManager>();

            // image picker
            builder.Singleton <IosImagePickerService, IImagePickerService>();

            // connectivity
            builder.Singleton <IosConnectivityService, IConnectivityService>();
        }
Ejemplo n.º 10
0
        public void Should_be_able_to_save_a_cms_item()
        {
            // Given

            var bootstrapper = new CustomBootstrapper();
            var browser      = new Browser(bootstrapper);
            var streamReader = new StreamReader(Path.Combine(Environment.CurrentDirectory, "Content", "Logo.png"));
            var multipart    = new BrowserContextMultipartFormData(x =>
                                                                   x.AddFile("Logo.png", "Logo.png", "image/png", streamReader.BaseStream));
            // When
            var result = browser.Post("/cms/",
                                      delegate(BrowserContext with)
            {
                with.HttpRequest();
                with.FormValue("key", "Homepage_Title_Background");
                with.MultiPartFormData(multipart);
            });

            // Then
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
Ejemplo n.º 11
0
        private static ConfigurableBootstrapper CreateConfigurableBootstrapper()
        {
            var bootstrapper = new CustomBootstrapper(with =>
            {
                with.Module <HealthEndpoint>();
                with.Module <HostNameEndpoint>();
                with.Module <IpEndpoint>();
                with.Module <OperatingSystemEndpoint>();
                with.Module <PowershellScriptEndpoint>();
                with.Module <AgentHistoryEndPoint>();
                with.Module <DashboardActivityEndpoint>();
                with.Dependency <IHostNameProcessor>(typeof(HostNameProcessor));
                with.Dependency <IDashboardDataService>(typeof(DashboardDataService));
                with.Dependency <IIpAddressProcessor>(typeof(IpAddressProcessor));
                with.Dependency <IOperatingSystemProcessor>(typeof(OperatingSystemProcessor));
                with.Dependency <IPowershellScript>(typeof(NancyPowershellScript));
                with.Dependency <IScript>(typeof(Script));
            });

            return(bootstrapper);
        }
Ejemplo n.º 12
0
        protected override void ConfigureIoc(IContainerBuilder builder)
        {
            // core
            CustomBootstrapper.Configure(builder);

            builder.Singleton <DroidAppInfoService, IAppInfoService>();

            builder.Singleton <DroidFragmentDialogService, IDialogsService>();
            builder.Singleton <DroidExtendedDialogsService, IExtendedDialogsService>();

            // permissions
            builder.Singleton <PermissionsService, IPermissionsService>();
            builder.Singleton <PermissionsManager, IPermissionsManager>();
            builder.Singleton <RequestResultHandler, IPermissionRequestHandler>();

            // image picker
            builder.Singleton <DroidImagePickerService, IImagePickerService>();
            builder.Singleton <ImagePickerActivityResultHandler, IImagePickerActivityResultHandler>();

            // connectivity
            builder.Singleton <ConnectivityService, IConnectivityService>();
        }
Ejemplo n.º 13
0
        protected override void ConfigureServices(IServiceCollection services)
        {
            var cultureInfo = new CultureInfo("en-US");

            _defaultBootstrapper = new DefaultBootstrapper(
                tenantCode: TENANT_CODE,
                localization: LOCALIZATIONS,
                uiLanguage: UI_LANGUAGE,
                uiCultureInfo: cultureInfo,
                cultureInfo: cultureInfo,
                serviceCollection: services
            );
            _defaultBootstrapper.Initialize(false);

            _customBootstrapper = new CustomBootstrapper(
                tenantCode: TENANT_CODE,
                localization: LOCALIZATIONS,
                uiLanguage: UI_LANGUAGE,
                uiCultureInfo: cultureInfo,
                cultureInfo: cultureInfo,
                serviceCollection: services
            );
            _customBootstrapper.Initialize(true);
        }
Ejemplo n.º 14
0
        public MainWindow()
        {
            Common.Logging.LogManager.Adapter = new NLogLoggerFactoryAdapter(new Common.Logging.Configuration.NameValueCollection());

            //make sure we can connect to the database
            CheckDBConnection();

            //set the log directory
            SetLogDirectory();

            //set the connection string
            DBUtils.SetConnectionString();

            //set EF configuration, necessary for MySql to work
            DBUtils.SetDbConfiguration();

            InitializeComponent();
            DataContext = this;

            //load datagrid layout
            string layoutFile = AppDomain.CurrentDomain.BaseDirectory + "GridLayout.xml";

            if (File.Exists(layoutFile))
            {
                try
                {
                    InstrumentsGrid.DeserializeLayout(File.ReadAllText(layoutFile));
                }
                catch
                {
                }
            }

            LogMessages = new ConcurrentNotifierBlockingList <LogEventInfo>();

            //target is where the log managers send their logs, here we grab the memory target which has a Subject to observe
            var target = LogManager.Configuration.AllTargets.Single(x => x.Name == "myTarget") as MemoryTarget;

            //Log unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

            //we subscribe to the messages and send them all to the LogMessages collection
            if (target != null)
            {
                target.Messages.Subscribe(msg => LogMessages.TryAdd(msg));
            }

            //build the instruments grid context menu
            //we want a button for each BarSize enum value in the UpdateFreqSubMenu menu
            foreach (int value in Enum.GetValues(typeof(BarSize)))
            {
                var button = new MenuItem
                {
                    Header = Regex.Replace(((BarSize)value).ToString(), "([A-Z])", " $1").Trim(),
                    Tag    = (BarSize)value
                };
                button.Click += UpdateHistoricalDataBtn_ItemClick;
                ((MenuItem)Resources["UpdateFreqSubMenu"]).Items.Add(button);
            }

            //create metadata db if it doesn't exist
            var entityContext = new MyDBContext();

            entityContext.Database.Initialize(false);

            //seed the datasources no matter what, because these are added frequently
            Seed.SeedDatasources(entityContext);

            //check for any exchanges, seed the db with initial values if nothing is found
            if (!entityContext.Exchanges.Any())
            {
                Seed.DoSeed();
            }

            //create data db if it doesn't exist
            var dataContext = new DataDBContext();

            dataContext.Database.Initialize(false);
            dataContext.Dispose();

            //create quartz db if it doesn't exist
            QuartzUtils.InitializeDatabase(Settings.Default.databaseType);

            //build the tags menu
            var allTags = entityContext.Tags.ToList();

            BuildTagContextMenu(allTags);

            //build session templates menu
            BuildSetSessionTemplateMenu();

            Instruments = new ObservableCollection <Instrument>();

            var instrumentRepo = new InstrumentRepository(entityContext);
            var instrumentList = instrumentRepo.FindInstruments().Result;

            foreach (Instrument i in instrumentList)
            {
                Instruments.Add(i);
            }

            //create brokers
            var cfRealtimeBroker = new ContinuousFuturesBroker(new QDMSClient.QDMSClient(
                                                                   "RTDBCFClient",
                                                                   "127.0.0.1",
                                                                   Properties.Settings.Default.rtDBReqPort,
                                                                   Properties.Settings.Default.rtDBPubPort,
                                                                   Properties.Settings.Default.hDBPort,
                                                                   Properties.Settings.Default.httpPort,
                                                                   Properties.Settings.Default.apiKey,
                                                                   useSsl: Properties.Settings.Default.useSsl),
                                                               connectImmediately: false);
            var cfHistoricalBroker = new ContinuousFuturesBroker(new QDMSClient.QDMSClient(
                                                                     "HDBCFClient",
                                                                     "127.0.0.1",
                                                                     Properties.Settings.Default.rtDBReqPort,
                                                                     Properties.Settings.Default.rtDBPubPort,
                                                                     Properties.Settings.Default.hDBPort,
                                                                     Properties.Settings.Default.httpPort,
                                                                     Properties.Settings.Default.apiKey,
                                                                     useSsl: Properties.Settings.Default.useSsl),
                                                                 connectImmediately: false);
            var localStorage = DataStorageFactory.Get();

            RealTimeBroker = new RealTimeDataBroker(cfRealtimeBroker, localStorage,
                                                    new IRealTimeDataSource[] {
                //new Xignite(Properties.Settings.Default.xigniteApiToken),
                //new Oanda(Properties.Settings.Default.oandaAccountId, Properties.Settings.Default.oandaAccessToken),
                new IB(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, Properties.Settings.Default.rtdClientIBID),
                //new ForexFeed(Properties.Settings.Default.forexFeedAccessKey, ForexFeed.PriceType.Mid)
            });
            HistoricalBroker = new HistoricalDataBroker(cfHistoricalBroker, localStorage,
                                                        new IHistoricalDataSource[] {
                new Yahoo(),
                new FRED(),
                //new Forexite(),
                new IB(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, Properties.Settings.Default.histClientIBID),
                new Quandl(Properties.Settings.Default.quandlAuthCode),
                new BarChart(Properties.Settings.Default.barChartApiKey)
            });

            var countryCodeHelper = new CountryCodeHelper(entityContext.Countries.ToList());

            EconomicReleaseBroker = new EconomicReleaseBroker("FXStreet",
                                                              new[] { new fx.FXStreet(countryCodeHelper) });

            //create the various servers
            _realTimeServer       = new RealTimeDataServer(Properties.Settings.Default.rtDBPubPort, Properties.Settings.Default.rtDBReqPort, RealTimeBroker);
            _historicalDataServer = new HistoricalDataServer(Properties.Settings.Default.hDBPort, HistoricalBroker);

            //and start them
            _realTimeServer.StartServer();
            _historicalDataServer.StartServer();

            //we also need a client to make historical data requests with
            _client = new QDMSClient.QDMSClient(
                "SERVERCLIENT",
                "localhost",
                Properties.Settings.Default.rtDBReqPort,
                Properties.Settings.Default.rtDBPubPort,
                Properties.Settings.Default.hDBPort,
                Properties.Settings.Default.httpPort,
                Properties.Settings.Default.apiKey,
                useSsl: Properties.Settings.Default.useSsl);
            _client.Connect();
            _client.HistoricalDataReceived += _client_HistoricalDataReceived;

            ActiveStreamGrid.ItemsSource = RealTimeBroker.ActiveStreams;

            //create the scheduler
            var quartzSettings = QuartzUtils.GetQuartzSettings(Settings.Default.databaseType);
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory(quartzSettings);

            _scheduler            = schedulerFactory.GetScheduler();
            _scheduler.JobFactory = new JobFactory(HistoricalBroker,
                                                   Properties.Settings.Default.updateJobEmailHost,
                                                   Properties.Settings.Default.updateJobEmailPort,
                                                   Properties.Settings.Default.updateJobEmailUsername,
                                                   Properties.Settings.Default.updateJobEmailPassword,
                                                   Properties.Settings.Default.updateJobEmailSender,
                                                   Properties.Settings.Default.updateJobEmail,
                                                   new UpdateJobSettings(
                                                       noDataReceived: Properties.Settings.Default.updateJobReportNoData,
                                                       errors: Properties.Settings.Default.updateJobReportErrors,
                                                       outliers: Properties.Settings.Default.updateJobReportOutliers,
                                                       requestTimeouts: Properties.Settings.Default.updateJobTimeouts,
                                                       timeout: Properties.Settings.Default.updateJobTimeout,
                                                       toEmail: Properties.Settings.Default.updateJobEmail,
                                                       fromEmail: Properties.Settings.Default.updateJobEmailSender),
                                                   localStorage,
                                                   EconomicReleaseBroker);
            _scheduler.Start();

            //Take jobs stored in the qmds db and move them to the quartz db - this can be removed in the next version
            MigrateJobs(entityContext, _scheduler);

            var bootstrapper = new CustomBootstrapper(
                DataStorageFactory.Get(),
                EconomicReleaseBroker,
                HistoricalBroker,
                RealTimeBroker,
                Properties.Settings.Default.apiKey);
            var uri  = new Uri((Settings.Default.useSsl ? "https" : "http") + "://localhost:" + Properties.Settings.Default.httpPort);
            var host = new NancyHost(bootstrapper, uri);

            host.Start();

            entityContext.Dispose();

            ShowChangelog();
        }
Ejemplo n.º 15
0
        public void Initialisize()
        {
            _log.Info($"Server is initialisizing ...");

            //create data db if it doesn't exist
            DataDBContext dataContext;

            try
            {
                dataContext = new DataDBContext(_config.LocalStorage.ConnectionString);
                dataContext.Database.Initialize(false);
            }
            catch (System.Data.Entity.Core.ProviderIncompatibleException ex)
            {
                throw new NotSupportedException("Could not connect to context DataDB!", ex);
            }
            dataContext.Dispose();

            MyDBContext entityContext;

            try
            {
                entityContext = new MyDBContext(_config.DataStorage.ConnectionString);
                entityContext.Database.Initialize(false);
            }
            catch (System.Data.Entity.Core.ProviderIncompatibleException ex)
            {
                throw new NotSupportedException("Could not connect to context MyDB!", ex);
            }

            // initialisize helper classes

            var cfRealtimeBroker   = new ContinuousFuturesBroker(GetClient("RTDBCFClient"), false);
            var cfHistoricalBroker = new ContinuousFuturesBroker(GetClient("HDBCFClient"), false);

            IDataStorage localStorage;

            switch (_config.LocalStorage.Type)
            {
            case LocalStorageType.MySql:
                localStorage = new QDMSServer.DataSources.MySQLStorage(_config.LocalStorage.ConnectionString);
                break;

            case LocalStorageType.SqlServer:
                localStorage = new QDMSServer.DataSources.SqlServerStorage(_config.LocalStorage.ConnectionString);
                break;

            default:
                throw new NotSupportedException("Not supported local storage type: " + _config.LocalStorage.Type);
            }

            // create brokers
            _historicalDataBroker  = new HistoricalDataBroker(cfHistoricalBroker, localStorage, new IHistoricalDataSource[] {
                // @todo please add here some historical data sources the service should provide
            });
            _realTimeDataBroker    = new RealTimeDataBroker(cfRealtimeBroker, localStorage, new IRealTimeDataSource[] {
                // @todo please add here some real time data sources the service should provide
            });
            _economicReleaseBroker = new EconomicReleaseBroker("FXStreet",
                                                               new[] { new fx.FXStreet(new CountryCodeHelper(entityContext.Countries.ToList())) });

            // create servers
            _historicalDataServer = new HistoricalDataServer(_config.HistoricalDataService.Port, _historicalDataBroker);
            _realTimeDataServer   = new RealTimeDataServer(_config.RealtimeDataService.PublisherPort, _config.RealtimeDataService.RequestPort, _realTimeDataBroker);

            // create scheduler
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); //todo need settings for scheduler + jobfactory

            _scheduler = schedulerFactory.GetScheduler();

            var bootstrapper = new CustomBootstrapper(
                localStorage,
                _economicReleaseBroker,
                _historicalDataBroker,
                _realTimeDataBroker,
                _scheduler,
                _config.WebService.ApiKey);
            var uri = new Uri((_config.WebService.UseSsl ? "https" : "http") + "://localhost:" + _config.WebService.Port);

            _httpServer = new NancyHost(bootstrapper, uri);

            // ... start the servers
            _historicalDataServer.StartServer();
            _realTimeDataServer.StartServer();
            _httpServer.Start();
            _scheduler.Start();

            _log.Info($"Server is ready.");
        }