PersistenceSettings

Namespace: Akka.Persistence
We found 10 examples in language CSharp for this search. You will see 29 fragments of code.

Other methods

        public T SetDefaultPersistence(Action<PersistenceSettings> settingFunc)
        {
            var ps = new PersistenceSettings();
            settingFunc.Invoke(ps);
            config.DefaultPersistenceSettings = ps; 
            return (T)this;
        }

        public T SetMainPersistence(Func<PersistenceSettings, PersistenceSettings> settingFunc)
        {
            config.MainPersistenceSettings = settingFunc.Invoke(new PersistenceSettings());
            return (T)this;
        }

        public T SetExperiencesRelationshopPersistence(Func<PersistenceSettings, PersistenceSettings> settingFunc)
        {
            config.ExperienceRelationshipPersistenceSettings = settingFunc.Invoke(new PersistenceSettings());
            return (T)this;
        }


    public void Reset()
    {
      this.Copy(PersistenceSettings.Defaults);
    }

    internal ElementPersistenceSettings GetElementSettings(Type type)
    {
      return PersistenceSettings.DefaultElementSettings;
    }


        [SetUp]
        public void Setup()
        {
            var persistenceSettings = CreatePersistenceSettings();

            var services = new ServiceCollection();
            services.AddAutoMapperAndMaps();
            services.AddPersistence(persistenceSettings);

            serviceProvider = services.BuildServiceProvider(false);
            Insert(); //Insert at least one for the select test
        }

        private PersistenceSettings CreatePersistenceSettings()
        {
            var persistenceSettings = new PersistenceSettings();
            persistenceSettings.ConnectionString = "Data Source=CleanTemplate.db";
            persistenceSettings.Database = DatabaseSource.SQLite3.ToString();
            persistenceSettings.UpdateDatabaseOnStartup = true;
            persistenceSettings.ShowSql = true;
            return persistenceSettings;
        }


        private static void _ConfigureToUpdateDatabase(this IServiceCollection services, PersistenceSettings persistenceSettings)
        {
            services
            // Add common FluentMigrator services
            .AddFluentMigratorCore()
            .ConfigureRunner(rb => rb.ConfigureRunnerSQLite3(persistenceSettings))
            // Enable logging to console in the FluentMigrator way
            .AddLogging(lb => lb.AddFluentMigratorConsole());
        }


        public Task<ICollection<TEntity>> GetAsync(Func<TEntity, bool>? predicate = null)
        {
            var query = Collection.AsQueryable();

            if (predicate != null)
            {
                query = query.Where(predicate);
            }

            ICollection<TEntity> result = query.ToList();
            return Task.FromResult(result);
        }

        public Task<TEntity> GetByIdAsync(int id)
        {
            var result = Collection.AsQueryable()
                .SingleOrDefault(x => x.Id == id);

            if (result == null)
            {
                throw new Exception($"Item not found by ID {id}.");
            }

            return Task.FromResult(result);
        }

        public async Task<int> CreateAsync(TEntity entity)
        {
            var succeeded = await Collection.InsertOneAsync(entity);
            if (!succeeded)
            {
                throw new Exception($"Creating of entity '{typeof(TEntity)}' failed.");
            }

            // hack - first item is created with ID=0, we want first to have ID=1
            if (entity.Id == 0)
            {
                entity.Id = 1;
                await UpdateAsync(0, entity, false);
            }

            return entity.Id;
        }

        public Task UpdateAsync(int id, TEntity entity)
        {
            return UpdateAsync(id, entity, true);
        }

        public Task DeleteAsync(int id)
        {
            return Collection.DeleteOneAsync(x => x.Id == id);
        }

        private async Task UpdateAsync(int id, TEntity entity, bool updateIdFromParameter)
        {
            if (updateIdFromParameter)
            {
                entity.Id = id;
            }

            var found = await Collection.UpdateOneAsync(x => x.Id == id, entity);
            if (!found)
            {
                throw new Exception($"Item not found by ID {id}.");
            }
        }


		/// <inheritdoc />
		public override string ToString()
		{
			return Name;
		}

		/// <inheritdoc />
		protected override async Task AddAsync(TAggregateRoot item, CancellationToken cancellationToken)
		{
			await this.collection
				.InsertOneAsync(item, cancellationToken: cancellationToken)
				.ConfigureAwait(false);
		}

		/// <inheritdoc />
		protected override async Task AddRangeAsync(IEnumerable<TAggregateRoot> items, CancellationToken cancellationToken)
		{
			await this.collection
				.InsertManyAsync(items, cancellationToken: cancellationToken)
				.ConfigureAwait(false);
		}

		/// <inheritdoc />
		protected override async Task RemoveRangeAsync(ISpecification<TAggregateRoot> specification, CancellationToken cancellationToken)
		{
			await this.collection
				.DeleteManyAsync(specification.Predicate, cancellationToken)
				.ConfigureAwait(false);
		}

		/// <inheritdoc />
		protected override async Task RemoveRangeAsync(IEnumerable<TAggregateRoot> items, CancellationToken cancellationToken)
		{
			IList<TAggregateRoot> itemsList = items.ToList();

			IList<WriteModel<TAggregateRoot>> deletes = new List<WriteModel<TAggregateRoot>>();
			foreach(TAggregateRoot item in itemsList)
			{
				Expression<Func<TAggregateRoot, bool>> predicate = this.CreatePrimaryKeyPredicate(item.ID!);
				deletes.Add(new DeleteOneModel<TAggregateRoot>(predicate));
			}

			await this.collection
				.BulkWriteAsync(deletes, new BulkWriteOptions { IsOrdered = false }, cancellationToken)
				.ConfigureAwait(false);
		}

		/// <inheritdoc />
		protected override async Task UpdateAsync(TAggregateRoot item, CancellationToken cancellationToken)
		{
			await this.collection
				.ReplaceOneAsync(this.CreatePrimaryKeyPredicate(item.ID!), item, cancellationToken: cancellationToken)
				.ConfigureAwait(false);
		}


        [OneTimeSetUp]
        public void Setup()
        {
            _result = BrowserTestSuite.Server.Get("test1");
        }

        [Test]
        public void it_should_return_empty()
        {
            _result.ShouldBeEquivalentTo(string.Empty);
        }

        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            var useOracle = configuration.GetValue<bool>("PersistenceSettings:UseOracle");
            var useMsSql = configuration.GetValue<bool>("PersistenceSettings:UseMsSql");
            if (useOracle)
            {
                var connectionString = configuration.GetValue<string>("PersistenceSettings:connectionStrings:oracle");
                services.AddOracle<ApplicationDbContext>(connectionString);
            }
            else if (useMsSql)
            {
                var connectionString = configuration.GetValue<string>("PersistenceSettings:connectionStrings:mssql");
                services.AddMSSQL<ApplicationDbContext>(connectionString);
            }

            services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>());
            services.AddScoped<IIntegrationEventService, IntegrationEventService>();

            return services;
        }

        private static IServiceCollection AddOracle<T>(this IServiceCollection services, string connectionString)
            where T : DbContext
        {
            services.AddDbContext<T>(m => m.UseOracle(connectionString, e => e.MigrationsAssembly(typeof(T).Assembly.FullName)));
            using var scope = services.BuildServiceProvider().CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<T>();
            dbContext.Database.Migrate();
            
            return services;
        }

        // ReSharper disable once InconsistentNaming
        private static IServiceCollection AddMSSQL<T>(this IServiceCollection services, string connectionString)
            where T : DbContext
        {
            services.AddDbContext<T>(m => m.UseSqlServer(connectionString, e => e.MigrationsAssembly(typeof(T).Assembly.FullName)));
            using var scope = services.BuildServiceProvider().CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<T>();
            dbContext.Database.Migrate();

            return services;
        }


        public void EnsureDatabaseIsCreated()
        {

            try
            {
                _localStore.Maintenance.ForDatabase(_persistenceSettings.DatabaseName).Send(new GetStatisticsOperation());
            }
            catch (DatabaseDoesNotExistException)
            {

                _localStore.Maintenance.Server.Send(new CreateDatabaseOperation(new DatabaseRecord(_persistenceSettings.DatabaseName)));

            }

        }


        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Contains the service collection.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            var settingsSection = this.Configuration.GetSection("ApplicationSettings");
            services.Configure<ApplicationSettings>(settingsSection);
            var settings = settingsSection.Get<ApplicationSettings>();

            string connectionString = this.Configuration.GetConnectionString("DefaultConnection");
            string redisConnectionString = this.Configuration.GetConnectionString("RedisConnection");

            if (settings.ShowDiagnostics)
            {
                Log.Information("Connection String: {0}", connectionString);
                Log.Information("Redis String: {0}", redisConnectionString);
            }

            if (!string.IsNullOrWhiteSpace(redisConnectionString))
            {
                // setup Redis
                RedisManager.Initialize(redisConnectionString);
            }

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

            // add options support for CORS preflight.
            services.AddOptions();

            // initialize entity framework and init application framework stores
            services
                .AddIdentity<User, IdentityRole<Guid>>(options =>
                {
                    options.Password.RequiredLength = 8;
                    options.User.RequireUniqueEmail = true;
                })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // setup MVC
            services
                .AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddSessionStateTempDataProvider();

            // add session
            services.AddSession();

            // setup distributed caching mechanisms.
            if (!string.IsNullOrWhiteSpace(redisConnectionString))
            {
                services.AddDistributedRedisCache(option =>
                {
                    option.Configuration = redisConnectionString;
                });
            }
            else
            {
                services.AddDistributedMemoryCache();
            }

            // if thread settings config has a value...
            if (settings.MinimumCompletionPortThreads > 0)
            {
                // setup threading
                ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
                ThreadPool.SetMinThreads(workerThreads, completionPortThreads > settings.MinimumCompletionPortThreads ? completionPortThreads : settings.MinimumCompletionPortThreads);
            }

            // setup data protection service.
            var dataProtectionService = services.AddDataProtection()
                .SetDefaultKeyLifetime(TimeSpan.FromDays(90))
                .SetApplicationName("LatchKeyCloud");

            // based on the storage method, configure data persistence storage
            switch (settings.PersistenceSettings.StorageMethod)
            {
                case DataPersistenceStorageMethods.Redis:
                    Log.Information("Persisting data to Redis");
                    dataProtectionService.PersistKeysToRedis(RedisManager.Connection, "DataProtection-Keys");
                    break;
                case DataPersistenceStorageMethods.FileSystem:
                    // add data protection with a specific folder to share across a farm.
                    // Do note that to remain secure, the folder must have full permissions for the web application user and no other user.
                    if (!string.IsNullOrWhiteSpace(settings.PersistenceSettings.FolderPath))
                    {
                        Log.Information("Persisting data to folder {0}", settings.PersistenceSettings.FolderPath);

                        // add local file system persistance storage
                        dataProtectionService
                            .PersistKeysToFileSystem(new DirectoryInfo(settings.PersistenceSettings.FolderPath));

                        Log.Information("Environment Version: {0}", RuntimeInformation.OSDescription);

                        // get OS version from description
                        var version = OSPlatformExtensions.GetVersion();

                        // need Windows 8/2012 or newer to support DPAPI-NG
                        if (!string.IsNullOrWhiteSpace(settings.PersistenceSettings.Thumbprint) && (version.Major > 6 || (version.Major == 6 && version.Minor >= 2)))
                        {
                            // use NG encryption if a persistance cert thumbprint was specified and OS supports...

                            if (settings.ShowDiagnostics)
                            {
                                Log.Information("Using modern data protection DPAPI-NG, hash: {0}", settings.PersistenceSettings.Thumbprint);
                            }

                            dataProtectionService.ProtectKeysWithDpapiNG("CERTIFICATE=HashId:" + settings.PersistenceSettings.Thumbprint,
                              flags: Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGProtectionDescriptorFlags.None);
                        }
                        else
                        {
                            // otherwise, use DPAPI method.
                            Log.Information("Using local DPAPI data protection method.");
                            dataProtectionService.ProtectKeysWithDpapi();
                        }
                    }

                    break;
                case DataPersistenceStorageMethods.AzureVault:
                    Log.Information("Persisting data to Azure Vault");
                    dataProtectionService.PersistKeysToAzureBlobStorage(new Uri(settings.PersistenceSettings.AzureBlobUriWithToken));
                    break;
            }

            // if an instrumentation key is specified...
            if (!string.IsNullOrWhiteSpace(settings.InsightsInstrumentationKey))
            {
                services.AddApplicationInsightsTelemetry(settings.InsightsInstrumentationKey);
            }
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">Contains the application builder.</param>
        /// <param name="env">Contains the hosting environment.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var settingsSection = this.Configuration.GetSection("ApplicationSettings");
            var settings = settingsSection.Get<ApplicationSettings>();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // if auto-migrate is configured....
            if (settings.AutoMigrate)
            {
                // initialize the database via migrations.
                this.InitializeDatabase(app, env);
            }

            app.UseSession();
            app.UseHttpsRedirection();

            // file extensions provider.
            var extensionsProvider = new FileExtensionContentTypeProvider();

            if (!extensionsProvider.Mappings.ContainsKey(".woff2"))
            {
                extensionsProvider.Mappings.Add(".woff2", "font/woff2");
            }

            app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = extensionsProvider });
            app.UseCookiePolicy();
            app.UseAuthentication();

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

        /// <summary>
        /// This method is used to execute database migrations as well as initiate some basic start-up data.
        /// </summary>
        /// <param name="app">Contains the application builder.</param>
        /// <param name="env">Contains the hosting environment.</param>
        private void InitializeDatabase(IApplicationBuilder app, IHostingEnvironment env)
        {
            try
            {
                using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
                {
                    // execute the application database migrations
                    var appContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                    appContext.Database.Migrate();

                    // initialize application data.
                    appContext.InitializeApplicationData(env);
                    appContext.InitializeDefaultUserData(serviceScope.ServiceProvider.GetRequiredService<UserManager<User>>());
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "An error occurred while attepting to load migration and test data.");
            }
        }

Akka.Persistence.PersistenceSettings : Settings

Constructors :

public PersistenceSettings(ActorSystem system = , Config config = )

Methods :

public ViewSettings get_View()
public AtLeastOnceDeliverySettings get_AtLeastOnceDelivery()
public Void set_AtLeastOnceDelivery(AtLeastOnceDeliverySettings value = )
public InternalSettings get_Internal()
public Void InjectTopLevelFallback(Config config = )
public ActorSystem get_System()
public Config get_Config()
public ActorSystemSetup get_Setup()
public Boolean get_HasCluster()
public ProviderSelection get_ProviderSelectionType()
public String get_ConfigVersion()
public String get_ProviderClass()
public String get_SupervisorStrategyClass()
public Boolean get_SerializeAllMessages()
public Boolean get_SerializeAllCreators()
public TimeSpan get_AskTimeout()
public TimeSpan get_CreationTimeout()
public TimeSpan get_UnstartedPushTimeout()
public String get_LogLevel()
public String get_StdoutLogLevel()
public MinimalLogger get_StdoutLogger()
public IList<String> get_Loggers()
public String get_LoggersDispatcher()
public TimeSpan get_LoggerStartTimeout()
public Boolean get_LoggerAsyncStart()
public Boolean get_LogConfigOnStart()
public Int32 get_LogDeadLetters()
public Boolean get_LogDeadLettersDuringShutdown()
public TimeSpan get_LogDeadLettersSuspendDuration()
public Boolean get_AddLoggingReceive()
public Boolean get_DebugAutoReceive()
public Boolean get_DebugEventStream()
public Boolean get_DebugUnhandledMessage()
public Boolean get_DebugRouterMisconfiguration()
public String get_Home()
public Boolean get_DebugLifecycle()
public Boolean get_FsmDebugEvent()
public Int32 get_DefaultVirtualNodesFactor()
public String get_SchedulerClass()
public TimeSpan get_SchedulerShutdownTimeout()
public Boolean get_CoordinatedShutdownTerminateActorSystem()
public Boolean get_CoordinatedShutdownRunByActorSystemTerminate()
public String ToString()
public Type GetType()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods