Ejemplo n.º 1
0
        public override void Execute(object parameter)
        {
            var    g = new SampleDataGenerator();
            string d = g.Translate(ActiveDiagramView.Diagram as PSMDiagram);

            SampleDocumentWindow.Show(MainWindow.dockManager, d, ActiveDiagramView.Diagram as PSMDiagram, g.Log);
        }
Ejemplo n.º 2
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            var app = CreateConfigureBooksApp();

            SwaggerConfig.Register();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configuration.EnableCors();
            GlobalConfiguration.Configuration.EnsureInitialized();

            //Create sample data, import books
            var session = app.OpenSystemSession();

            if (session.EntitySet <IUser>().Count() == 0)
            {
                SampleDataGenerator.CreateBasicTestData(app);
            }
            if (session.EntitySet <IBook>().Count() < 100)
            {
                var import = new GoogleBooksImport();
                import.ImportBooks(app, 200);
            }
        }
Ejemplo n.º 3
0
 private static void CreateSampleData()
 {
     // We create sample data multiple times, so later test wipes out data from previous test.
     // We do not wipe out certain tables
     DataUtility.DeleteAllData(BooksApp, exceptEntities: new Type[] { typeof(IDbInfo), typeof(IDbModuleInfo) });
     SampleDataGenerator.CreateUnitTestData(BooksApp);
 }
Ejemplo n.º 4
0
        private void OnLoadTemplateClick(object sender, RoutedEventArgs e)
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;


            var template = m_Reporter.Templater.LoadTemplate(TemplateSelection.SelectedValue.ToString());

            var sampleTbl  = SampleDataGenerator.GenerateSampleTable();
            var reportData = new SimpleReportData
            {
                TemplateData = template,
                ContentData  = new SimpleContentData
                {
                    ListOfTexts = new Dictionary <string, string> {
                        { "appVersion", version }
                    },
                    ListOfTables = new List <SimpleTableData>
                    {
                        new SimpleTableData
                        {
                            Table = sampleTbl,
                        },
                    },
                },
            };

            var printData = m_Reporter.CreateReport(reportData);

            m_ReportViewer.LoadReport(printData);
        }
Ejemplo n.º 5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ShowWarning("This is Online Marketing sample data generator. This tool should be used for the internal purposes only. It wasn't fully tested and using it may corrupt your data. Internet connection is needed to generate contacts with real names and personas.");

        btnGenerate.Click += (_, __) =>
        {
            var generator = new SampleDataGenerator(SiteContext.CurrentSiteID)
            {
                Information = s => ShowInformation(s),
                Error       = s => ShowError(s)
            };

            var stopwatch = Stopwatch.StartNew();

            generator.Generate(new SampleDataGenerator.GenerationOptions()
            {
                GenerateContactStatuses = chckCreateContactStatuses.Checked,
                ContactsCount           = chckGenerateContacts.Checked ? txtContactsCount.Text.ToInteger(0) : 0,
                ContactsWithRealNames   = chckContactRealNames.Checked,
                GeneratePersonas        = txtGeneratePersonas.Checked,
                ScoresCount             = chckGenerateScores.Checked ? txtScoresCount.Text.ToInteger(0) : 0,
                ActivitiesForEachExistingContactCount = chckGenerateActivities.Checked ? txtActivitiesCount.Text.ToInteger(0) : 0,
            });

            ShowInformation("Time elapsed: " + stopwatch.Elapsed);
        };
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Generate sample data button click handler
    /// </summary>
    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.WebAnalytics", "ManageData"))
        {
            RedirectToAccessDenied("CMS.WebAnalytics", "ManageData");
        }

        // Check whether range is defined
        if ((ucSampleFrom.SelectedDateTime == DateTimeHelper.ZERO_TIME) || (ucSampleTo.SelectedDateTime == DateTimeHelper.ZERO_TIME))
        {
            ShowError(GetString("analyt.settings.invalidrangegenerate"));
            return;
        }

        // Try start sample data generator
        if (SampleDataGenerator.GenerateSampleData(ucSampleFrom.SelectedDateTime, ucSampleTo.SelectedDateTime, SiteContext.CurrentSiteID, drpGenerateObjects.SelectedValue))
        {
            EnableControls(false);
            ViewState["GeneratorStarted"] = true;
        }

        // Start refresh timer
        timeRefresh.Enabled = true;

        // Display info label and loading image
        ReloadInfoPanel();
    }
Ejemplo n.º 7
0
        public void ShouldDeterminWhetherTypeIsSupported()
        {
            SampleDataGenerator dataGenerator = new SampleDataGenerator();

            dataGenerator.SupportsType("string").Should().BeTrue();
            dataGenerator.SupportsType("noType").Should().BeFalse();
        }
Ejemplo n.º 8
0
        public void GetSampleDataTest()
        {
            var data = SampleDataGenerator.GetSampleData(100, DateTimeOffset.Now.AddDays(-19), DateTimeOffset.Now,
                                                         TimeSpan.FromDays(1));

            Assert.IsTrue(data.Count == 20);
            Assert.IsTrue(data[0].Close == data[1].Open);
        }
Ejemplo n.º 9
0
        public static void InitImpl()
        {
            if (BooksApp != null)
            {
                return;
            }
            LogFilePath = ConfigurationManager.AppSettings["LogFilePath"];
            DeleteLocalLogFile();

            var protectedSection = (NameValueCollection)ConfigurationManager.GetSection("protected");
            var loginCryptoKey   = protectedSection["LoginInfoCryptoKey"];
            var connString       = protectedSection["MsSqlConnectionString"];
            var logConnString    = protectedSection["MsSqlLogConnectionString"];

            BooksApp = new BooksEntityApp(loginCryptoKey);
            //Add mock email/sms service
            NotificationListener = new NotificationListener(BooksApp, blockAll: true);
            //Set magic captcha in login settings, so we can pass captcha in unit tests
            var loginStt = BooksApp.GetConfig <Vita.Modules.Login.LoginModuleSettings>();

            loginStt.MagicCaptcha = "Magic";
            BooksApp.Init();
            //connect to database
            var driver     = MsSqlDbDriver.Create(connString);
            var dbOptions  = MsSqlDbDriver.DefaultMsSqlDbOptions;
            var dbSettings = new DbSettings(driver, dbOptions, connString, upgradeMode: DbUpgradeMode.Always); // schemas);
            var resetDb    = ConfigurationManager.AppSettings["ResetDatabase"] == "true";

            if (resetDb)
            {
                Vita.UnitTests.Common.TestUtil.DropSchemaObjects(dbSettings);
            }
            BooksApp.ConnectTo(dbSettings);
            var logDbSettings = new DbSettings(driver, dbOptions, logConnString);

            BooksApp.LoggingApp.ConnectTo(logDbSettings);
            BooksApp.LoggingApp.LogPath = LogFilePath;
            TestUtil.DeleteAllData(BooksApp, exceptEntities: new [] { typeof(IDbInfo), typeof(IDbModuleInfo) });
            TestUtil.DeleteAllData(BooksApp.LoggingApp);

            SampleDataGenerator.CreateUnitTestData(BooksApp);

            // Start service
            var serviceUrl      = ConfigurationManager.AppSettings["ServiceUrl"];
            var jsonNames       = ConfigurationManager.AppSettings["JsonStyleNames"] == "true";
            var jsonMappingMode = jsonNames ? ApiNameMapping.UnderscoreAllLower : ApiNameMapping.Default;

            StartService(serviceUrl, jsonMappingMode);
            // create client
            var clientContext = new OperationContext(BooksApp);

            // change options to None to disable logging of test client calls
            Client = new WebApiClient(clientContext, serviceUrl, clientName: "TestClient", nameMapping: jsonMappingMode,
                                      options: ClientOptions.EnableLog, badRequestContentType: typeof(List <ClientFault>));
            WebApiClient.SharedHttpClientHandler.AllowAutoRedirect = false; //we need it for Redirect test
        }
Ejemplo n.º 10
0
        private void CreateSampleNewDocument()
        {
            SampleDataGenerator sampleDataGenerator = new SampleDataGenerator();

            sampleDataGenerator.GenerateComments = false;
            string sampleDoc = sampleDataGenerator.Translate(diagramNewVersion);

            tbNewDoc.Text = sampleDoc;
            UpdateFolding();
        }
Ejemplo n.º 11
0
        public void TestSampleGenerator()
        {
            Project project = TestUtils.CreateSampleProject();

            SampleDataGenerator generator   = new SampleDataGenerator();
            PSMSchema           psmSchema   = project.SingleVersion.PSMSchemas[0];
            XDocument           xmlDocument = generator.Translate(psmSchema);

            xmlDocument.Save("TestSampleGenerator.xml");
        }
Ejemplo n.º 12
0
        private void CreateSampleNewDocument()
        {
            SampleDataGenerator sampleDataGenerator = new SampleDataGenerator();

            sampleDataGenerator.GenerateComments = false;
            XDocument sampleDoc = sampleDataGenerator.Translate(schemaVersion2);

            tbNewDoc.Text = XDocumentToString(sampleDoc);
            UpdateFolding();
        }
Ejemplo n.º 13
0
        public static void Init()
        {
            Configuration configuration = new Configuration().Configure();

            using (UnitOfWork.Start())
            {
                new SchemaExport(configuration)
                .Execute(false, true, false, true, UnitOfWork.CurrentSession.Connection, null);
                SampleDataGenerator.LoadSampleData();
            }
        }
Ejemplo n.º 14
0
        public void InspectMinimumLimits()
        {
            double           value           = 0;
            IRandomGenerator randomGenerator = new RandomGeneratorStub(0.01);
            var sampleData = new SampleDataGenerator(5, 10, randomGenerator);

            for (var i = 0; i < 100; i++)
            {
                value = Math.Round(sampleData.GetNextValue(), 2);
                Assert.True(value >= 5);
            }
        }
Ejemplo n.º 15
0
        private void GenerateAnotherFile(IFilePresenterTab filetab)
        {
            SampleDataGenerator g = new SampleDataGenerator();

            if (ScopeObject != null)
            {
                g.RootForGeneration = (PSMAssociationMember)ScopeObject;
            }
            XDocument xmlDocument = g.Translate(filetab.ValidationSchema);

            filetab.SetDocumentText(xmlDocument.ToString());
        }
Ejemplo n.º 16
0
        private void CreateSampleDocument()
        {
            SampleDataGenerator sampleDataGenerator = new SampleDataGenerator();

            sampleDataGenerator.GenerateComments = false;
            string sampleDoc = sampleDataGenerator.Translate(diagramOldVersion);

            tbOldDoc.Text = sampleDoc;

            SaveOutput(sampleDoc);
            UpdateFolding();
        }
Ejemplo n.º 17
0
        public void InspectMaximumLimits()
        {
            double           value           = 0;
            IRandomGenerator randomGenerator = new RandomGeneratorStub(0.99);
            var sampleData = new SampleDataGenerator(5, 10, randomGenerator);

            for (int i = 0; i < 100; i++)
            {
                value = Math.Round(sampleData.GetNextValue(), 2);
                Assert.LessOrEqual(value, 10);
            }
        }
Ejemplo n.º 18
0
        private void Reset()
        {
            ActivateExternalTemperature = false;
            TelemetryActive             = true;

            int peakFrequencyInTicks = Convert.ToInt32(Math.Ceiling((double)PEAK_FREQUENCY_IN_SECONDS / REPORT_FREQUENCY_IN_SECONDS));

            _temperatureGenerator         = new SampleDataGenerator(33, 36, 42, peakFrequencyInTicks);
            _humidityGenerator            = new SampleDataGenerator(20, 50);
            _externalTemperatureGenerator = new SampleDataGenerator(-20, 120);

            TelemetryIntervalInSeconds = REPORT_FREQUENCY_IN_SECONDS;
        }
Ejemplo n.º 19
0
        public void Application_Start(object sender, EventArgs e)
        {
            var builder = new ContainerBuilder();

            log4net.Config.XmlConfigurator.Configure();
            InitializeServiceLocator(builder);
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            RegisterRoutes(RouteTable.Routes);
            SampleDataGenerator.LoadSampleData();
        }
Ejemplo n.º 20
0
        public RemoteMonitorTelemetry(ILogger logger, string deviceId)
        {
            _logger   = logger;
            _deviceId = deviceId;

            ActivateExternalTemperature = false;
            TelemetryActive             = true;

            int peakFrequencyInTicks = Convert.ToInt32(Math.Ceiling((double)PEAK_FREQUENCY_IN_SECONDS / REPORT_FREQUENCY_IN_SECONDS));

            _temperatureGenerator         = new SampleDataGenerator(33, 36, 42, peakFrequencyInTicks);
            _speedGenerator               = new SampleDataGenerator(20, 50);
            _externalTemperatureGenerator = new SampleDataGenerator(-20, 120);
        }
Ejemplo n.º 21
0
        private void CreateSampleDocument()
        {
            SampleDataGenerator sampleDataGenerator = new SampleDataGenerator();

            sampleDataGenerator.GenerateComments = false;
            XDocument sampleDoc = sampleDataGenerator.Translate(schemaVersion1, bSchemaAware.IsChecked == true ? "LastSchema.xsd" : null);

            string documentString = XDocumentToString(sampleDoc);

            tbOldDoc.Text = documentString;

            SaveOutput(documentString);
            UpdateFolding();
        }
Ejemplo n.º 22
0
        public RemoteMonitorTelemetry(ILogger logger, string deviceId)
        {
            _logger   = logger;
            _deviceId = deviceId;

            ActivateExternalTemperature = false;
            TelemetryActive             = true;

            int peakFrequencyInTicks = Convert.ToInt32(Math.Ceiling((double)PeakFrequencyInSeconds / ReportFrequencyInSeconds));

            _temperatureGenerator         = new SampleDataGenerator(33, 36, 42, peakFrequencyInTicks);
            _humidityGenerator            = new SampleDataGenerator(20, 50);
            _externalTemperatureGenerator = new SampleDataGenerator(-20, 120);
        }
Ejemplo n.º 23
0
        public void ExpectingPeaks()
        {
            int    numberExpectedPeaks = 4;
            int    peaksSeen           = 0;
            double value;
            var    sampleData = new SampleDataGenerator(5, 10, 15, 25);

            for (int i = 0; i < 120; i++)
            {
                value = Math.Round(sampleData.GetNextValue(), 2);
                if (value > 15)
                {
                    ++peaksSeen;
                }
            }
            Assert.That(numberExpectedPeaks, Is.EqualTo(peaksSeen));
        }
Ejemplo n.º 24
0
        public void ExcludingPeaks()
        {
            var    numberExpectedPeaks = 0;
            var    peaksSeen           = 0;
            double value;
            var    sampleData = new SampleDataGenerator(5, 10);

            for (var i = 0; i < 120; i++)
            {
                value = Math.Round(sampleData.GetNextValue(), 2);
                if (value > 10)
                {
                    ++peaksSeen;
                }
            }
            Assert.Equal(numberExpectedPeaks, peaksSeen);
        }
Ejemplo n.º 25
0
        private void AssertHandlingEvent(Cargo cargo, HandlingEvent evnt, HandlingType expectedEventType,
                                         Location expectedLocation, int completionTimeMs, int registrationTimeMs,
                                         Voyage voyage)
        {
            Assert.AreEqual(expectedEventType, evnt.Type);
            Assert.AreEqual(expectedLocation, evnt.Location);

            DateTime expectedCompletionTime = SampleDataGenerator.Offset(completionTimeMs);

            Assert.AreEqual(expectedCompletionTime, evnt.CompletionTime);

            DateTime expectedRegistrationTime = SampleDataGenerator.Offset(registrationTimeMs);

            Assert.AreEqual(expectedRegistrationTime, evnt.RegistrationTime);

            Assert.AreEqual(voyage, evnt.Voyage);
            Assert.AreEqual(cargo, evnt.Cargo);
        }
Ejemplo n.º 26
0
        public GridOptimizerTests()
        {
            var startTime = DateTimeOffset.Now.AddDays(-10);
            var endTime   = DateTimeOffset.Now;

            _optimizerSettings = new OptimizerSettings
            {
                AccountBalance       = 10000,
                AccountLeverage      = 500,
                BacktesterType       = typeof(OhlcBacktester),
                BacktestSettingsType = typeof(BacktestSettings),
            };

            var data = SampleDataGenerator.GetSampleData(200, startTime, endTime, TimeSpan.FromDays(1));

            var symbol = new OhlcSymbol(new TimeBasedBars(TimeSpan.FromDays(1)))
            {
                Name = "Main"
            };
            var symbolData = new SymbolBacktestData(symbol, data);

            _optimizerSettings.SymbolsData = new List <ISymbolBacktestData> {
                symbolData
            };
            _optimizerSettings.BacktestSettingsParameters = new List <object>
            {
                startTime,
                endTime,
            }.ToArray();
            _optimizerSettings.TradeEngineType    = typeof(BacktestTradeEngine);
            _optimizerSettings.TimerContainerType = typeof(TimerContainer);
            _optimizerSettings.ServerType         = typeof(Server);
            _optimizerSettings.RobotSettingsType  = typeof(RobotParameters);
            _optimizerSettings.RobotType          = typeof(SampleBot);
            _optimizerSettings.Parameters         = new List <OptimizeParameter>()
            {
                new OptimizeParameter("Periods", 30, 50, 10),
                new OptimizeParameter("Deviation", 2),
                new OptimizeParameter("Range", 2000, 6000, 2000)
            };
            _optimizerSettings.BacktesterInterval = TimeSpan.FromHours(1);

            _optimizer = new GridOptimizer(_optimizerSettings);
        }
Ejemplo n.º 27
0
        public override void Execute(object parameter)
        {
            SampleDataGenerator g = new SampleDataGenerator();

            g.MinimalTree = true;
            g.EmptyValues = true;
            g.UseAttributesDefaultValues = false;
            if (ScopeObject != null)
            {
                g.RootForGeneration = (PSMAssociationMember)ScopeObject;
            }
            XDocument xmlDocument = g.Translate((PSMSchema)Current.ActiveDiagram.Schema);

            FilePresenterButtonInfo[] additionalButtonsInfo = new [] { new FilePresenterButtonInfo()
                                                                       {
                                                                           Text = "Generate another file", Icon = ExolutioResourceNames.GetResourceImageSource(ExolutioResourceNames.xmlIcon), UpdateFileContentAction = GenerateAnotherFile
                                                                       } };
            Current.MainWindow.FilePresenter.DisplayFile(xmlDocument, EDisplayedFileType.XML, Current.ActiveDiagram.Caption + "_sample.xml", g.Log, (PSMSchema)Current.ActiveDiagram.Schema, null, additionalButtonsInfo);
        }
        public static void Initialize(bool recreate = false, bool skipSeeding = false)
        {
            using (var ctx = new PeopleSearchContext()) {
                // remove the database if we've been asked to recreate it
                if (recreate)
                {
                    ctx.Database.EnsureDeleted();
                }

                // ensure the database is created; we'll never migrate, so this is fine
                //   for demonstration purposes
                if (ctx.Database.EnsureCreated() && !skipSeeding)
                {
                    // add some interesting seed data; we'll use some census name data to make
                    //   our test data resemble reality
                    ctx.People.AddRange(SampleDataGenerator.GeneratePeople().Take(100));
                    ctx.SaveChanges();
                }
            }
        }
Ejemplo n.º 29
0
        public void ShouldGenerateDataAccordingToGivenTypes()
        {
            SampleDataGenerator dataGenerator = new SampleDataGenerator();

            string stringData = (string)dataGenerator.GenerateForType("string");

            stringData.GetType().Should().Be(typeof(string));

            int intData = (int)dataGenerator.GenerateForType("integer");

            intData.GetType().Should().Be(typeof(int));

            double doubleData = (double)dataGenerator.GenerateForType("double");

            doubleData.GetType().Should().Be(typeof(double));

            DateTime dateTimeData = (DateTime)dataGenerator.GenerateForType("dateTime");

            dateTimeData.GetType().Should().Be(typeof(DateTime));
        }
Ejemplo n.º 30
0
        private static void CreateSampleData()
        {
            var cacheStt         = BooksApp.CacheSettings;
            var saveCacheEnabled = cacheStt.CacheEnabled;

            cacheStt.CacheEnabled = false;

            var entitiesToClear = BooksApp.Model.GetAllEntityTypes().ToList();

            // We create sample data multiple times, so later test wipes out data from previous test.
            // We do not wipe out certain tables
            TestUtil.DeleteAllData(BooksApp, exceptEntities:
                                   new Type[] { typeof(IErrorLog), typeof(IDbInfo), typeof(IDbModuleInfo) });
            if (BooksApp.LoggingApp != null)
            {
                TestUtil.DeleteAllData(BooksApp.LoggingApp, exceptEntities:
                                       new Type[] { typeof(IErrorLog), typeof(IDbInfo), typeof(IDbModuleInfo), typeof(IDbUpgradeBatch), typeof(IDbUpgradeScript) });
            }

            SampleDataGenerator.CreateUnitTestData(BooksApp);
            cacheStt.CacheEnabled = saveCacheEnabled;
        }
Ejemplo n.º 31
0
        // Configure is called after ConfigureServices is called.
        public async void Configure(IApplicationBuilder app,
          IHostingEnvironment env,
          ILoggerFactory loggerFactory,
          SampleDataGenerator sampleData,
          AllReadyContext context,
          IConfiguration configuration)
        {
            loggerFactory.MinimumLevel = LogLevel.Verbose;

            // todo: in RC update we can read from a logging.json config file
            loggerFactory.AddConsole((category, level) =>
            {
                if (category.StartsWith("Microsoft."))
                {
                    return level >= LogLevel.Information;
                }
                return true;
            });

            if (env.IsDevelopment())
            {
                // this will go to the VS output window
                loggerFactory.AddDebug((category, level) =>
                {
                    if (category.StartsWith("Microsoft."))
                    {
                        return level >= LogLevel.Information;
                    }
                    return true;
                });
            }

            // CORS support
            app.UseCors("allReady");

            // Configure the HTTP request pipeline.

            var usCultureInfo = new CultureInfo("en-US");
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(usCultureInfo),
                SupportedCultures = new List<CultureInfo>(new[] { usCultureInfo }),
                SupportedUICultures = new List<CultureInfo>(new[] { usCultureInfo })
            });

            // Add Application Insights to the request pipeline to track HTTP request telemetry data.
            app.UseApplicationInsightsRequestTelemetry();

            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
            }

            // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
            app.UseApplicationInsightsExceptionTelemetry();

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline.
            app.UseIdentity();

            // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
            // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
            if (Configuration["Authentication:Facebook:AppId"] != null)
            {
                app.UseFacebookAuthentication(options =>
                {
                    options.AppId = Configuration["Authentication:Facebook:AppId"];
                    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                });
            }
            // app.UseGoogleAuthentication();

            if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
            {
                app.UseMicrosoftAccountAuthentication(options =>
                {
                    options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
                    options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
                    options.Scope.Add("wl.basic");
                    options.Scope.Add("wl.signin");
                });
            }

            if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
            {
                app.UseTwitterAuthentication(options =>
                {
                    options.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
                    options.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
                });
            }
            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                     name: "areaRoute",
                     template: "{area:exists}/{controller}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            // Add sample data and test admin accounts if specified in Config.Json.
            // for production applications, this should either be set to false or deleted.
            if (env.IsDevelopment() || env.IsEnvironment("Staging"))
            {
                context.Database.Migrate();
            }
            if (Configuration["SampleData:InsertSampleData"] == "true")
            {
                sampleData.InsertTestData();
            }
            if (Configuration["SampleData:InsertTestUsers"] == "true")
            {
                await sampleData.CreateAdminUser();
            }
        }
Ejemplo n.º 32
0
        // Configure is called after ConfigureServices is called.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, 
            IConfiguration configuration)
        {
            // todo: in RC update we can read from a logging.json config file
            loggerFactory.AddConsole((category, level) =>
            {
                if (category.StartsWith("Microsoft."))
                {
                    return level >= LogLevel.Information;
                }
                return true;
            });

            if (env.IsDevelopment())
            {
                // this will go to the VS output window
                loggerFactory.AddDebug((category, level) =>
                {
                    if (category.StartsWith("Microsoft."))
                    {
                        return level >= LogLevel.Information;
                    }
                    return true;
                });
            }

            // CORS support
            app.UseCors("allReady");

            // Configure the HTTP request pipeline.
            var usCultureInfo = new CultureInfo("en-US");
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                SupportedCultures = new List<CultureInfo>(new[] { usCultureInfo }),
                SupportedUICultures = new List<CultureInfo>(new[] { usCultureInfo })
            });

            // Add Application Insights to the request pipeline to track HTTP request telemetry data.
            app.UseApplicationInsightsRequestTelemetry();

            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else if (env.IsStaging())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
            }

            // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
            app.UseApplicationInsightsExceptionTelemetry();

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline.
            app.UseIdentity();

            // Add token-based protection to the request inject pipeline
            app.UseTokenProtection(new TokenProtectedResourceOptions
            {
                Path = "/api/request",
                PolicyName = "api-request-injest"
            });

            // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
            // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
            if (Configuration["Authentication:Facebook:AppId"] != null)
            {
                var options = new FacebookOptions
                {
                    AppId = Configuration["Authentication:Facebook:AppId"],
                    AppSecret = Configuration["Authentication:Facebook:AppSecret"],
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name"
                };
                options.Scope.Add("email");

                app.UseFacebookAuthentication(options);
            }

            if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
            {
                var options = new MicrosoftAccountOptions
                {
                    ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
                    ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
                };

                app.UseMicrosoftAccountAuthentication(options);
            }
            //TODO: mgmccarthy: working on getting email from Twitter
            //http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
            if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
            {
                var options = new TwitterOptions
                {
                    ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"],
                    ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"]
                };

                app.UseTwitterAuthentication(options);
            }

            if (Configuration["Authentication:Google:ClientId"] != null)
            {
                var options = new GoogleOptions
                {
                    ClientId = Configuration["Authentication:Google:ClientId"],
                    ClientSecret = Configuration["Authentication:Google:ClientSecret"]
                };

                app.UseGoogleAuthentication(options);
            }

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}");
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });

            // Add sample data and test admin accounts if specified in Config.Json.
            // for production applications, this should either be set to false or deleted.
            if (env.IsDevelopment() || env.IsEnvironment("Staging"))
            {
                context.Database.Migrate();
            }

            if (Configuration["SampleData:InsertSampleData"] == "true")
            {
                sampleData.InsertTestData();
            }

            if (Configuration["SampleData:InsertTestUsers"] == "true")
            {
                await sampleData.CreateAdminUser();
            }
        }
    private void GenerateBtnClickAction(object sender, EventArgs e)
    {
        var generator = new SampleDataGenerator(SiteContext.CurrentSiteID)
        {
            Information = s => ShowInformation(s),
            Error = s => ShowError(s)
        };

        var stopwatch = Stopwatch.StartNew();

        generator.Generate(new SampleDataGenerator.GenerationOptions()
        {
            GenerateContactStatuses = chckCreateContactStatuses.Checked,
            ContactsCount = chckGenerateContacts.Checked ? txtContactsCount.Text.ToInteger(0) : 0,
            GenerateMergedContacts = chckGenerateMergedContacts.Checked,
            GenerateContactRelationships = chckGenerateRelationships.Checked,
            ContactsWithRealNames = chckContactRealNames.Checked,
            GeneratePersonas = txtGeneratePersonas.Checked,
            GenerateContactGroups = chckGenerateCGs.Checked ? txtCGsCount.Text.ToInteger(0) : 0,
            ScoresCount = chckGenerateScores.Checked ? txtScoresCount.Text.ToInteger(0) : 0,
            ActivitiesForEachExistingContactCount = chckGenerateActivities.Checked ? txtActivitiesCount.Text.ToInteger(0) : 0,
        });

        ShowInformation("Time elapsed: " + stopwatch.Elapsed);
    }
Ejemplo n.º 34
0
    // Configure is called after ConfigureServices is called.
    public async void Configure(IApplicationBuilder app,
      IHostingEnvironment env,
      ILoggerFactory loggerFactory,
      SampleDataGenerator sampleData)
    {

      loggerFactory.MinimumLevel = LogLevel.Information;
      loggerFactory.AddConsole();

      // CORS support
      app.UseCors("allReady");

      // Configure the HTTP request pipeline.

      // Add Application Insights to the request pipeline to track HTTP request telemetry data.
      app.UseApplicationInsightsRequestTelemetry();

      // Add the following to the request pipeline only in development environment.
      if (env.IsDevelopment())
      {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
      }
      else
      {
        // Add Error handling middleware which catches all application specific errors and
        // sends the request to the following path or controller action.
        app.UseExceptionHandler("/Home/Error");
      }

      // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
      app.UseApplicationInsightsExceptionTelemetry();

      // Add static files to the request pipeline.
      app.UseStaticFiles();

      // Add cookie-based authentication to the request pipeline.
      app.UseIdentity();

      // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
      // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
      if (Configuration["Authentication:Facebook:AppId"] != null)
      {
        app.UseFacebookAuthentication(options =>
        {
          options.AppId = Configuration["Authentication:Facebook:AppId"];
          options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
        });
      }
      // app.UseGoogleAuthentication();

      if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
      {
        app.UseMicrosoftAccountAuthentication(options =>
        {
            options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
            options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
			options.Scope.Add("wl.basic");
			options.Scope.Add("wl.signin");
		});
      }

      if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
      {
        app.UseTwitterAuthentication(options =>
        {
          options.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
          options.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
        });
      }
      // Add MVC to the request pipeline.
      app.UseMvc(routes =>
      {
        routes.MapRoute(
                   name: "areaRoute",
                   template: "{area:exists}/{controller}/{action=Index}/{id?}");

        routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
      });

      // Add sample data and test admin accounts if specified in Config.Json.
      // for production applications, this should either be set to false or deleted.
      if (Configuration["Data:InsertSampleData"] == "true")
      {
        sampleData.InsertTestData();
      }
      if (Configuration["Data:InsertTestUsers"] == "true")
      {
        await sampleData.CreateAdminUser();
      }
    }
 public void foo()
 {
     var root = new SampleDataGenerator().Generate();
 }