Esempio n. 1
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_App == null)
            {
                IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver.Resolve <IAppEnvironmentProvider>();

                _App = appEnvironmentProvider.GetActiveAppEnvironment();
            }

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            string redirectUriHost = $"{context.Request.Scheme}://{context.Request.Host.Value}{_App.GetHostVirtualPath()}SignIn";
            string redirectUri     = $"{_App.GetSsoUrl()}/connect/authorize?scope={string.Join(" ", _App.Security.Scopes)}&client_id={_App.Security.ClientId}&redirect_uri={redirectUriHost}&response_type=id_token token";

            string pathname = _App.GetHostVirtualPath() + (context.Request.Path.HasValue ? context.Request.Path.Value.Substring(1) : string.Empty);

            string state = $@"{{""pathname"":""{pathname}""}}";

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            context.Response.Redirect($"{redirectUri}&state={state}&nonce={nonce}");

            return(Task.CompletedTask);
        }
Esempio n. 2
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            ConfigureWebApiRoutes();
            GlobalFilters.Filters.Add(new HandleErrorAttribute());
            ConfigureMvcRoutes();

            var webConfigFile = this.Server.MapPath("~/Web.config");

            var config = ConfigurationManager.OpenMappedExeConfiguration(
                new ExeConfigurationFileMap {
                ExeConfigFilename = webConfigFile
            },
                ConfigurationUserLevel.None);

            AppEnvironment.Initialize(
                "FinanceManager",
                new InitializationOptions
            {
                ConfigStore            = config.GetConfigStore(),
                EnableLogging          = true,
                GenerateServiceClients = false
            });

            var bundlesJsonFile = this.Server.MapPath("~/Bundles.json");

            AppEnvironment.BundleConfigurator.Configure(File.ReadAllText(bundlesJsonFile));

            ControllerBuilder.Current.SetControllerFactory(new ComposableControllerFactory());
            GlobalConfiguration.Configuration.DependencyResolver = new ComposableDependencyResolver();
        }
Esempio n. 3
0
        public virtual void OnAppStartup()
        {
            string jobSchedulerDbConnectionString = AppEnvironment.GetConfig <string>("JobSchedulerDbConnectionString");

            SqlServerStorage storage = new SqlServerStorage(jobSchedulerDbConnectionString, new SqlServerStorageOptions
            {
                PrepareSchemaIfNecessary     = false,
                UseRecommendedIsolationLevel = true,
                SchemaName = "Jobs"
            });

            if (AppEnvironment.HasConfig("JobSchedulerAzureServiceBusConnectionString"))
            {
                string signalRAzureServiceBusConnectionString = AppEnvironment.GetConfig <string>("JobSchedulerAzureServiceBusConnectionString");

                storage.UseServiceBusQueues(signalRAzureServiceBusConnectionString);
            }

            JobStorage.Current = storage;
            GlobalConfiguration.Configuration.UseStorage(storage);
            GlobalConfiguration.Configuration.UseAutofacActivator(_lifetimeScope);
            GlobalConfiguration.Configuration.UseLogProvider(LogProvider);

            BackgroundJobServerOptions options = new BackgroundJobServerOptions
            {
                Activator = JobActivator
            };

            foreach (IHangfireOptionsCustomizer customizer in Customizers)
            {
                customizer.Customize(GlobalConfiguration.Configuration, options, storage);
            }

            _backgroundJobServer = new BackgroundJobServer(options, storage);
        }
        public virtual void OnAppStartup()
        {
            AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment();

            string jobSchedulerDbConnectionString = activeAppEnvironment.GetConfig <string>("JobSchedulerDbConnectionString");

            SqlServerStorage storage = new SqlServerStorage(jobSchedulerDbConnectionString, new SqlServerStorageOptions
            {
                PrepareSchemaIfNecessary = false,
#if NET461
                TransactionIsolationLevel = IsolationLevel.ReadCommitted,
#else
                TransactionIsolationLevel = System.Data.IsolationLevel.ReadCommitted,
#endif
                SchemaName = "Jobs"
            });

            if (activeAppEnvironment.HasConfig("JobSchedulerAzureServiceBusConnectionString"))
            {
                string signalRAzureServiceBusConnectionString = activeAppEnvironment.GetConfig <string>("JobSchedulerAzureServiceBusConnectionString");

                storage.UseServiceBusQueues(signalRAzureServiceBusConnectionString);
            }

            GlobalConfiguration.Configuration.UseStorage(storage);
            GlobalConfiguration.Configuration.UseAutofacActivator(_lifetimeScope);
            GlobalConfiguration.Configuration.UseLogProvider(LogProvider);

            _backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
            {
                Activator = JobActivator
            }, storage);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <Saml2Configuration>(Configuration.GetSection("Saml2"));
            services.Configure <Saml2Configuration>(saml2Configuration =>
            {
                //saml2Configuration.SignAuthnRequest = true;
                saml2Configuration.SigningCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SigningCertificateFile"]), Configuration["Saml2:SigningCertificatePassword"]);

                //saml2Configuration.SignatureValidationCertificates.Add(CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SignatureValidationCertificateFile"])));
                saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);

                var entityDescriptor = new EntityDescriptor();
                entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Configuration["Saml2:IdPMetadata"]));
                if (entityDescriptor.IdPSsoDescriptor != null)
                {
                    saml2Configuration.AllowedIssuer           = entityDescriptor.EntityId;
                    saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
                    saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
                    saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
                }
                else
                {
                    throw new Exception("IdPSsoDescriptor not loaded from metadata.");
                }
            });

            services.AddSaml2(slidingExpiration: true);

            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
        /// <summary>
        /// Calls <see cref="SwaggerDocsConfig.DescribeAllEnumsAsStrings(bool)"/>
        /// | Make it compatible with owin branching
        /// | Ignores CancellationToken parameter type
        /// </summary>
        public static SwaggerDocsConfig ApplyDefaultApiConfig(this SwaggerDocsConfig doc, HttpConfiguration webApiConfig)
        {
            doc.DescribeAllEnumsAsStrings();
            doc.RootUrl(req => new Uri(req.RequestUri, req.GetOwinContext().Request.PathBase.Value).ToString());
            doc.OperationFilter <OpenApiIgnoreParameterTypeOperationFilter <CancellationToken> >();
            AppEnvironment appEnv = (AppEnvironment)webApiConfig.DependencyResolver.GetService(typeof(AppEnvironment));

            doc.OperationFilter(() => new DefaultAuthorizationOperationFilter {
                AppEnvironment = appEnv
            });

            doc.OAuth2("oauth2")
            .Flow("password")
            .TokenUrl($"{appEnv.GetSsoUrl()}/connect/token")
            .Scopes(scopes =>
            {
                if (!appEnv.Security.Scopes.SequenceEqual(new[] { "openid", "profile", "user_info" }))
                {
                    foreach (string scope in appEnv.Security.Scopes)
                    {
                        scopes.Add(scope, scope);
                    }
                }
            });

            return(doc);
        }
Esempio n. 7
0
        protected override void OnMouseDown(MouseEventArgs e)
        {
            brush  = AppEnvironment.CreateBrush((e.Button != MouseButtons.Left));
            Cursor = Cursors.WaitCursor;

            base.OnMouseDown(e);
        }
        public void ParseToEnvelopes_Positive(
            double widthA,
            double heightA,
            double widthB,
            double heightB,
            params string[] args
            )
        {
            // Arrange
            var expectedEnvelopes = new List <RectangularEnvelope>
            {
                new RectangularEnvelope(widthA, heightA),
                new RectangularEnvelope(widthB, heightB)
            };

            var environment = new AppEnvironment(mockConsoleManager.Object);

            // Act
            var actualEnvelopes = environment.Parse(args);

            // Assert
            Assert.Equal(
                expectedEnvelopes,
                actualEnvelopes.Cast <RectangularEnvelope>(),
                new RectangularEnvelopeEqualityComparer()
                );
        }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            IdentityServerBearerTokenAuthenticationOptions authOptions = new IdentityServerBearerTokenAuthenticationOptions
            {
                ClientId                      = activeAppEnvironment.Security.ClientName,
                Authority                     = activeAppEnvironment.Security.SSOServerUrl,
                DelayLoadMetadata             = true,
                RequiredScopes                = activeAppEnvironment.Security.Scopes,
                ClientSecret                  = activeAppEnvironment.Security.ClientSecret.Sha512(),
                EnableValidationResultCache   = true,
                ValidationResultCacheDuration = TimeSpan.FromMinutes(15),
                // ValidationMode = ValidationMode.ValidationEndpoint,
                ValidationMode           = ValidationMode.Local,
                PreserveAccessToken      = true,
                SigningCertificate       = _certificateProvider.GetSingleSignOnCertificate(),
                BackchannelHttpHandler   = GetHttpClientHandler(nameof(IdentityServerBearerTokenAuthenticationOptions.BackchannelHttpHandler)),
                IntrospectionHttpHandler = GetHttpClientHandler(nameof(IdentityServerBearerTokenAuthenticationOptions.IntrospectionHttpHandler)),
                IssuerName = activeAppEnvironment.Security.SSOServerUrl
            };

            owinApp.UseIdentityServerBearerTokenAuthentication(authOptions);
        }
Esempio n. 10
0
        public override IEnumerable <Client> GetClients()
        {
            AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

            return(new[]
            {
                GetImplicitFlowClient(new BitImplicitFlowClient
                {
                    ClientName = "Test",
                    ClientId = "Test",
                    Secret = "secret",
                    RedirectUris = new List <string>
                    {
                        $@"^(http|https):\/\/(\S+\.)?(bit-framework.com|localhost|127.0.0.1)(:\d+)?\b{activeAppEnvironment.GetHostVirtualPath()}\bSignIn\/?"
                    },
                    PostLogoutRedirectUris = new List <string>
                    {
                        $@"^(http|https):\/\/(\S+\.)?(bit-framework.com|localhost|127.0.0.1)(:\d+)?\b{activeAppEnvironment.GetHostVirtualPath()}\bSignOut\/?"
                    },
                    TokensLifetime = TimeSpan.FromDays(1)
                }),
                GetResourceOwnerFlowClient(new BitResourceOwnerFlowClient
                {
                    ClientName = "TestResOwner",
                    ClientId = "TestResOwner",
                    Secret = "secret",
                    TokensLifetime = TimeSpan.FromDays(1)
                })
            });
        }
Esempio n. 11
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            if (_App == null)
            {
                _App = dependencyResolver.Resolve <AppEnvironment>();
            }

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            string client_Id = context.Request.Query["client_id"] ?? _App.GetSsoDefaultClientId();
            string afterLoginRedirect_uri = context.Request.Query["redirect_uri"] ?? $"{context.Request.Scheme}://{context.Request.Host.Value}{_App.GetHostVirtualPath()}SignIn";

            string ssoRedirectUri = $"{_App.GetSsoUrl()}/connect/authorize?scope={string.Join(" ", _App.Security.Scopes)}&client_id={client_Id}&redirect_uri={afterLoginRedirect_uri}&response_type=id_token token";

            string stateArgs = context.Request.Query["state"] ?? "{}";

            string nonce = randomStringProvider.GetRandomString(12);

            string url = $"{ssoRedirectUri}&state={stateArgs}&nonce={nonce}";

            if (context.Request.Query["acr_values"] != null)
            {
                url += $"&acr_values={context.Request.Query["acr_values"]}";
            }

            context.Response.Redirect(url);

            return(Task.CompletedTask);
        }
Esempio n. 12
0
        public static void Main(string[] args)
        {
            var logPath = "application.log";

            ILogger logger = new AggregatedLogger
                             (
                new FileLogger(logPath),
                new ConsoleLogger()
                             );

            var environment = new AppEnvironment(logger);

            try
            {
                if (!Validator.IsArgumentsValid(args))
                {
                    logger.LogInformation(
                        $"Input must be like <FilePath> <SearchString>;{Environment.NewLine}" +
                        $"<FilePath> <SearchString> <ReplaceableString");

                    return;
                }

                var inputData = environment.Parse(args);

                environment.Run(inputData);
            }
            catch (Exception ex)
            {
                logger.LogInformation(ex.Message);
            }
        }
Esempio n. 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <Saml2Configuration>(Configuration.GetSection("Saml2"));
            services.Configure <Saml2Configuration>(saml2Configuration =>
            {
                //saml2Configuration.SignAuthnRequest = true;
                saml2Configuration.SigningCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SigningCertificateFile"]), Configuration["Saml2:SigningCertificatePassword"]);

                //saml2Configuration.SignatureValidationCertificates.Add(CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SignatureValidationCertificateFile"])));
                saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);

                var entityDescriptor = new EntityDescriptor();
                entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Configuration["Saml2:IdPMetadata"]));
                if (entityDescriptor.IdPSsoDescriptor != null)
                {
                    saml2Configuration.AllowedIssuer           = entityDescriptor.EntityId;
                    saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
                    saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
                    saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
                }
                else
                {
                    throw new Exception("IdPSsoDescriptor not loaded from metadata.");
                }
            });

            services.AddSaml2();

            services.AddMvc();
        }
        private static void ConfigureSplunkLogging(IConfiguration Configuration)
        {
            //Get nlog.config file
            var nlogConfiguration = NLog.LogManager.Configuration;

            //To ignore Splunk certificate errors
            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };

            var webServiceTarget = nlogConfiguration.FindTargetByName <WebServiceTarget>("Splunk");

            webServiceTarget.Url = new Uri(Configuration["SplunkUrl"]);
            MethodCallParameter headerParameter = new MethodCallParameter
            {
                Name   = Configuration["SplunkHeaderName"],
                Layout = Configuration["SplunkHeaderLayout"]
            };

            webServiceTarget.Headers.Add(headerParameter);

            if (!String.IsNullOrWhiteSpace(AppEnvironment) && AppEnvironment.Equals("local"))
            {
                var logconsole = new ConsoleTarget("logconsole");
                nlogConfiguration.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
            }

            NLog.LogManager.Configuration = nlogConfiguration;

            //Set Global Diagnostics context
            GlobalDiagnosticsContext.Set("application", Configuration["Application"]);
            GlobalDiagnosticsContext.Set("environment", AppEnvironment);
        }
Esempio n. 15
0
        protected override void OnFillRegionComputed(Point[][] polygonSet)
        {
            using (PdnGraphicsPath path = new PdnGraphicsPath())
            {
                path.AddPolygons(polygonSet);

                using (PdnRegion fillRegion = new PdnRegion(path))
                {
                    Rectangle boundingBox = fillRegion.GetBoundsInt();

                    Surface        surface = ((BitmapLayer)ActiveLayer).Surface;
                    RenderArgs     ra      = new RenderArgs(surface);
                    HistoryMemento ha;

                    using (PdnRegion affected = Utility.SimplifyAndInflateRegion(fillRegion))
                    {
                        ha = new BitmapHistoryMemento(Name, Image, DocumentWorkspace, DocumentWorkspace.ActiveLayerIndex, affected);
                    }

                    ra.Graphics.CompositingMode = AppEnvironment.GetCompositingMode();
                    ra.Graphics.FillRegion(brush, fillRegion.GetRegionReadOnly());

                    HistoryStack.PushNewMemento(ha);
                    ActiveLayer.Invalidate(boundingBox);
                    Update();
                }
            }
        }
Esempio n. 16
0
        public WebApiMiddlewareConfiguration(IAppEnvironmentProvider appEnvironmentProvider,
                                             IEnumerable <IWebApiConfigurationCustomizer> webApiConfgurationCustomizers, System.Web.Http.Dependencies.IDependencyResolver webApiDependencyResolver, IWebApiOwinPipelineInjector webApiOwinPipelineInjector)
        {
            if (appEnvironmentProvider == null)
            {
                throw new ArgumentNullException(nameof(appEnvironmentProvider));
            }

            if (webApiConfgurationCustomizers == null)
            {
                throw new ArgumentNullException(nameof(webApiConfgurationCustomizers));
            }

            if (webApiDependencyResolver == null)
            {
                throw new ArgumentNullException(nameof(webApiDependencyResolver));
            }

            if (webApiOwinPipelineInjector == null)
            {
                throw new ArgumentNullException(nameof(webApiOwinPipelineInjector));
            }

            _activeAppEnvironment          = appEnvironmentProvider.GetActiveAppEnvironment();
            _webApiConfgurationCustomizers = webApiConfgurationCustomizers;
            _webApiDependencyResolver      = webApiDependencyResolver;
            _webApiOwinPipelineInjector    = webApiOwinPipelineInjector;
        }
        public virtual X509Certificate2 GetSingleSignOnServerCertificate()
        {
            if (_certificate == null)
            {
                string password = AppEnvironment
                                  .GetConfig <string>(AppEnvironment.KeyValues.IdentityCertificatePassword) ?? throw new InvalidOperationException($"{nameof(AppEnvironment.KeyValues.IdentityCertificatePassword)} is null.");

                byte[] pfxRaw = File.ReadAllBytes(PathProvider.MapPath(AppEnvironment.GetConfig(AppEnvironment.KeyValues.IdentityServerCertificatePath, AppEnvironment.KeyValues.IdentityServerCertificatePathDefaultValue) !));

                try
                {
                    _certificate = new X509Certificate2(pfxRaw, password);
                }
                catch
                {
                    _certificate = new X509Certificate2(pfxRaw, password, X509KeyStorageFlags.UserKeySet);
                }

                using X509Chain chain = new X509Chain();
                bool isValid = chain.Build(_certificate);
                if (!isValid && chain.ChainStatus.Any(s => s.Status == X509ChainStatusFlags.NotTimeValid))
                {
                    throw new InvalidOperationException($"A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file.");
                }
            }

            return(_certificate);
        }
Esempio n. 18
0
        /// <summary>
        ///     Sets up the form
        /// </summary>
        private void MainWindow_Load(object sender, EventArgs e)
        {
            // set the title
            this.Text = "Borderless Gaming " + Assembly.GetExecutingAssembly().GetName().Version.ToString(2) + ((UAC.Elevated) ? " [Administrator]" : "");

            // load up settings
            this.toolStripRunOnStartup.Checked    = AppEnvironment.SettingValue("RunOnStartup", false);
            this.toolStripGlobalHotkey.Checked    = AppEnvironment.SettingValue("UseGlobalHotkey", false);
            this.toolStripMouseLock.Checked       = AppEnvironment.SettingValue("UseMouseLockHotkey", false);
            this.toolStripCheckForUpdates.Checked = AppEnvironment.SettingValue("CheckForUpdates", true);
            this.useMouseHideHotkeyWinScrollLockToolStripMenuItem.Checked = AppEnvironment.SettingValue("UseMouseHideHotkey", false);
            this.startMinimizedToTrayToolStripMenuItem.Checked            = AppEnvironment.SettingValue("StartMinimized", false);
            this.hideBalloonTipsToolStripMenuItem.Checked          = AppEnvironment.SettingValue("HideBalloonTips", false);
            this.closeToTrayToolStripMenuItem.Checked              = AppEnvironment.SettingValue("CloseToTray", false);
            this.viewFullProcessDetailsToolStripMenuItem.Checked   = AppEnvironment.SettingValue("ViewAllProcessDetails", false);
            this.useSlowerWindowDetectionToolStripMenuItem.Checked = AppEnvironment.SettingValue("SlowWindowDetection", false);

            // minimize the window if desired (hiding done in Shown)
            if (AppEnvironment.SettingValue("StartMinimized", false) || Tools.StartupParameters.Contains("-minimize"))
            {
                this.WindowState = FormWindowState.Minimized;
            }
            else
            {
                this.WindowState = FormWindowState.Normal;
            }
        }
Esempio n. 19
0
 public override void SetupEnvironment(AppEnvironment env)
 {
     Check.That(env, (e) => e != AppEnvironment.None, "env");
     SetCurrentEnvironment(env)
     .ConstructBudgetAppBasePath()
     .ConfigureLog()
     .ConfigureDatabases();
 }
        public virtual AppEnvironment GetActiveAppEnvironment()
        {
            AppEnvironment result = _appEnvironmentProvider.GetActiveAppEnvironment();

            _appEnvCustomizer?.Invoke(result);

            return(result);
        }
Esempio n. 21
0
 public void SetUp()
 {
     this.transactionScope          = new TransactionScope();
     this.environmentTypeRepository = new EnvironmentTypeRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
     this.appEnvironmentRepostory   = new AppEnvironmentRepository(ConfigurationManager.ConnectionStrings["BBOS"].ConnectionString);
     this.appEnvironment            = BuildMeA.AppEnvironment("CustomAppEnvironment");
     this.environmentType           = BuildMeA.EnvironmentType("CustomAppEnvironment", "Server name 1", "adf_db_name 1", 1, "bravura DOCS Environment Type", "b", "e");
 }
Esempio n. 22
0
        /// <summary>
        /// Find where the FFMpeg report file is from the output using Regex.
        /// </summary>
        /// <param name="lines">The lines<see cref="string"/>.</param>
        /// <returns>The <see cref="string"/>.</returns>
        private static string FindReportFile(string lines)
        {
            Match m;

            return((m = Regex.Match(lines, RegexFindReportFile)).Success
                ? Path.Combine(AppEnvironment.GetLogsDirectory(), m.Groups[1].Value)
                : string.Empty);
        }
Esempio n. 23
0
 public OrderCloudIntegrationsCardConnectService(OrderCloudIntegrationsCardConnectConfig config, string environment, IFlurlClientFactory flurlFactory)
 {
     Config = config;
     // if no credentials are provided in Test and UAT, responses will be mocked.
     noAccountCredentials = string.IsNullOrEmpty(config?.Authorization) && string.IsNullOrEmpty(config?.AuthorizationCad);
     appEnvironment       = (AppEnvironment)Enum.Parse(typeof(AppEnvironment), environment);
     _flurl = flurlFactory.Get($"https://{Config?.Site}.{Config?.BaseUrl}/");
 }
Esempio n. 24
0
 protected RegistryBase(AppEnvironment env)
 {
     RootPath   = env.RootDir;
     LogPath    = env.LogDir;
     VarPath    = env.VarDir;
     ConfigPath = env.ConfigDir;
     AppVersion = env.AppVersion;
 }
Esempio n. 25
0
        public static AppBuilder <TApp> CreateBuilder <TApp>(string[] args) where TApp : BaseApplication, new()
        {
            var env = new AppEnvironment();

            env.Add(new ServiceCollection());
            env.Add(new DefaultConfiguration());
            return(new AppBuilder <TApp>(env));
        }
        public void ParseToEnvelopes_Negative(params string[] args)
        {
            // Arrange
            var environment = new AppEnvironment(mockConsoleManager.Object);

            // Assert
            Assert.Throws <FormatException>(() => environment.Parse(args));
        }
Esempio n. 27
0
        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ValidateRequire())
                {
                    return;
                }

                if (radioBtnType1.Checked)
                {
                    strItemType = radioBtnType1.Text;
                }
                else
                {
                    strItemType = radioBtnType2.Text;
                }

                DataTable dtbResult = m_bizReport.GetCostReports(txtYear.IntValue, Util.ConvertObjectToInteger(cboMonth.SelectedValue)
                                                                 , strProdDateFrom, strProdDateTo, strProdOrderNoFrom, strProdOrderNoTo, strItemType);

                if (!Util.IsNullOrEmptyOrZero(dtbResult.Rows.Count))
                {
                    AppEnvironment.ShowWaitForm("Please Wait", "Initializing Report.");
                    ReportDocument rpt = ReportUtil.LoadReport("RPT020_CostReport.rpt");
                    rpt.SetDataSource(dtbResult);
                    string monthYear = cboMonth.Text + " " + txtYear.Text;

                    DateTime minDate = dtbResult.AsEnumerable()
                                       .Select(cols => cols.Field <DateTime>("DocDate"))
                                       .FirstOrDefault();

                    DateTime maxDate = dtbResult.AsEnumerable()
                                       .Select(cols => cols.Field <DateTime>("DocDate"))
                                       .OrderByDescending(p => p.Ticks)
                                       .FirstOrDefault();

                    //string dateMinMax = minDate.ToString("dd/MM/yyyy") + " - " + maxDate.ToString("dd/MM/yyyy");
                    string dateMinMax = ProdDateFrom.Text + " - " + ProdDateTo.Text;
                    rpt.SetParameterValue("dateMinMax", dateMinMax);
                    rpt.SetParameterValue("MonthYear", monthYear);
                    FrmPreviewReport frmPrint = new FrmPreviewReport();

                    AppEnvironment.CloseWaitForm();

                    ReportUtil.PrintPreviewReport(frmPrint, rpt);
                }
                else
                {
                    MessageBox.Show("Data not Found.", "RPT020", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                AppEnvironment.CloseWaitForm();
                ExceptionManager.ManageException(this, ex);
            }
        }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            owinApp.Map("/core", coreApp =>
            {
                LogProvider.SetCurrentLogProvider(_dependencyManager.Resolve <ILogProvider>());

                AppEnvironment activeAppEnvironment = _appEnvironmentProvider.GetActiveAppEnvironment();

                IdentityServerServiceFactory factory = new IdentityServerServiceFactory()
                                                       .UseInMemoryClients(_dependencyManager.Resolve <IClientProvider>().GetClients().ToArray())
                                                       .UseInMemoryScopes(_scopesProvider.GetScopes());

                factory.UserService =
                    new Registration <IUserService>(_dependencyManager.Resolve <IUserService>());

                factory.ViewService = new Registration <IViewService>(_dependencyManager.Resolve <IViewService>());

                bool requireSslConfigValue = activeAppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false);

                string identityServerSiteName = activeAppEnvironment.GetConfig("IdentityServerSiteName", "Identity Server");

                IdentityServerOptions identityServerOptions = new IdentityServerOptions
                {
                    SiteName           = identityServerSiteName,
                    SigningCertificate = _certificateProvider.GetSingleSignOnCertificate(),
                    Factory            = factory,
                    RequireSsl         = requireSslConfigValue,
                    EnableWelcomePage  = activeAppEnvironment.DebugMode == true,
                    CspOptions         = new CspOptions
                    {
                        // Content security policy
                        Enabled = false
                    },
                    Endpoints = new EndpointOptions
                    {
                        EnableAccessTokenValidationEndpoint   = true,
                        EnableAuthorizeEndpoint               = true,
                        EnableCheckSessionEndpoint            = true,
                        EnableClientPermissionsEndpoint       = true,
                        EnableCspReportEndpoint               = true,
                        EnableDiscoveryEndpoint               = true,
                        EnableEndSessionEndpoint              = true,
                        EnableIdentityTokenValidationEndpoint = true,
                        EnableIntrospectionEndpoint           = true,
                        EnableTokenEndpoint           = true,
                        EnableTokenRevocationEndpoint = true,
                        EnableUserInfoEndpoint        = true
                    }
                };

                coreApp.UseIdentityServer(identityServerOptions);
            });
        }
Esempio n. 29
0
        public ServiceKDS()
        {
            InitializeComponent();

            this.AutoLog   = true;
            _svcInstallLog = AppEnvironment.GetFullSpecialFileNameInAppDir("InstallLog", null, true);

//            args = new string[] { "-autoGenLicence" };
        }
        private void treeObjects_OnDropItemIntoTree(object sender, DragEventArgs e)
        {
            TreeNode myNode = null;

            if (e.Data.GetDataPresent(typeof(TreeNode)))
            {
                myNode = (TreeNode)(e.Data.GetData(typeof(TreeNode)));
            }
            else
            {
                return;
            }

            Point position = new Point(e.X, e.Y);

            position = this.treeObjects.PointToClient(position);

            TreeNode dropNode = this.treeObjects.GetNodeAt(position);

            TreeNode dragNode = null;

            bool needUpdate = false;

            if ((dropNode != null && dropNode.Parent != myNode && dropNode != myNode) || (dropNode == null))
            {
                dragNode = myNode;
                myNode.Remove();
                needUpdate = true;
            }

            if (dragNode != null && needUpdate)
            {
                TestObjectNurse dragNurse = TestObjectNurse.FromTreeNode(dragNode);
                string          newName   = "";
                if (dropNode == null)
                {
                    newName = SpyWindowHelper.DeriveControlName(RootNurseObject, dragNurse.NodeName);
                    treeObjects.Nodes.Add(dragNode);
                }
                else
                {
                    newName = SpyWindowHelper.DeriveControlName(RootNurseObject, dragNurse.NodeName);
                    dropNode.Nodes.Add(dragNode);
                }

                if (newName != dragNurse.NodeName)
                {
                    dragNurse.NodeName = newName;

                    SelectedNodesChanged(dragNode);

                    MessageBox.Show(string.Format(StringResources.LPSpy_SpyMainWindow_ObjNameSameMsg, newName));
                }
                treeObjects.SelectedNode = dragNode;
                AppEnvironment.SetModelChanged(true);
            }
        }
Esempio n. 31
0
 public Startup(SeqServerUri seqServerUri, AppEnvironment appEnvironment)
 {
     this.seqServerUri = seqServerUri;
     this.appEnvironment = appEnvironment;
 }