コード例 #1
0
ファイル: App.cs プロジェクト: artwallace/PsmFramework
        private static void Initialize()
        {
            Opts = new AppOptions();
            Mgr = new AppManager(Opts, GenerateGraphicsContext(), MainMenuMode.MainMenuModeFactory);

            Mgr.GoToTitleScreenMode();
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: nick-randal/UsefulCSharp
        private static int RunUnderLogging(AppOptions options, DateTime start)
        {
            IRunnerSettings settings = (RunnerSettings)options;

            using (var logger = new Logger())
            using (var rollingFileLogSink = new RollingFileLogSink(settings.FileLoggerSettings))
            {
                try
                {
                    logger.AddLogSink(rollingFileLogSink);

                    SendLogFilePathToExchange(logger, rollingFileLogSink, options);

                    var runner = new Runner(settings, logger);

                    return (int)runner.Go();
                }
                catch (Exception ex)
                {
                    logger.PostException(ex);
                    throw ex;
                }
                finally
                {
                    logger.PostEntryNoTimestamp("Elapsed time {0}", DateTime.UtcNow - start);
                    logger.CompleteAllAsync().Wait(new TimeSpan(0, 0, 3));
                }
            }
        }
コード例 #3
0
ファイル: App.cs プロジェクト: artwallace/PsmFramework
        private static void Cleanup()
        {
            Mgr.Dispose();
            Mgr = null;

            //Persist your options here if you haven't already.
            Opts = null;
        }
コード例 #4
0
        /// <summary>
        /// Creates a custom token to be used with apps to sign in using firebase custom authentication
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> CreateToken()
        {
            var uid = Guid.NewGuid().ToString();

            string project    = "ainfirestoreproject";
            var    mappedPath = Server.MapPath("/Certificate/ainfirestoreproject-139fe45328fd.json");
            var    credential = GoogleCredential.FromFile(mappedPath);

            AppOptions a = new AppOptions()
            {
                Credential = credential,
                ProjectId  = project,
            };

            if (FirebaseAuth.DefaultInstance == null)
            {
                FirebaseApp.Create(a);
            }

            string customToken = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(uid);

            ViewData["Token"] = customToken;
            return(View());
        }
コード例 #5
0
        public void ServiceAccountCredentialScoping()
        {
            var credential = GoogleCredential.FromFile("./resources/service_account.json");
            var options    = new AppOptions()
            {
                Credential = credential,
            };
            var app = FirebaseApp.Create(options);

            Assert.Equal("[DEFAULT]", app.Name);

            var copy = app.Options;

            Assert.NotSame(options, copy);
            Assert.NotSame(credential, copy.Credential);
            Assert.IsType <ServiceAccountCredential>(copy.Credential.UnderlyingCredential);
            var credentialScopes = (copy.Credential.UnderlyingCredential
                                    as ServiceAccountCredential).Scopes;

            foreach (var scope in FirebaseApp.DefaultScopes)
            {
                Assert.Contains(scope, credentialScopes);
            }
        }
コード例 #6
0
        public SendGroupingsPage(bool mainPage, SendType?type = null, string pageTitle = null,
                                 AppOptions appOptions        = null)
        {
            _pageName = string.Concat(nameof(SendGroupingsPage), "_", DateTime.UtcNow.Ticks);
            InitializeComponent();
            SetActivityIndicator(_mainContent);
            _broadcasterService  = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService");
            _syncService         = ServiceContainer.Resolve <ISyncService>("syncService");
            _vaultTimeoutService = ServiceContainer.Resolve <IVaultTimeoutService>("vaultTimeoutService");
            _sendService         = ServiceContainer.Resolve <ISendService>("sendService");
            _vm          = BindingContext as SendGroupingsPageViewModel;
            _vm.Page     = this;
            _vm.MainPage = mainPage;
            _vm.Type     = type;
            _appOptions  = appOptions;
            if (pageTitle != null)
            {
                _vm.PageTitle = pageTitle;
            }

            if (Device.RuntimePlatform == Device.iOS)
            {
                _absLayout.Children.Remove(_fab);
                if (type == null)
                {
                    ToolbarItems.Add(_aboutIconItem);
                }
                ToolbarItems.Add(_addItem);
            }
            else
            {
                ToolbarItems.Add(_syncItem);
                ToolbarItems.Add(_lockItem);
                ToolbarItems.Add(_aboutTextItem);
            }
        }
コード例 #7
0
 public LoginSsoPage(AppOptions appOptions = null)
 {
     _storageService      = ServiceContainer.Resolve <IStorageService>("storageService");
     _messagingService    = ServiceContainer.Resolve <IMessagingService>("messagingService");
     _vaultTimeoutService = ServiceContainer.Resolve <IVaultTimeoutService>("vaultTimeoutService");
     _messagingService.Send("showStatusBar", true);
     _appOptions = appOptions;
     InitializeComponent();
     _vm      = BindingContext as LoginSsoPageViewModel;
     _vm.Page = this;
     _vm.StartTwoFactorAction   = () => Device.BeginInvokeOnMainThread(async() => await StartTwoFactorAsync());
     _vm.StartSetPasswordAction = () =>
                                  Device.BeginInvokeOnMainThread(async() => await StartSetPasswordAsync());
     _vm.SsoAuthSuccessAction = () => Device.BeginInvokeOnMainThread(async() => await SsoAuthSuccessAsync());
     _vm.CloseAction          = async() =>
     {
         _messagingService.Send("showStatusBar", false);
         await Navigation.PopModalAsync();
     };
     if (Device.RuntimePlatform == Device.Android)
     {
         ToolbarItems.RemoveAt(0);
     }
 }
コード例 #8
0
        /// <summary>
        /// Configures the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="options">The options.</param>
        /// <exception cref="ArgumentNullException">command</exception>
        public static void Configure(CommandLineApplication command,
                                     AppOptions options)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            command.Description = "Parse the MQDQ apparatus and text documents " +
                                  "creating an overlaps report into the specified file";
            command.HelpOption("-?|-h|--help");

            CommandArgument appDirArgument = command.Argument("[app-file-dir]",
                                                              "The input apparatus files directory");
            CommandArgument appMaskArgument = command.Argument("[app-file-mask]",
                                                               "The input apparatus files mask");
            CommandArgument outputPathArgument = command.Argument("[output-path]",
                                                                  "The output file path");

            CommandOption regexMaskOption = command.Option("-r|--regex",
                                                           "Use regular expressions in files masks", CommandOptionType.NoValue);
            CommandOption recursiveOption = command.Option("-s|--sub",
                                                           "Recurse subdirectories in matching files masks",
                                                           CommandOptionType.NoValue);

            command.OnExecute(() =>
            {
                options.Command = new ReportOverlapsCommand(
                    appDirArgument.Value,
                    appMaskArgument.Value,
                    outputPathArgument.Value,
                    regexMaskOption.HasValue(),
                    recursiveOption.HasValue());
                return(0);
            });
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: nick-randal/UsefulCSharp
        private static void SendLogFilePathToExchange(ILoggerSync logger, IRollingFileLogSink fileLogSink, AppOptions options)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(options.ExchangePath))
                {
                    logger.PostEntry("Exchange -e option not set, skipping.");
                    return;
                }

                logger.PostEntry("Attempting connection to UI Host '" + SharedConst.LogExchangeNetPipe + "'.");

                var endPoint = new EndpointAddress(SharedConst.LogExchangeNetPipe);
                var pipeFactory = new ChannelFactory<ILogExchange>(new NetNamedPipeBinding(), endPoint);
                var logExchange = pipeFactory.CreateChannel();

                logExchange.ReportLogFilePath(fileLogSink.CurrentLogFilePath ?? "Path not found.");
            }
            catch(EndpointNotFoundException ex)
            {
                logger.PostException(ex);
            }
        }
コード例 #10
0
 /// <inheritdoc />
 public abstract Task <AppOptions> GetOptions(string id, AppOptions options);
コード例 #11
0
 public ApplicationDatabaseOptionsBuilder(IOptions <AppOptions> options)
     : base()
 {
     _options = options.Value;
 }
コード例 #12
0
ファイル: AddEditPage.xaml.cs プロジェクト: xq2/mobile
        public AddEditPage(
            string cipherId       = null,
            CipherType?type       = null,
            string folderId       = null,
            string collectionId   = null,
            string name           = null,
            string uri            = null,
            bool fromAutofill     = false,
            AppOptions appOptions = null,
            bool cloneMode        = false,
            ViewPage viewPage     = null)
        {
            _storageService      = ServiceContainer.Resolve <IStorageService>("storageService");
            _deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService");
            _vaultTimeoutService = ServiceContainer.Resolve <IVaultTimeoutService>("vaultTimeoutService");
            _keyConnectorService = ServiceContainer.Resolve <IKeyConnectorService>("keyConnectorService");

            _appOptions           = appOptions;
            _fromAutofill         = fromAutofill;
            FromAutofillFramework = _appOptions?.FromAutofillFramework ?? false;
            InitializeComponent();
            _vm               = BindingContext as AddEditPageViewModel;
            _vm.Page          = this;
            _vm.CipherId      = cipherId;
            _vm.FolderId      = folderId == "none" ? null : folderId;
            _vm.CollectionIds = collectionId != null ? new HashSet <string>(new List <string> {
                collectionId
            }) : null;
            _vm.CollectionsRepeaterView = _collectionsRepeaterView;
            _vm.Type        = type;
            _vm.DefaultName = name ?? appOptions?.SaveName;
            _vm.DefaultUri  = uri ?? appOptions?.Uri;
            _vm.CloneMode   = cloneMode;
            _vm.ViewPage    = viewPage;
            _vm.Init();
            SetActivityIndicator();
            if (_vm.EditMode && !_vm.CloneMode && Device.RuntimePlatform == Device.Android)
            {
                ToolbarItems.Add(_attachmentsItem);
                ToolbarItems.Add(_deleteItem);
            }
            if (Device.RuntimePlatform == Device.iOS)
            {
                ToolbarItems.Add(_closeItem);
                if (_vm.EditMode && !_vm.CloneMode)
                {
                    ToolbarItems.Add(_moreItem);
                }
                _vm.ShowNotesSeparator = true;

                _typePicker.On <iOS>().SetUpdateMode(UpdateMode.WhenFinished);
                _ownershipPicker.On <iOS>().SetUpdateMode(UpdateMode.WhenFinished);
            }

            _typePicker.ItemDisplayBinding          = new Binding("Key");
            _cardBrandPicker.ItemDisplayBinding     = new Binding("Key");
            _cardExpMonthPicker.ItemDisplayBinding  = new Binding("Key");
            _identityTitlePicker.ItemDisplayBinding = new Binding("Key");
            _folderPicker.ItemDisplayBinding        = new Binding("Key");
            _ownershipPicker.ItemDisplayBinding     = new Binding("Key");

            _loginPasswordEntry.Keyboard = Keyboard.Create(KeyboardFlags.None);

            _nameEntry.ReturnType    = ReturnType.Next;
            _nameEntry.ReturnCommand = new Command(() =>
            {
                if (_vm.Cipher.Type == CipherType.Login)
                {
                    _loginUsernameEntry.Focus();
                }
                else if (_vm.Cipher.Type == CipherType.Card)
                {
                    _cardholderNameEntry.Focus();
                }
            });

            _loginUsernameEntry.ReturnType    = ReturnType.Next;
            _loginUsernameEntry.ReturnCommand = new Command(() => _loginPasswordEntry.Focus());
            _loginPasswordEntry.ReturnType    = ReturnType.Next;
            _loginPasswordEntry.ReturnCommand = new Command(() => _loginTotpEntry.Focus());

            _cardholderNameEntry.ReturnType    = ReturnType.Next;
            _cardholderNameEntry.ReturnCommand = new Command(() => _cardNumberEntry.Focus());
            _cardExpYearEntry.ReturnType       = ReturnType.Next;
            _cardExpYearEntry.ReturnCommand    = new Command(() => _cardCodeEntry.Focus());

            _identityFirstNameEntry.ReturnType         = ReturnType.Next;
            _identityFirstNameEntry.ReturnCommand      = new Command(() => _identityMiddleNameEntry.Focus());
            _identityMiddleNameEntry.ReturnType        = ReturnType.Next;
            _identityMiddleNameEntry.ReturnCommand     = new Command(() => _identityLastNameEntry.Focus());
            _identityLastNameEntry.ReturnType          = ReturnType.Next;
            _identityLastNameEntry.ReturnCommand       = new Command(() => _identityUsernameEntry.Focus());
            _identityUsernameEntry.ReturnType          = ReturnType.Next;
            _identityUsernameEntry.ReturnCommand       = new Command(() => _identityCompanyEntry.Focus());
            _identityCompanyEntry.ReturnType           = ReturnType.Next;
            _identityCompanyEntry.ReturnCommand        = new Command(() => _identitySsnEntry.Focus());
            _identitySsnEntry.ReturnType               = ReturnType.Next;
            _identitySsnEntry.ReturnCommand            = new Command(() => _identityPassportNumberEntry.Focus());
            _identityPassportNumberEntry.ReturnType    = ReturnType.Next;
            _identityPassportNumberEntry.ReturnCommand = new Command(() => _identityLicenseNumberEntry.Focus());
            _identityLicenseNumberEntry.ReturnType     = ReturnType.Next;
            _identityLicenseNumberEntry.ReturnCommand  = new Command(() => _identityEmailEntry.Focus());
            _identityEmailEntry.ReturnType             = ReturnType.Next;
            _identityEmailEntry.ReturnCommand          = new Command(() => _identityPhoneEntry.Focus());
            _identityPhoneEntry.ReturnType             = ReturnType.Next;
            _identityPhoneEntry.ReturnCommand          = new Command(() => _identityAddress1Entry.Focus());
            _identityAddress1Entry.ReturnType          = ReturnType.Next;
            _identityAddress1Entry.ReturnCommand       = new Command(() => _identityAddress2Entry.Focus());
            _identityAddress2Entry.ReturnType          = ReturnType.Next;
            _identityAddress2Entry.ReturnCommand       = new Command(() => _identityAddress3Entry.Focus());
            _identityAddress3Entry.ReturnType          = ReturnType.Next;
            _identityAddress3Entry.ReturnCommand       = new Command(() => _identityCityEntry.Focus());
            _identityCityEntry.ReturnType              = ReturnType.Next;
            _identityCityEntry.ReturnCommand           = new Command(() => _identityStateEntry.Focus());
            _identityStateEntry.ReturnType             = ReturnType.Next;
            _identityStateEntry.ReturnCommand          = new Command(() => _identityPostalCodeEntry.Focus());
            _identityPostalCodeEntry.ReturnType        = ReturnType.Next;
            _identityPostalCodeEntry.ReturnCommand     = new Command(() => _identityCountryEntry.Focus());
        }
コード例 #13
0
 protected override void RegisterServices(IServiceCollection services, AppOptions options)
 {
     services.AddTransient <SetStackDuplicateSignature>();
     services.AddSingleton <ILock>(new EmptyLock());
     base.RegisterServices(services, options);
 }
コード例 #14
0
 public RepositoryBase(IIndex index, IValidator <T> validator, AppOptions options) : base(index, validator)
 {
     _options             = options;
     NotificationsEnabled = options.EnableRepositoryNotifications;
 }
コード例 #15
0
 public EventNotificationsJob(IQueue <EventNotification> queue, SlackService slackService, IMailer mailer, IProjectRepository projectRepository, AppOptions appOptions, EmailOptions emailOptions, IUserRepository userRepository, IEventRepository eventRepository, ICacheClient cacheClient, UserAgentParser parser, ILoggerFactory loggerFactory = null) : base(queue, loggerFactory)
 {
     _slackService      = slackService;
     _mailer            = mailer;
     _projectRepository = projectRepository;
     _appOptions        = appOptions;
     _emailOptions      = emailOptions;
     _userRepository    = userRepository;
     _eventRepository   = eventRepository;
     _cache             = cacheClient;
     _parser            = parser;
 }
コード例 #16
0
 public ExternalApp()
 {
     opts = null;
     Reset();
 }
コード例 #17
0
            public virtual void Reset()
            {
                exception = null;

                if (opts != null)
                   opts.Reset();
                else
                   opts = new Software.AppOptions();

                ResetOutput();

                successExitCode = 0;
            }
コード例 #18
0
ファイル: Program.cs プロジェクト: EgyFalseX/Winform
 public static string GetOptionValue(AppOptions AppOp)
 {
     string ReturnMe = "0";
     System.Data.DataTable dt = FXFW.SqlDB.LoadDataTable(string.Format("Select opvalue From CDOptions Where opname = N'{0}'", AppOp));
     if (dt.Rows.Count > 0)
     {
         ReturnMe = dt.Rows[0][0].ToString();
     }
     return ReturnMe;
 }
コード例 #19
0
ファイル: Program.cs プロジェクト: EgyFalseX/Winform
 public static bool SetOptionValue(AppOptions AppOp, string Value)
 {
     bool ReturnMe = false;
     SqlConnection con = new SqlConnection(FXFW.SqlDB.SqlConStr);
     SqlCommand cmd = new SqlCommand("", con);
     try
     {
         cmd.CommandText = string.Format("Update CDOptions Set opvalue = N'{0}' Where opname = N'{1}'", Value, AppOp);
         con.Open();
         cmd.ExecuteNonQuery();
         ReturnMe = true;
     }
     catch (SqlException)
     { }
     con.Close();
     return ReturnMe;
 }
コード例 #20
0
 public GoogleAuthService(IOptions <AppOptions> appOptions, IAppUsersService appUserStorage)
 {
     _appOptions     = appOptions.Value;
     _appUserStorage = appUserStorage;
 }
コード例 #21
0
 public CheckForRegressionAction(IStackRepository stackRepository, IQueue <WorkItemData> workItemQueue, SemanticVersionParser semanticVersionParser, AppOptions options, ILoggerFactory loggerFactory = null) : base(options, loggerFactory)
 {
     _stackRepository       = stackRepository;
     _workItemQueue         = workItemQueue;
     _semanticVersionParser = semanticVersionParser;
     ContinueOnError        = true;
 }
コード例 #22
0
 public LogFormattingPlugin(AppOptions options) : base(options)
 {
 }
コード例 #23
0
 public QueueNotificationAction(IQueue <EventNotification> notificationQueue, IQueue <WebHookNotification> webHookNotificationQueue, IWebHookRepository webHookRepository, WebHookDataPluginManager webHookDataPluginManager, AppOptions options, ILoggerFactory loggerFactory = null) : base(options, loggerFactory)
 {
     _notificationQueue        = notificationQueue;
     _webHookNotificationQueue = webHookNotificationQueue;
     _webHookRepository        = webHookRepository;
     _webHookDataPluginManager = webHookDataPluginManager;
     ContinueOnError           = true;
 }
コード例 #24
0
 public UsageFormattingPlugin(AppOptions options) : base(options)
 {
 }
コード例 #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddSerializers();
                services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
                AppOptions = Configuration
                             .GetSection("AppOptions")
                             .Get <AppOptions>();
                _logger.LogDebug($"appOptions:{ToJson(AppOptions)}");
                services.Configure <AppOptions>(Configuration.GetSection("AppOptions"));
                var keyVaultSigningOptions = Configuration
                                             .GetSection("KeyVaultSigningOptions")
                                             .Get <KeyVaultSigningOptions>();


                LogOptions <KeyVaultSigningOptions>("KeyVaultSigningOptions");
                LogOptions <CosmosDbConfiguration>("CosmosDbConfiguration");
                LogOptions <IdentityServerOptions>("IdentityServer");
                LogOptions <TokenExchangeOptions>("TokenExchangeOptions");
                LogOptions <ExternalServicesOptions>("ExternalServicesOptions");

                services.Configure <IdentityServerOptions>(Configuration.GetSection("IdentityServer"));
                services.Configure <KeyVaultSigningOptions>(Configuration.GetSection("KeyVaultSigningOptions"));
                services.Configure <TokenExchangeOptions>(Configuration.GetSection("TokenExchangeOptions"));
                services.Configure <ExternalServicesOptions>(Configuration.GetSection("ExternalServicesOptions"));
                services.Configure <SelfManagedCertificatesOptions>(Configuration.GetSection("SelfManagedCertificatesOptions"));
                var dd = Configuration
                         .GetSection("SelfManagedCertificatesOptions")
                         .Get <SelfManagedCertificatesOptions>();

                _logger.LogInformation($"HostingEnvironment.EnvironmentNam:{HostingEnvironment.EnvironmentName}");
                if (AppOptions.DangerousAcceptAnyServerCertificateValidator)
                {
                    Func <HttpMessageHandler> configureHandler = () =>
                    {
                        var handler = new HttpClientHandler
                        {
                            //!DO NOT DO IT IN PRODUCTION!! GO AND CREATE VALID CERTIFICATE!

                            ServerCertificateCustomValidationCallback =
                                (httpRequestMessage, x509Certificate2, x509Chain, sslPolicyErrors) => { return(true); }
                        };

                        return(handler);
                    };


                    services.AddHttpClient(FluffyBunny4.Constants.ExternalServiceClient.HttpClientName)
                    .ConfigurePrimaryHttpMessageHandler(configureHandler);
                }
                else
                {
                    services.AddHttpClient(FluffyBunny4.Constants.ExternalServiceClient.HttpClientName)
                    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler());
                }

                // set forward header keys to be the same value as request's header keys
                // so that redirect URIs and other security policies work correctly.
                var aspNETCORE_FORWARDEDHEADERS_ENABLED = string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_FORWARDEDHEADERS_ENABLED"), "true", StringComparison.OrdinalIgnoreCase);
                if (aspNETCORE_FORWARDEDHEADERS_ENABLED)
                {
                    //To forward the scheme from the proxy in non-IIS scenarios
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                        // Only loopback proxies are allowed by default.
                        // Clear that restriction because forwarders are enabled by explicit
                        // configuration.
                        options.KnownNetworks.Clear();
                        options.KnownProxies.Clear();
                    });
                }
                _logger.LogInformation($"ASPNETCORE_FORWARDEDHEADERS_ENABLED = ${aspNETCORE_FORWARDEDHEADERS_ENABLED}");

                services.AddHttpClient("MyClient")
                .AddCorrelationIdForwarding();     // add the handler to attach the correlation ID to outgoing requests for this named client
                services.AddDefaultCorrelationId(options => {
                    options.AddToLoggingScope = true;
                });
                services.AddHostStorage();
                services.AddScopedStorage();
                services.AddScopedServices();

                //////////////////////////////////////////////
                // refresh_token grace feature begin
                //////////////////////////////////////////////
                services.AddGraceRefreshTokenService();

                services.AddFluffyBunny4AutoMapper();

                //////////////////////////////////////////////
                // refresh_token grace feature end
                //////////////////////////////////////////////


                ///////////////////////////////////////////////////////////////////////////////
                /// AddCosmosOperationalStore
                ///////////////////////////////////////////////////////////////////////////////
                _logger.LogInformation("ConfigureServices - AddCosmosOperationalStore ");

                /*
                 * var cosmosPrimaryKeyVaultFetchStore = new SimpleStringKeyVaultFetchStore(
                 *  new KeyVaultFetchStoreOptions<string>()
                 *  {
                 *      ExpirationSeconds = 3600,
                 *      KeyVaultName = keyVaultName,
                 *      SecretName = cosmosPrimaryKeySecretName
                 *  }, ManagedIdentityHelper.CreateKeyVaultClient(_logger), _logger);
                 * var primaryKey = cosmosPrimaryKeyVaultFetchStore.GetStringValueAsync().GetAwaiter().GetResult();
                 */
                services.Configure <CosmosDbConfiguration>(Configuration.GetSection("CosmosDbConfiguration"));


                services.AddTransient <IResourceValidator, MyDefaultResourceValidator>();
                services.AddClaimsService <MyDefaultClaimsService>();

                var jsonClientFile = Path.Combine(
                    Global.HostContext.ContentRootPath, "settings/clients.json");
                var jsonApiScopesFile = Path.Combine(
                    Global.HostContext.ContentRootPath, "settings/api-scopes.json");
                var jsonApiResourcesFile = Path.Combine(
                    Global.HostContext.ContentRootPath, "settings/api-resources.json");

                var options = new ConfigurationStoreOptions();
                services.AddSingleton(options);

                var operationalStoreOptions = new OperationalStoreOptions
                {
                    EnableTokenCleanup = true
                };
                services.AddSingleton(operationalStoreOptions);

                services.AddSingleton <IConsentExternalService, ConsentExternalService>();

                _logger.LogInformation("ConfigureServices - AddIdentityServer ");

                services.AddSingleton <IHashFixer, HashFixer>();
                services.AddTransient <ITokenResponseGenerator, MyTokenResponseGenerator>();
                var builder = services.AddIdentityServer()
                              //.AddInMemoryIdentityResources(Config.IdentityResources)
                              //     .AddInMemoryApiScopes(Config.ApiScopes)
                              //     .AddInMemoryClientExtras(jsonClientFile)
                              .AddEntityFrameworkStores()
                              .AddInMemoryCaching()
                              .AddExtensionGrantValidator <ArbitraryIdentityGrantValidator>()
                              .AddExtensionGrantValidator <ArbitraryTokenGrantValidator>()
                              .AddExtensionGrantValidator <TokenExchangeGrantValidator>()
                              .AddExtensionGrantValidator <TokenExchangeMutateGrantValidator>()
                              .SwapOutRefreshTokenStore()
                              .SwapOutReferenceTokenStore()
                              .SwapOutTokenRevocationRequestValidator()
                              .SwapOutTokenRevocationResponseGenerator()
                              .SwapOutTokenService <MyDefaultTokenService>();

                // services.AddTenantAdminServices();
                var entityFrameworkConnectionOptions = Configuration
                                                       .GetSection("EntityFrameworkConnectionOptions")
                                                       .Get <EntityFrameworkConnectionOptions>();
                services.Configure <EntityFrameworkConnectionOptions>(Configuration.GetSection("EntityFrameworkConnectionOptions"));
                if (HostingEnvironment.IsDevelopment())
                {
                    _logger.LogDebug(
                        $"entityFrameworkConnectionOptions:{ToJson(entityFrameworkConnectionOptions)}");
                }

                switch (AppOptions.DatabaseType)
                {
                default:
                case AppOptions.DatabaseTypes.InMemory:
                    services.AddInMemoryDbContextOptionsProvider();
                    break;

                case AppOptions.DatabaseTypes.Postgres:
                    //     services.AddEntityFrameworkNpgsql();
                    services.AddPostgresDbContextOptionsProvider();
                    break;

                case AppOptions.DatabaseTypes.CosmosDB:
                    //    services.AddEntityFrameworkCosmos();
                    services.AddCosmosDbContextOptionsProvider();
                    break;

                case AppOptions.DatabaseTypes.SqlServer:
                    //    services.AddEntityFrameworkCosmos();
                    services.AddSqlServerDbContextOptionsProvider();
                    break;
                }



                services.AddDbContextTenantServices();

                //  builder.AddDeveloperSigningCredential();



                //////////////////////////////////////////////
                // IdentityServer sometimes doesn't do a TryAddTransient
                // so we have to replace the services with a remove then add.
                // I like a concept of only one service in a system that only is designed for that one service.
                // IServiceCollection lets you add multiple times and the way you get all of them is to ask for
                // IEnumerable<IClientSecretValidator>.  If you just want one, you ask for IClientSecretValidator and you get
                // the last one added.  Hence, I like replace == remove + add.
                //////////////////////////////////////////////
                // replace IdentityServer's IClientSecretValidator with mine.
                // note: This isn't needed for the refesh_token grace stuff
                //       This is to allow a refresh_token to be redeemed without a client_secret
                services.SwapOutClientSecretValidator <FluffyBunnyClientSecretValidator>();
                services.SwapOutIntrospectionResponseGenerator <FluffyBunnyIntrospectionResponseGenerator>();
                services.SwapOutCustomTokenRequestValidator <FluffyBunnyCustomTokenRequestValidator>();
                services.SwapOutDeviceCodeValidator <MyDeviceCodeValidator>();



                // BASICALLY to make sure your stuff is the one being used, add it last.

                ///////////////////////////////////////////////////////////////////////////////
                // TenantServices
                ///////////////////////////////////////////////////////////////////////////////
                // if you add this it locks you into an url that is {identityServerBase}/{tenantId}/{endpoints} vs
                // {identityServerBase}/{endpoints}
                // I utilize IScopedContext<TenantRequestContext> a SCOPED object that you can inject anywhere in the pipeline to tell you what tenant we have.
                ///////////////////////////////////////////////////////////////////////////////
                _logger.LogInformation("ConfigureServices - AddTenantServices ");
                services.AddTenantServices();
                services.AddTenantResolverCache <TenantResolver>();


                if (keyVaultSigningOptions.Enabled)
                {
                    ///////////////////////////////////////////////////////////////////////////////
                    /// Add KeyVaultSigningServices
                    ///////////////////////////////////////////////////////////////////////////////
                    _logger.LogInformation("ConfigureServices - KeyVaultSigningServices ");
                    services.AddKeyVaultTokenCreationServices();

                    switch (keyVaultSigningOptions.SigningType)
                    {
                    case KeyVaultSigningOptions.SigningTypes.KeyVaultCertificate:
                    {
                        services.AddKeyVaultCertificatesStores(options =>
                            {
                                options.ExpirationSeconds = 43200;
                                options.KeyVaultName      = keyVaultSigningOptions.KeyVaultName;
                                options.KeyIdentifier     = "fluffy-oauth2";
                            });
                        services.AddAzureKeyVaultCertificateSignatureProvider();
                    }
                    break;

                    case KeyVaultSigningOptions.SigningTypes.KeyVaultECDsaKey:
                    {
                        services.AddKeyVaultECDsaStores(options =>
                            {
                                options.ExpirationSeconds = 43200;
                                options.KeyVaultName      = keyVaultSigningOptions.KeyVaultName;
                                options.KeyIdentifier     = "{0}-key-ecc-signing";
                            });

                        services.AddAzureKeyVaultECDsaSignatureProvider();
                    }
                    break;

                    default:
                        throw new Exception("Need a SigningType!");
                    }
                }
                else
                {
                    services.AddSelfManagedValidationKeysStores();
                }


                switch (AppOptions.OperationalStoreType)
                {
                default:
                case AppOptions.DatabaseTypes.InMemory:
                    services.AddInMemoryTenantAwarePersistedGrantStoreOperationalStore();
                    break;

                case AppOptions.DatabaseTypes.CosmosDB:
                    services.AddCosmosOperationalStore();
                    break;

                case AppOptions.DatabaseTypes.EntityFramework:
                    services.AddEntityFrameworkOperationalStore();
                    break;
                }

                services.AddConsentDiscoveryCacheAccessor();
                services.AddDiscoveryCacheAccessor();

                services.AddControllers();
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo {
                        Title = "TokenService", Version = "v1"
                    });
                });
            }
            catch (Exception ex)
            {
                _deferedException = ex;
            }
        }
コード例 #26
0
 public CheckEventDateAction(AppOptions options, ILoggerFactory loggerFactory = null) : base(options, loggerFactory)
 {
     ContinueOnError = true;
 }
コード例 #27
0
ファイル: Program.cs プロジェクト: ajaxx/WireRabbit
        /// <summary>
        /// Application entry point
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            try {
                _options = OptionParser.Parse<AppOptions>();

                // if there is no registered pattern, add a catch-all pattern
                if (_options.Patterns.Count == 0)
                {
                    _options.Patterns.Add("#");
                }

                var random = new Random();
                var randomQueue = "wirerabbit-" + random.Next(0, 0x7fffffff).ToString("X").ToLowerInvariant();

                Console.WriteLine("WireRabbit creating queue: {0}", randomQueue);

                var factory = new ConnectionFactory() { Uri = _options.BrokerUri };
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.ExchangeDeclarePassive(_options.Exchange);
                        // declare a queue that will be used to consume messages
                        channel.QueueDeclare(randomQueue, false, false, true, new Dictionary<string, object>());
                        // bind the routing keys (patterns)
                        foreach (var pattern in _options.Patterns)
                        {
                            channel.QueueBind(randomQueue, _options.Exchange, pattern);
                            Console.WriteLine("WireRabbit binding to {0}", pattern);
                        }
                        // create a consumer
                        var consumer = new QueueingBasicConsumer(channel);
                        // consume the content
                        channel.BasicConsume(randomQueue, false, consumer);

                        Console.WriteLine("WireRabbit is listening ...");

                        while (true)
                        {
                            HandleMessage((BasicDeliverEventArgs) consumer.Queue.Dequeue());
                        }
                    }
                }

            } catch( OptionParsingException e ) {
                Console.Error.WriteLine(e.Message);
                AppOptions.Usage();
            }
        }
コード例 #28
0
 public EventPluginManager(IServiceProvider serviceProvider, AppOptions options, IMetricsClient metricsClient = null, ILoggerFactory loggerFactory = null) : base(serviceProvider, options, metricsClient, loggerFactory)
 {
 }
コード例 #29
0
ファイル: MCTEFollowUp.cs プロジェクト: EgyFalseX/WebSites
 public static string GetOptionValue1(AppOptions AppOp)
 {
     string ReturnMe = "0";
     OleDbConnection con = Connection;
     OleDbCommand cmd = new OleDbCommand("", con);
     try
     {
         cmd.CommandText = string.Format("Select opvalue From CDOptions Where opname = N'{0}'", AppOp);
         con.Open();
         ReturnMe = cmd.ExecuteScalar().ToString();
     }
     catch (SqlException)
     { }
     con.Close();
     return ReturnMe;
 }
コード例 #30
0
        public App(AppOptions appOptions)
        {
            _appOptions                = appOptions ?? new AppOptions();
            _userService               = ServiceContainer.Resolve <IUserService>("userService");
            _broadcasterService        = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService");
            _messagingService          = ServiceContainer.Resolve <IMessagingService>("messagingService");
            _stateService              = ServiceContainer.Resolve <IStateService>("stateService");
            _lockService               = ServiceContainer.Resolve <ILockService>("lockService");
            _syncService               = ServiceContainer.Resolve <ISyncService>("syncService");
            _tokenService              = ServiceContainer.Resolve <ITokenService>("tokenService");
            _cryptoService             = ServiceContainer.Resolve <ICryptoService>("cryptoService");
            _cipherService             = ServiceContainer.Resolve <ICipherService>("cipherService");
            _folderService             = ServiceContainer.Resolve <IFolderService>("folderService");
            _settingsService           = ServiceContainer.Resolve <ISettingsService>("settingsService");
            _collectionService         = ServiceContainer.Resolve <ICollectionService>("collectionService");
            _searchService             = ServiceContainer.Resolve <ISearchService>("searchService");
            _authService               = ServiceContainer.Resolve <IAuthService>("authService");
            _platformUtilsService      = ServiceContainer.Resolve <IPlatformUtilsService>("platformUtilsService");
            _storageService            = ServiceContainer.Resolve <IStorageService>("storageService");
            _secureStorageService      = ServiceContainer.Resolve <IStorageService>("secureStorageService");
            _passwordGenerationService = ServiceContainer.Resolve <IPasswordGenerationService>(
                "passwordGenerationService");
            _i18nService         = ServiceContainer.Resolve <II18nService>("i18nService") as MobileI18nService;
            _deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService");

            Bootstrap();
            _broadcasterService.Subscribe(nameof(App), async(message) =>
            {
                if (message.Command == "showDialog")
                {
                    var details     = message.Data as DialogDetails;
                    var confirmed   = true;
                    var confirmText = string.IsNullOrWhiteSpace(details.ConfirmText) ?
                                      AppResources.Ok : details.ConfirmText;
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        if (!string.IsNullOrWhiteSpace(details.CancelText))
                        {
                            confirmed = await Current.MainPage.DisplayAlert(details.Title, details.Text, confirmText,
                                                                            details.CancelText);
                        }
                        else
                        {
                            await Current.MainPage.DisplayAlert(details.Title, details.Text, confirmText);
                        }
                        _messagingService.Send("showDialogResolve", new Tuple <int, bool>(details.DialogId, confirmed));
                    });
                }
                else if (message.Command == "locked")
                {
                    await LockedAsync(!(message.Data as bool?).GetValueOrDefault());
                }
                else if (message.Command == "lockVault")
                {
                    await _lockService.LockAsync(true);
                }
                else if (message.Command == "logout")
                {
                    if (Migration.MigrationHelpers.Migrating)
                    {
                        return;
                    }
                    Device.BeginInvokeOnMainThread(async() => await LogOutAsync(false));
                }
                else if (message.Command == "loggedOut")
                {
                    // Clean up old migrated key if they ever log out.
                    await _secureStorageService.RemoveAsync("oldKey");
                }
                else if (message.Command == "resumed")
                {
                    if (Device.RuntimePlatform == Device.iOS)
                    {
                        ResumedAsync();
                    }
                }
                else if (message.Command == "slept")
                {
                    if (Device.RuntimePlatform == Device.iOS)
                    {
                        await SleptAsync();
                    }
                }
                else if (message.Command == "migrated")
                {
                    await Task.Delay(1000);
                    await SetMainPageAsync();
                }
                else if (message.Command == "popAllAndGoToTabGenerator" ||
                         message.Command == "popAllAndGoToTabMyVault")
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        if (Current.MainPage is TabsPage tabsPage)
                        {
                            while (tabsPage.Navigation.ModalStack.Count > 0)
                            {
                                await tabsPage.Navigation.PopModalAsync(false);
                            }
                            if (message.Command == "popAllAndGoToTabMyVault")
                            {
                                _appOptions.MyVaultTile = false;
                                tabsPage.ResetToVaultPage();
                            }
                            else
                            {
                                _appOptions.GeneratorTile = false;
                                tabsPage.ResetToGeneratorPage();
                            }
                        }
                    });
                }
            });
        }
コード例 #31
0
 public MarkAsCriticalAction(AppOptions options, ILoggerFactory loggerFactory = null) : base(options, loggerFactory)
 {
     ContinueOnError = true;
 }
コード例 #32
0
        private static AppOptions GetSettings(CoverageProject project)
        {
            // get global settings

            var settings = AppOptions.Get();

            /*
             * ========================================
             * Process PropertyGroup settings
             * ========================================
             * <PropertyGroup Label="FineCodeCoverage">
             *      ...
             * </PropertyGroup>
             */

            var settingsPropertyGroup = project.ProjectFileXElement.XPathSelectElement($"/PropertyGroup[@Label='{Vsix.Code}']");

            if (settingsPropertyGroup != null)
            {
                foreach (var property in settings.GetType().GetProperties())
                {
                    try
                    {
                        var xproperty = settingsPropertyGroup.Descendants().FirstOrDefault(x => x.Name.LocalName.Equals(property.Name, StringComparison.OrdinalIgnoreCase));

                        if (xproperty == null)
                        {
                            continue;
                        }

                        var strValue = xproperty.Value;

                        if (string.IsNullOrWhiteSpace(strValue))
                        {
                            continue;
                        }

                        var strValueArr = strValue.Split('\n', '\r').Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).ToArray();

                        if (!strValue.Any())
                        {
                            continue;
                        }

                        if (TypeMatch(property.PropertyType, typeof(string)))
                        {
                            property.SetValue(settings, strValueArr.FirstOrDefault());
                        }
                        else if (TypeMatch(property.PropertyType, typeof(string[])))
                        {
                            property.SetValue(settings, strValueArr);
                        }

                        else if (TypeMatch(property.PropertyType, typeof(bool), typeof(bool?)))
                        {
                            if (bool.TryParse(strValueArr.FirstOrDefault(), out bool value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(bool[]), typeof(bool?[])))
                        {
                            var arr = strValueArr.Where(x => bool.TryParse(x, out var _)).Select(x => bool.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(int), typeof(int?)))
                        {
                            if (int.TryParse(strValueArr.FirstOrDefault(), out var value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(int[]), typeof(int?[])))
                        {
                            var arr = strValueArr.Where(x => int.TryParse(x, out var _)).Select(x => int.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(short), typeof(short?)))
                        {
                            if (short.TryParse(strValueArr.FirstOrDefault(), out var vaue))
                            {
                                property.SetValue(settings, vaue);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(short[]), typeof(short?[])))
                        {
                            var arr = strValueArr.Where(x => short.TryParse(x, out var _)).Select(x => short.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(long), typeof(long?)))
                        {
                            if (long.TryParse(strValueArr.FirstOrDefault(), out var value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(long[]), typeof(long?[])))
                        {
                            var arr = strValueArr.Where(x => long.TryParse(x, out var _)).Select(x => long.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(decimal), typeof(decimal?)))
                        {
                            if (decimal.TryParse(strValueArr.FirstOrDefault(), out var value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(decimal[]), typeof(decimal?[])))
                        {
                            var arr = strValueArr.Where(x => decimal.TryParse(x, out var _)).Select(x => decimal.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(double), typeof(double?)))
                        {
                            if (double.TryParse(strValueArr.FirstOrDefault(), out var value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(double[]), typeof(double?[])))
                        {
                            var arr = strValueArr.Where(x => double.TryParse(x, out var _)).Select(x => double.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(float), typeof(float?)))
                        {
                            if (float.TryParse(strValueArr.FirstOrDefault(), out var value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(float[]), typeof(float?[])))
                        {
                            var arr = strValueArr.Where(x => float.TryParse(x, out var _)).Select(x => float.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else if (TypeMatch(property.PropertyType, typeof(char), typeof(char?)))
                        {
                            if (char.TryParse(strValueArr.FirstOrDefault(), out var value))
                            {
                                property.SetValue(settings, value);
                            }
                        }
                        else if (TypeMatch(property.PropertyType, typeof(char[]), typeof(char?[])))
                        {
                            var arr = strValueArr.Where(x => char.TryParse(x, out var _)).Select(x => char.Parse(x));
                            if (arr.Any())
                            {
                                property.SetValue(settings, arr);
                            }
                        }

                        else
                        {
                            throw new Exception($"Cannot handle '{property.PropertyType.Name}' yet");
                        }
                    }
                    catch (Exception exception)
                    {
                        Logger.Log($"Failed to override '{property.Name}' setting", exception);
                    }
                }
            }

            // return

            return(settings);
        }
コード例 #33
0
 public WebHookRepository(ExceptionlessElasticConfiguration configuration, IValidator <WebHook> validator, AppOptions options)
     : base(configuration.WebHooks, validator, options)
 {
 }
コード例 #34
0
 public SlackService(IQueue <WebHookNotification> webHookNotificationQueue, FormattingPluginManager pluginManager, ITextSerializer serializer, AppOptions appOptions, ILoggerFactory loggerFactory = null)
 {
     _webHookNotificationQueue = webHookNotificationQueue;
     _pluginManager            = pluginManager;
     _serializer = serializer;
     _appOptions = appOptions;
     _logger     = loggerFactory.CreateLogger <SlackService>();
 }
コード例 #35
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IMvcBuilder builder = services.AddControllersWithViews(options =>
            {
                // it doesn't require tokens for requests made using the following safe HTTP methods: GET, HEAD, OPTIONS, and TRACE
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

                options.Configure();
            })
                                  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                                  .AddDataAnnotationsLocalization()
                                  .AddJsonOptions(options => options.JsonSerializerOptions.Configure())
                                  .ConfigureApiBehaviorOptions(options => options.Configure());

#if DEBUG
            if (Env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation();
            }
#endif

            services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization");

            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[] { "zh-CN", "en-US" };

                options.SetDefaultCulture(supportedCultures[0])
                .AddSupportedCultures(supportedCultures)
                .AddSupportedUICultures(supportedCultures);
            });


            services.AddResponseCompression((options) =>
            {
                // https://resources.infosecinstitute.com/the-breach-attack/
                // Disable compression on dynamically generated pages which over secure connections to avoid security problems.
                options.EnableForHttps = false;
            });


            // Microsoft.Extensions.Caching.StackExchangeRedis
            //services.AddStackExchangeRedisCache(options =>
            //{
            //    options.Configuration = "localhost:5000";
            //    options.InstanceName = "LightBlogCache";
            //});


            ConfigureIdentityServer(services);


            services.AddDbContext <UserDbContext>((sp, options) =>
            {
                // 闭包 or 反模式
                //sp.GetRequiredService<UserDbContext>();
                var identityConnStr = AppOptions.ResolveConnectionString <string>("Identity");
                options.UseSqlServer(identityConnStr,
                                     sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
            });
            services.AddTransient <IRepository <User, int>, UserRepository>();
            services.AddTransient <IUserService <User>, UserService>();


            services.AddScoped <EncryptFormResourceFilterAttribute>();
            services.AddSingleton(AppInfo.Instance.Certificate);
            services.AddScoped <InjectResultActionFilter>();


            var jsPath = DashboardRoutes.Routes.Contains("/js[0-9]+") ? "/js[0-9]+" : "/js[0-9]{3}";
            //DashboardRoutes.Routes.Append(jsPath, new EmbeddedResourceDispatcher("application/javascript", Assembly.GetExecutingAssembly(),$"{typeof(Startup).Namespace}.HangfireCustomDashboard.hangfire.custom.js"));
            DashboardRoutes.Routes.Append(jsPath, new StaticFileDispatcher("application/javascript", "js/hangfire.custom.js", Env.WebRootFileProvider));


            var IdentityConnStr = AppOptions.ResolveConnectionString <string>("Identity");
            services.AddHangfire(x => x.UseSqlServerStorage(IdentityConnStr));
            services.AddHangfireServer();


            services.AddTransient <IJobManageService, JobManageService>();
            services.AddSingleton <JobEntryResolver>();


            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();


            services.AddHostedService <ConsumeScopedServiceHostedService>();
            services.AddScoped <IScopedProcessingService, ScopedProcessingService>();


            //services.AddDNTCaptcha(options =>
            //// options.UseSessionStorageProvider() // -> It doesn't rely on the server or client's times. Also it's the safest one.
            //// options.UseMemoryCacheStorageProvider() // -> It relies on the server's times. It's safer than the CookieStorageProvider.
            //options.UseCookieStorageProvider() // -> It relies on the server and client's times. It's ideal for scalability, because it doesn't save anything in the server's memory
            //// options.UseDistributedCacheStorageProvider() // --> It's ideal for scalability using `services.AddStackExchangeRedisCache()` for instance.

            //// Don't set this line (remove it) to use the installed system's fonts (FontName = "Tahoma").
            //// Or if you want to use a custom font, make sure that font is present in the wwwroot/fonts folder and also use a good and complete font!
            //// .UseCustomFont(Path.Combine(_env.WebRootPath, "fonts", "name.ttf"))
            //// .AbsoluteExpiration(minutes: 7)
            //// .ShowThousandsSeparators(false);
            //);


            services.Configure <MultiTenancyOptions <string> >(Configuration.GetSection("MultiTenancy"));
            services.PostConfigure <MultiTenancyOptions <string> >(options => {
                IRequestTenantProvider <string> provider = null;
                options.RequestTenantProviders.Add(provider);
            });
        }
コード例 #36
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            var eventUploadIntent = new Intent(this, typeof(EventUploadReceiver));

            _eventUploadPendingIntent = PendingIntent.GetBroadcast(this, 0, eventUploadIntent,
                                                                   PendingIntentFlags.UpdateCurrent);
            var alarmIntent = new Intent(this, typeof(LockAlarmReceiver));

            _lockAlarmPendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent,
                                                                 PendingIntentFlags.UpdateCurrent);
            var clearClipboardIntent = new Intent(this, typeof(ClearClipboardAlarmReceiver));

            _clearClipboardPendingIntent = PendingIntent.GetBroadcast(this, 0, clearClipboardIntent,
                                                                      PendingIntentFlags.UpdateCurrent);

            var policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build();

            StrictMode.SetThreadPolicy(policy);

            _deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService");
            _messagingService    = ServiceContainer.Resolve <IMessagingService>("messagingService");
            _broadcasterService  = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService");
            _userService         = ServiceContainer.Resolve <IUserService>("userService");
            _appIdService        = ServiceContainer.Resolve <IAppIdService>("appIdService");
            _storageService      = ServiceContainer.Resolve <IStorageService>("storageService");
            _eventService        = ServiceContainer.Resolve <IEventService>("eventService");

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            UpdateTheme(ThemeManager.GetTheme(true));
            base.OnCreate(savedInstanceState);
            if (!CoreHelpers.InDebugMode())
            {
                Window.AddFlags(Android.Views.WindowManagerFlags.Secure);
            }

#if !FDROID
            var hockeyAppListener = new HockeyAppCrashManagerListener(_appIdService, _userService);
            var hockeyAppTask     = hockeyAppListener.InitAsync(this);
#endif

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            _appOptions = GetOptions();
            LoadApplication(new App.App(_appOptions));

            _broadcasterService.Subscribe(_activityKey, (message) =>
            {
                if (message.Command == "scheduleLockTimer")
                {
                    var alarmManager      = GetSystemService(AlarmService) as AlarmManager;
                    var lockOptionMinutes = (int)message.Data;
                    var lockOptionMs      = lockOptionMinutes * 60000;
                    var triggerMs         = Java.Lang.JavaSystem.CurrentTimeMillis() + lockOptionMs + 10;
                    alarmManager.Set(AlarmType.RtcWakeup, triggerMs, _lockAlarmPendingIntent);
                }
                else if (message.Command == "cancelLockTimer")
                {
                    var alarmManager = GetSystemService(AlarmService) as AlarmManager;
                    alarmManager.Cancel(_lockAlarmPendingIntent);
                }
                else if (message.Command == "startEventTimer")
                {
                    StartEventAlarm();
                }
                else if (message.Command == "stopEventTimer")
                {
                    var task = StopEventAlarmAsync();
                }
                else if (message.Command == "finishMainActivity")
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish());
                }
                else if (message.Command == "listenYubiKeyOTP")
                {
                    ListenYubiKey((bool)message.Data);
                }
                else if (message.Command == "updatedTheme")
                {
                    RestartApp();
                }
                else if (message.Command == "exit")
                {
                    ExitApp();
                }
                else if (message.Command == "copiedToClipboard")
                {
                    var task = ClearClipboardAlarmAsync(message.Data as Tuple <string, int?, bool>);
                }
            });
        }
コード例 #37
0
 public ParallelForEachWebCrawlerStrategy(IHttpClientFactory httpClientFactory, AppOptions options,
                                          IResultSaver resultSaver) :
     base(httpClientFactory, options, resultSaver)
 {
 }
コード例 #38
0
 public ProductEntityTypeConfiguration(AppOptions appOptions)
 {
     this.appOptions = appOptions;
 }
コード例 #39
0
 Task <AppOptions> App([FromServices] AppOptions app)
 {
     return(Task.FromResult(app));
 }
コード例 #40
0
ファイル: AltinnApp.cs プロジェクト: tomolse/altinn-studio
 public override Task <AppOptions> GetOptions(string id, AppOptions options)
 {
     return(Task.FromResult(options));
 }
コード例 #41
0
ファイル: Driver.cs プロジェクト: simas76/scielo-dev
            public static void Main(string[] args)
            {
                Uri uri;
                PDFPoppler reader;
                RawDocument rdoc;
                NormDocument ndoc;
                MarkupHTML marker;
                HTMLDocument htmldoc;
                string filepath, format, num;

                AppOptions options = new AppOptions (args);

                #if DEBUG
                Logger.ActivateDebug ();
                #endif

                if (options.GotNoArguments) {
                Application.Init ();
                MarkerWindow win = new MarkerWindow ();
                win.Show ();
                Application.Run ();
                } else {
                if (!options.Format && !options.numColumns) {
                options.DoHelp ();
                Environment.Exit (0);
                } else if (!options.GotNoArguments && options.Format) {
                format = options.FirstArgument;
                filepath = options.SecondArgument;
                uri = ParsePath (filepath);

                if (uri != null) {
                    try {
                        reader = new PDFPoppler (uri);

                        Logger.Debug ("Transformando PDF", "");

                        rdoc = reader.CreateRawDocument ();
                        ndoc = rdoc.Normalize (format);
                        ndoc.WriteDocument (Environment.CurrentDirectory,
                            Path.GetFileNameWithoutExtension (filepath), "norm");
                        marker = new MarkupHTML (ndoc);
                        htmldoc = marker.CreateHTMLDocument ();
                        htmldoc.WriteDocument (Environment.CurrentDirectory,
                            Path.GetFileNameWithoutExtension (filepath), "htm");
                        reader.GetNonText ();

                        Logger.Debug ("Finalizando", "");
                    } catch (FileNotFoundException) {
                        Logger.Error ("El archivo {0} no existe", filepath);
                        Environment.Exit (1);
                    }
                } else {
                    Logger.Error ("Solo se acepta la ruta a un documento PDF", "");
                    Environment.Exit (1);
                }
                } else if (!options.GotNoArguments && options.numColumns) {
                num = options.FirstArgument;
                filepath = options.SecondArgument;
                format = options.ThirdArgument;
                uri = ParsePath (filepath);

                if (uri != null) {
                    try {
                        Console.WriteLine ("En opcion de columnas");
                        reader = new PDFPoppler (uri);

                        Console.WriteLine ("Transformando PDF ... ");

                        rdoc = reader.CreateRawDocument ();

                        Console.WriteLine ("Buscando las {0} columnas.", num);
                        rdoc.BreakColumns();
                        Console.WriteLine ("Rompio las {0} columnas here......", rdoc.GetText());
                        rdoc.WriteDocument (Environment.CurrentDirectory,
                        Path.GetFileNameWithoutExtension (filepath), "column");
                        Console.WriteLine ("Finalizando\n");
                    } catch (FileNotFoundException) {
                        Console.WriteLine ("Error: El archivo {0} no existe.", filepath);
                        Environment.Exit (1);
                    }
                }
                }
                }
            }