static RedisFactory() { CacheSetting cacheSetting = CacheSetting.GetInstance(); if (cacheSetting != null) { var connectionPools = new CustomShardedConnectionPool[cacheSetting.Pools.Count]; int index = 0; foreach (CacheSetting.PoolConfig poolConfig in cacheSetting.Pools) { long initalDb = poolConfig.Db ?? 0L; RedisClientManagerConfig config = poolConfig.MaxReadPoolSize.HasValue || poolConfig.MaxWritePoolSize.HasValue?new RedisClientManagerConfig():null; if (config != null) { config.MaxReadPoolSize = poolConfig.MaxReadPoolSize.HasValue ? poolConfig.MaxReadPoolSize.Value : 50; config.MaxWritePoolSize = poolConfig.MaxWritePoolSize.HasValue ? poolConfig.MaxWritePoolSize.Value : 50; } var pool = new CustomShardedConnectionPool(poolConfig.Name, poolConfig.Weight, config, initalDb, poolConfig.Hosts); pool.PoolTimeout = poolConfig.PoolTimeout ?? 1000; pool.ConnectTimeout = poolConfig.ConnectTimeout; pool.SocketSendTimeout = poolConfig.SocketSendTimeout; pool.SocketReceiveTimeout = poolConfig.SocketReceiveTimeout; connectionPools[index] = pool; index++; } RedisClientManager = new AutoDetectShardedRedisClientManager(connectionPools); } }
protected override void OnStartAffer() { try { var setting = new EnvironmentSetting(); setting.EntityAssembly = Assembly.Load("GameRanking.Model"); ScriptEngines.AddReferencedAssembly("GameRanking.Model.dll"); ActionFactory.SetActionIgnoreAuthorize(1000, 1001); var cacheSetting = new CacheSetting(); cacheSetting.ChangedHandle += OnChangedNotify; GameEnvironment.Start(setting, cacheSetting); var cache = new ShareCacheStruct <UserRanking>(); Stopwatch t = new Stopwatch(); t.Start(); var list = cache.FindAll(false); t.Stop(); if (list.Count > 0) { } Console.WriteLine("The server is staring..."); } catch (Exception ex) { TraceLog.WriteError("App star error:{0}", ex); } }
public static string ToStringType(this CacheSetting cacheSetting) { switch (cacheSetting) { case CacheSetting.AppFabric: return(CacheTypes.AppFabricCache); break; case CacheSetting.memcached: return(CacheTypes.memcached); break; case CacheSetting.Memory: return(CacheTypes.MemoryCache); break; case CacheSetting.Redis: return(CacheTypes.redis); break; case CacheSetting.Web: return(CacheTypes.WebCache); break; default: return(CacheTypes.MemoryCache); break; } }
private DOCollection GetPropertyValue() { _rm = (ResourceManage)_p.GetValue(ParameterKey.RESOURCE_MANAGER); _token = (TransactionToken)_p.GetValue(ParameterKey.TOKEN); DOCollection rtn = null; lock (lockobj) { rtn = GetCache(_p.PropertyName); if (rtn == null) { Init(_p); var action = GetSourceDefinition(_p.PropertyName); if (action != null) { CacheSetting setting = new CacheSetting(); rtn = action.Invoke(setting); if (setting.IsCache) { SetCache(_p.PropertyName, rtn, setting.CacheExpiration, setting.CacheSlidingExpiration); } } After(_p); } } return(rtn); }
/// <summary>编辑 /// /// </summary> private void DoEdit() { string strMsg = CheckSelect("修改"); if (strMsg != string.Empty) { MessageBox.Show(strMsg); return; } DataGridViewRow drRowEdit = grdData.SelectedRows[0]; CacheSetting model = drRowEdit.Tag as CacheSetting; if (model == null) { int intKeyID = int.Parse(drRowEdit.Cells[gridmrzId.Name].Value.ToString()); model = m_CacheSettingDAL.GetModel(intKeyID); } if (model != null) { FrmCacheSettingSimpleDialog frmDialog = new FrmCacheSettingSimpleDialog(model, m_lstCacheSetting); if (frmDialog.ShowDialog() == DialogResult.OK) { m_lstCacheSetting = frmDialog.ListCacheSetting; grdData.DataSource = m_lstCacheSetting; grdData.Refresh(); } } }
/// <summary> /// The game service start. /// </summary> /// <param name="setting">Environment setting.</param> public static void Start(EnvironmentSetting setting) { CacheSetting cacheSetting = new CacheSetting(); cacheSetting.ChangedHandle += EntitySyncManger.OnChange; Start(setting, cacheSetting); }
public void CreateOrUpdateCache(string cacheName, CacheSetting cacheSetting) { // Set cache options. var cacheEntryOptions = _cacheSettingProvider.CreateMemoryCacheEntryOptions(CacheItemPriority.High, cacheSetting.ExpiresAt); // Save data in cache. _cache.Set(cacheName, cacheSetting, cacheEntryOptions); }
private void btnSave_Click(object sender, EventArgs e) { string strReturnMsg = CheckInput(); if (strReturnMsg != string.Empty) { MessageBox.Show(strReturnMsg); return; } //新增 if (m_CacheSetting == null) { string strSetKeyValueNew = txtEditSetKey.Text.Trim(); if (m_CacheSettingDAL.CalcCount("SetKey='" + strSetKeyValueNew + "'") > 0) { MessageBox.Show(@"设置键已经存在"); return; } CacheSetting model = EntityOperateManager.AddEntity <CacheSetting>(this.tabPage); int intReturn = m_CacheSettingDAL.Add(model); if (intReturn > 0) { MessageBox.Show(@"添加成功"); model.Id = intReturn; m_lstCacheSetting.Add(model); ListCacheSetting = m_lstCacheSetting; this.DialogResult = DialogResult.OK; } else { MessageBox.Show(@"添加失败"); } } //修改 else { string strSetKeyValueEdit = txtEditSetKey.Text.Trim(); if (m_CacheSettingDAL.CalcCount(" Id !=" + m_CacheSetting.Id + " and SetKey='" + strSetKeyValueEdit + "'") > 0) { MessageBox.Show(@"设置键已经存在"); return; } m_CacheSetting = EntityOperateManager.EditEntity(this.tabPage, m_CacheSetting); bool blnReturn = m_CacheSettingDAL.Update(m_CacheSetting); if (blnReturn) { MessageBox.Show(@"修改成功"); ListCacheSetting = m_lstCacheSetting; this.DialogResult = DialogResult.OK; } else { MessageBox.Show(@"修改失败"); } } }
/// <summary> /// The game service start. /// </summary> /// <param name="setting">Environment setting.</param> /// <param name="cacheSetting">Cache setting.</param> public static void Start(EnvironmentSetting setting, CacheSetting cacheSetting) { if (IsRunning) { return; } TraceLog.WriteLine("{0} Server is starting...", DateTime.Now.ToString("HH:mm:ss")); _setting = setting; if (!RedisConnectionPool.Ping("127.0.0.1")) { string error = string.Format("Error: NIC is not connected or no network."); TraceLog.WriteLine(error); TraceLog.WriteError(error); return; } RedisConnectionPool.Initialize(_setting.Serializer); if (!RedisConnectionPool.CheckConnect()) { string error = string.Format("Error: the redis server is not started."); TraceLog.WriteLine(error); TraceLog.WriteError(error); return; } TraceLog.WriteLine("{0} Redis server connect successfully.", DateTime.Now.ToString("HH:mm:ss")); DbConnectionProvider.Initialize(); TraceLog.WriteLine("{0} DB server connect successfully.", DateTime.Now.ToString("HH:mm:ss")); EntitySchemaSet.CacheGlobalPeriod = _setting.CacheGlobalPeriod; EntitySchemaSet.CacheUserPeriod = _setting.CacheUserPeriod; if (_setting.EntityAssembly != null) { ProtoBufUtils.LoadProtobufType(_setting.EntityAssembly); EntitySchemaSet.LoadAssembly(_setting.EntityAssembly); } ZyGameBaseConfigManager.Intialize(); //init script. if (_setting.ScriptSysAsmReferences.Length > 0) { ScriptEngines.AddSysReferencedAssembly(_setting.ScriptSysAsmReferences); } ScriptEngines.AddReferencedAssembly("ZyGames.Framework.Game.dll"); if (_setting.ScriptAsmReferences.Length > 0) { ScriptEngines.AddReferencedAssembly(_setting.ScriptAsmReferences); } ScriptEngines.RegisterModelChangedBefore(OnModelChangeBefore); ScriptEngines.RegisterModelChangedAfter(OnModelChangeAtfer); ScriptEngines.OnLoaded += OnScriptLoaded; ScriptEngines.Initialize(); Language.SetLang(); CacheFactory.Initialize(cacheSetting, _setting.Serializer); EntitySchemaSet.StartCheckTableTimer(); Global = new ContextCacheSet <CacheItem>("__gameenvironment_global"); }
private void dataNavigator_PositionChanged(object sender, EventArgs e) { if (dataNavigator.ListInfo == null) { return; } m_CacheSetting = m_lstCacheSetting [this.dataNavigator.CurrentIndex]; DisplayData(m_CacheSetting); }
public void Dispose() { if (_isDisposed) { return; } _isDisposed = true; Current = CacheSetting.Enabled; }
public IActionResult SaveCacheSettings([FromBody] CacheSettingModel model) { if (ModelState.IsValid) { CacheSetting entity = new CacheSetting(); model.CopyTo(entity); return(_settingService.Save(entity).SaveResult(T)); } return(SaveFailure(GetModelErrors())); }
public void Init() { var ser = new JsonCacheSerializer(Encoding.UTF8); ConfigManager.GetConfigger <MyDataConfigger>(); RedisConnectionPool.Initialize(ser); DbConnectionProvider.Initialize(); EntitySchemaSet.LoadAssembly(typeof(SingleData).Assembly); var setting = new CacheSetting(); CacheFactory.Initialize(setting, ser); }
/// <summary>实例化设置</summary> public Setting() { Debug = true; ShowSQL = true; SQLPath = ""; ConnMaps = "Conn2#Conn,Table3@Table"; InitData = true; Cache = new CacheSetting(); Negative = new NegativeSetting(); //Model = new ModelSetting(); Oracle = new OracleSetting(); }
protected override void InitInternal(CacheSetting setting) { base.InitInternal(setting); var serverName = this.CacheName; if (setting != null) { if (!string.IsNullOrEmpty(setting.CacheInstanceName)) { serverName = setting.CacheInstanceName; } } this.redisServer = serverName; }
public AccountsController( IAccountRepository accountRepository, IOptions <CacheSetting> cacheSetting, IMemoryCache memoryCache) { _accountRepository = accountRepository; _cacheSetting = cacheSetting.Value; _memoryCache = memoryCache; _accountCacheList = new CacheList <Account>( _memoryCache, _accountRepository.Accounts, CacheKeys.Accounts.AccountsItems, _cacheSetting.ExpireMinutes); }
public UsersController( IUserRepository userRepository, IOptions <CacheSetting> сacheSetting, IMemoryCache memoryCache) { _userRepository = userRepository; _сacheSetting = сacheSetting.Value; _memoryCache = memoryCache; _userCacheList = new CacheList <User>( _memoryCache, _userRepository.UsersWithoutPasswords, CacheKeys.Users.UsersItems, _сacheSetting.ExpireMinutes); }
/// <summary>构造函数 /// /// </summary> /// <param name=model" CacheSetting">对象</param> /// <param name="lstCacheSetting">对象集合</param> public FrmCacheSettingSimpleDialog(CacheSetting modelCacheSetting, List <CacheSetting> lstCacheSetting) { InitializeComponent(); DoInitData(); m_lstCacheSetting = lstCacheSetting ?? new List <CacheSetting>(); m_CacheSettingDAL = GlobalHelp.GetResolve <IBseDAL <CacheSetting> >(); this.dataNavigator.Visible = false; if (modelCacheSetting != null) { this.dataNavigator.Visible = true; m_CacheSetting = modelCacheSetting; this.dataNavigator.ListInfo = lstCacheSetting.Select(t => t.Id.ToString()).ToList(); m_strIndex = lstCacheSetting.FindIndex(t => t.Id == m_CacheSetting.Id).ToString(); this.dataNavigator.CurrentIndex = int.Parse(m_strIndex); } }
/// <summary> /// The game service start. /// </summary> /// <param name="setting">Environment setting.</param> /// <param name="cacheSetting">Cache setting.</param> public static void Start(EnvironmentSetting setting, CacheSetting cacheSetting) { if (_isRunning == 1) { return; } _setting = setting; if (!RedisConnectionPool.CheckConnect()) { string error = string.Format("Error: the redis server is not started."); Console.WriteLine(error); TraceLog.WriteError(error); return; } DbConnectionProvider.Initialize(); EntitySchemaSet.CacheGlobalPeriod = _setting.CacheGlobalPeriod; EntitySchemaSet.CacheUserPeriod = _setting.CacheUserPeriod; if (_setting.EntityAssembly != null) { ProtoBufUtils.LoadProtobufType(_setting.EntityAssembly); EntitySchemaSet.LoadAssembly(_setting.EntityAssembly); } EntitySchemaSet.StartCheckTableTimer(); LoadGameEntitySchema(); ZyGameBaseConfigManager.Intialize(); //init script. if (_setting.ScriptSysAsmReferences.Length > 0) { ScriptEngines.AddSysReferencedAssembly(_setting.ScriptSysAsmReferences); } ScriptEngines.AddReferencedAssembly("ZyGames.Framework.Game.dll"); if (_setting.ScriptAsmReferences.Length > 0) { ScriptEngines.AddReferencedAssembly(_setting.ScriptAsmReferences); } ScriptEngines.RegisterModelChangedBefore(OnModelChangeBefore); ScriptEngines.RegisterModelChangedAfter(OnModelChangeAtfer); ScriptEngines.Initialize(); Language.SetLang(); CacheFactory.Initialize(cacheSetting); Global = new ContextCacheSet <CacheItem>("__gameenvironment_global"); Interlocked.Exchange(ref _isRunning, 1); }
/// <summary> /// Constructor, initialize a caching service object. /// </summary> /// <param name="key">Cache key.</param> /// <param name="parms">Parameters.</param> public CachingService(string key, params string[] parms) { LoadProviders(); setting = cacheSettingsSection.Caches[key]; if (setting == null) // No setting, use default setting. { enableCache = cacheSettingsSection.Enabled; if (!enableCache) { return; } defaultDuration = cacheSettingsSection.DefaultDuration; provider = defaultProvider; } else { enableCache = cacheSettingsSection.Enabled ? setting.Enabled : false; if (!enableCache) { return; } defaultDuration = setting.Duration; if (!string.IsNullOrEmpty(setting.Provider)) { provider = providers[setting.Provider]; } if (provider == null) { provider = defaultProvider; } } internalKey = GetInternalKey(key, parms); }
static FileDiskCacheManagerFactory() { CanvasSetting setting = null; string fname = Path.Combine(Path.GetDirectoryName((new TileSetting()).GetType().Assembly.Location), "GeoDo.RSS.Core.DrawEngine.GDIPlus.cnfg.xml"); if (File.Exists(fname)) { using (CanvasSettingParser p = new CanvasSettingParser()) { setting = p.Parse(fname); if (!Directory.Exists(setting.CacheSetting.Dir)) { Directory.CreateDirectory(setting.CacheSetting.Dir); } _tileSetting = setting.TileSetting; _cacheSetting = setting.CacheSetting; } } _fileIndexer = new FileIndexer(setting.CacheSetting.Dir);; }
public UserService( IUserRepository userRepository, IAccountRoleRepository accountRoleRepository, IOptions <JwtSetting> jwtSetting, IOptions <CacheSetting> cacheSetting, IMemoryCache memoryCache) : base( userRepository, accountRoleRepository) { _jwtSetting = jwtSetting.Value; _cacheSetting = cacheSetting.Value; _memoryCache = memoryCache; _userCacheList = new CacheList <User>( _memoryCache, _userRepository.UsersWithoutPasswords, CacheKeys.Users.UsersItems, _cacheSetting.ExpireMinutes); }
protected override void InitInternal(CacheSetting setting) { base.InitInternal(setting); var memcachedName = this.CacheName; string keyPrefix = null; if (setting != null) { if (!string.IsNullOrEmpty(setting.CacheInstanceName)) { memcachedName = setting.CacheInstanceName; } keyPrefix = setting.KeyPrefix; if (!string.IsNullOrEmpty(setting.Servers)) { MemcachedClient.Setup(memcachedName, setting.Servers.Split(',')); } } this.MemcachedClientInstance = MemcachedClient.GetInstance(memcachedName); this.MemcachedClientInstance.KeyPrefix = keyPrefix; }
public void CacheManager_GetCache_Add_ExecuteUsingCacheSetting_Test() { //初始化 var moqCache = new Mock<ICache>(); var moqProvider = new Mock<ICacheSettingProvider>(); CacheManager.SetCache(moqCache.Object); CacheManager.SetCacheSettingProvider(moqProvider.Object); var name = "Test"; var cacheSetting = new CacheSetting(name, true, 1000); moqProvider.Setup((p) => p.Get(name)).Returns(new CacheSetting(name, true, 1000)); var key = "key"; var value = "value"; //操作 var result = CacheManager.GetCache(name); result.Add("key", "value"); //验证 moqCache.Verify(c => c.Add(key, value, cacheSetting.ExpireTime), Times.Once()); }
public IContext CreateServiceContext(string serviceName) { return(new ServiceContext(this.ServiceContext.UserId, this.ServiceContext.RemoteIp, CacheSetting.IsUseCache(serviceName, setting))); }
public void Load(string directoryPath) { // Init { { var startupSetting = new StartupSetting(); startupSetting.ProcessSettings.Add(new ProcessSetting() { Path = @"Assemblies/Tor/tor.exe", Arguments = "-f torrc DataDirectory " + @"../../../Work/Tor", WorkingDirectory = @"Assemblies/Tor", }); startupSetting.ProcessSettings.Add(new ProcessSetting() { Path = @"Assemblies/Polipo/polipo.exe", Arguments = "-c polipo.conf", WorkingDirectory = @"Assemblies/Polipo", }); this.Startup = startupSetting; } { var catharsisSettings = new CatharsisSetting(); catharsisSettings.Ipv4AddressFilters.Add(new Ipv4AddressFilter("tcp:127.0.0.1:18118", null, new string[] { @"Catharsis_Ipv4.txt" })); this.Catharsis = catharsisSettings; } { var cacheSettings = new CacheSetting(); cacheSettings.Path = Path.Combine(directoryPath, "Cache.blocks"); this.Cache = cacheSettings; } { var colorsSetting = new ColorsSetting(); colorsSetting.Tree_Hit = System.Windows.Media.Colors.LightPink; colorsSetting.Link = System.Windows.Media.Colors.SkyBlue; colorsSetting.Link_New = System.Windows.Media.Colors.LightPink; colorsSetting.Message_Trust = System.Windows.Media.Colors.SkyBlue; colorsSetting.Message_Untrust = System.Windows.Media.Colors.LightPink; this.Colors = colorsSetting; } } // Config { var startupConfigPath = Path.Combine(directoryPath, "Startup.config"); var catharsisConfigPath = Path.Combine(directoryPath, "Catharsis.config"); var cacheConfigPath = Path.Combine(directoryPath, "Cache.config"); var colorsConfigPath = Path.Combine(directoryPath, "Colors.config"); if (!File.Exists(startupConfigPath)) { this.SaveObject(startupConfigPath, this.Startup); } if (!File.Exists(catharsisConfigPath)) { this.SaveObject(catharsisConfigPath, this.Catharsis); } if (!File.Exists(cacheConfigPath)) { this.SaveObject(cacheConfigPath, this.Cache); } if (!File.Exists(colorsConfigPath)) { this.SaveObject(colorsConfigPath, this.Colors); } this.Startup = this.LoadObject <StartupSetting>(startupConfigPath); this.Catharsis = this.LoadObject <CatharsisSetting>(catharsisConfigPath); this.Cache = this.LoadObject <CacheSetting>(cacheConfigPath); this.Colors = this.LoadObject <ColorsSetting>(colorsConfigPath); } }
/// <summary>实体对象值显示至控件 /// /// </summary> /// <param name="model">model</param> private void DisplayData(CacheSetting model) { EntityOperateManager.BindAll(this.tabPage, model); }
protected virtual void InitInternal(CacheSetting setting) { }
// ConfigureServices is where you register dependencies. // This method gets called by the runtime. // Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // Add services to the collection. services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddXmlDataContractSerializerFormatters() .AddMvcOptions(options => { options.FormatterMappings.SetMediaTypeMappingForFormat( Format.XmlFormat.Xml, new MediaTypeHeaderValue(Format.XmlFormat.ApplicationXml)); }); services.AddMemoryCache(); _jwtSetting = Configuration.GetSection(nameof(JwtSetting)) .Get <JwtSetting>(); _dbmsSetting = Configuration.GetSection(nameof(DBMSSetting)) .Get <DBMSSetting>(); _connectionString = Configuration.GetSection(nameof(ConnectionString)) .Get <ConnectionString>(); _sqlServerConnectionString = Configuration.GetSection(nameof(SQLServerConnectionString)) .Get <SQLServerConnectionString>(); _postgreSQLConnectionString = Configuration.GetSection(nameof(PostgreSQLConnectionString)) .Get <PostgreSQLConnectionString>(); _cacheSetting = Configuration.GetSection(nameof(CacheSetting)) .Get <CacheSetting>(); _appSetting = Configuration.GetSection(nameof(AppSetting)) .Get <AppSetting>(); services .Configure <JwtSetting>( Configuration.GetSection(nameof(JwtSetting))) .Configure <DBMSSetting>( Configuration.GetSection(nameof(DBMSSetting))) .Configure <ConnectionString>( Configuration.GetSection(nameof(ConnectionString))) .Configure <SQLServerConnectionString>( Configuration.GetSection(nameof(SQLServerConnectionString))) .Configure <PostgreSQLConnectionString>( Configuration.GetSection(nameof(PostgreSQLConnectionString))) .Configure <CacheSetting>( Configuration.GetSection(nameof(CacheSetting))) .Configure <AppSetting>( Configuration.GetSection(nameof(AppSetting))); // Set authentication scheme for JWT and set JWT provider configuration. services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateIssuerSigningKey = true, ValidateAudience = false, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes(_jwtSetting.Key)) }; }); // Register the Swagger generator, defining 1 or more Swagger documents. services.AddSwaggerGen(swagger => { swagger.SwaggerDoc("v1", new Info { Title = Parameters.Authorization, Version = "v1" }); swagger.AddSecurityDefinition(Parameters.Bearer, new ApiKeyScheme { In = Parameters.Header.FirstCharToLower(), Description = Resource.SwaggerSecurityDefinition, Name = Parameters.Authorization, Type = Parameters.ApiKey.FirstCharToLower() }); swagger.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { Parameters.Bearer, new string[] { } } }); }); // Create the IServiceProvider based on the container. return(AutofacConfigurator.GetAutofacServiceProvider( services, ApplicationContainer, DBMSSetting.GetDBMS(_dbmsSetting), DBMSSetting.GetConnectionString( _dbmsSetting, _connectionString, _sqlServerConnectionString, _postgreSQLConnectionString) )); }
/// <summary> /// Creates and seeds the local database with default settings. /// (DEBUG) : In debug mode the Db is always re-created. /// (RELEASE) : In reelase, the Db is not dropped. /// </summary> /// <param name="unitOfWork"></param> public static bool Seed(IUnitOfWork unitOfWork, bool repopulate = false) { if (unitOfWork == null) { throw new ArgumentNullException("unitOfWork"); } bool isCreated = false; User user = null; //#if DEBUG if (repopulate) { unitOfWork.ClearCachedItems(); unitOfWork.Save(); } //#else isCreated = unitOfWork.CreateDatabase(); //#endif if (!isCreated) { try { CacheSetting database = unitOfWork.CacheSettingRepository.GetByType(ResourceType.Database); if (database == null || database.LastRefreshedDateUtc < lastDatabaseUpdate) { if (database != null) { // Save the user's details to be re-added to the database. user = unitOfWork.UserRepository.GetUser(); } isCreated = unitOfWork.DropAndCreateDatabase(); unitOfWork.Save(); } } catch (Exception) { isCreated = unitOfWork.DropAndCreateDatabase(); unitOfWork.Save(); } } if (isCreated || repopulate) { // Prepopulate the cache settings. unitOfWork.CacheSettingRepository.Insert(new CacheSetting(null, ResourceType.Operators)); unitOfWork.CacheSettingRepository.Insert(new CacheSetting(lastDatabaseUpdate, ResourceType.Database)); // Prepopulate the application settings. unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.AllowLocation, false)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.UseMetric, new RegionInfo(CultureInfo.CurrentCulture.Name).IsMetric)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.ShowWeather, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.StoreLocation, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.UseUber, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.AutoPopulateLocation, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.AutoPopulateMostFrequent, false)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.AutoPopulateMostRecent, false)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.StoreRecent, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.SkipTripSelection, false)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.ShowAnnouncementsApplicationBar, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.ShowTripApplicationBar, true)); unitOfWork.AppSettingRepository.Insert(new AppSetting(ApplicationSetting.LoginUber, false)); // Prepopulate the modes. unitOfWork.TransportModeRepository.Insert(new TransportMode(ApplicationTransportMode.Bus, true)); unitOfWork.TransportModeRepository.Insert(new TransportMode(ApplicationTransportMode.Rail, true)); unitOfWork.TransportModeRepository.Insert(new TransportMode(ApplicationTransportMode.Taxi, true)); unitOfWork.TransportModeRepository.Insert(new TransportMode(ApplicationTransportMode.Boat, true)); // Save cache setting to the database. unitOfWork.Save(); if (user != null) { // Re-populate the user user = new User(Guid.NewGuid(), user.Token, user.Country, user.DismissedLocationPopup, user.LastKnownGeneralLocation, user.LastLocationUpdate, user.DismissedRateAppPopup, user.DismissedSignUpPopup, user.IsBumbleRegistered, user.Email, user.FirstName, user.LastName, user.IsFacebookRegistered, user.IsTwitterRegistered, user.FacebookInfo, user.TwitterInfo, user.TwitterHandle, user.AppUsageCount, user.DismissedLoginUberPopup, user.UberInfo, user.IsUberAuthenticated); unitOfWork.UserRepository.Insert(user); unitOfWork.Save(); } } return(isCreated); }
/// <summary> /// Initializes a new instance of the <see cref="CacheControlDecorator" /> class. /// </summary> /// <param name="cacheDuration">Duration of the cache.</param> /// <param name="cacheSetting">The cache setting.</param> /// <param name="wrappedResourceResult">The wrapped resource result.</param> public CacheControlDecorator(long cacheDuration, CacheSetting? cacheSetting, IResourceResult wrappedResourceResult) : base(wrappedResourceResult) { CacheDuration = cacheDuration; CacheSetting = cacheSetting; }
private async Task DownloadCountryData(Country country, DateTime?lastUpdatedDate) { ShowLoader(String.Format(AppResources.SplashLoaderTextDownloadingCountryData, country.Name)); if (user == null) { Token registerAnonymousToken = await DrumbleApiService.RegisterAnonymous(cancellationTokenSource.Token); user = new User(registerAnonymousToken); UnitOfWork.UserRepository.Insert(user); UnitOfWork.Save(); } IEnumerable <PublicTransportOperator> operators = await BumbleApiService.Operators(cancellationTokenSource.Token, user); UnitOfWork.PublicTransportOperatorRepository.RemoveAll(); IEnumerable <PublicTransportOperator> operatorsList = operators.ToList(); if (operatorsList.Count() == 0) { throw new Exception(AppResources.ApiErrorPopupMessageNoResources); } List <OperatorSetting> operatorSettings = UnitOfWork.OperatorSettingRepository.GetAll().ToList(); foreach (PublicTransportOperator transportOperator in operatorsList) { if (!operatorSettings.Select(x => x.OperatorName).Contains(transportOperator.Name)) { if (transportOperator.IsPublic) { UnitOfWork.OperatorSettingRepository.Insert(new OperatorSetting(transportOperator.Name, true)); } else { UnitOfWork.OperatorSettingRepository.Insert(new OperatorSetting(transportOperator.Name, false)); } } } UnitOfWork.PublicTransportOperatorRepository.InsertRange(operatorsList); UnitOfWork.Save(); user.Country = country; UnitOfWork.UserRepository.Update(user); UnitOfWork.Save(); CacheSetting cacheSetting = UnitOfWork.CacheSettingRepository.GetByType(ResourceType.Operators); cacheSetting.LastRefreshedDateUtc = DateTime.UtcNow; UnitOfWork.CacheSettingRepository.Update(cacheSetting); UnitOfWork.Save(); HideLoader(); TryNavigateToStartPage(); }