/// <summary> /// Default constructor. /// </summary> /// <param name="container">The current cache provider</param> public AppCache(ICacheProvider provider) { Authors = new ModelCache<Models.Author>(provider, a => a.Id.Value, a => a.Email); Categories = new ModelCache<Models.Category>(provider, c => c.Id.Value, c => c.Slug); Params = new ModelCache<Models.Param>(provider, p => p.Id.Value, p => p.InternalId); Posts = new ModelCache<Models.Post>(provider, p => p.Id.Value, p => p.Slug); Tags = new ModelCache<Models.Tag>(provider, t => t.Id.Value, t => t.Slug); }
private GameObject GetModel(int index) { ModelCache cache; if (!caches.TryGetValue(index, out cache)) { cache = new ModelCache() { alive = new List <GameObject>(), cached = new Stack <GameObject>(), }; caches[index] = cache; } GameObject model; if (cache.cached.Count > 0) { model = cache.cached.Pop(); model.SetActive(true); } else { model = (GameObject)Instantiate(db.ModelPrefabs[index]); } cache.alive.Add(model); return(model); }
/// <summary> /// 获取表名和字段 /// </summary> /// <returns></returns> public async Task <Dictionary <string, List <TABLES_COLUMNS> > > GetTableNameAndFields() { var _TableNames = await db.GetAllTableAsync(); var dic = new Dictionary <string, List <TABLES_COLUMNS> >(); var _TableAll = ModelCache.All(); for (int i = 0; i < _TableNames.Count; i++) { var item = _TableNames[i]; var _Cols = await db.GetColsByTableNameAsync(item.Name); List <ModelInfo> fieldInfoList = null; if (_TableAll.ContainsKey(item.Name)) { fieldInfoList = _TableAll[item.Name].ToList(); } foreach (var _Col in _Cols) { var _FieldDescribe = fieldInfoList?.FirstOrDefault(w => w.Name == _Col.ColName); if (_FieldDescribe != null) { _Col.ColRemark = _FieldDescribe.Remark; } } dic[item.Name] = _Cols; } return(dic); }
private static void AddGeneratorSpecificWriterSetups(SetupInfo setupInfo, ModelCache modelCache, List <WriterInfo> writerInfos) { var generatorSetups = setupInfo.Setup.GeneratorSetups; IGenerator?previousGenerator = null; for (int generatorSetupIndex = 0; generatorSetupIndex < generatorSetups?.Count; generatorSetupIndex++) { var generatorInfo = CreateGeneratorInfo(setupInfo, modelCache, generatorSetups[generatorSetupIndex], generatorSetupIndex, previousGenerator); previousGenerator = generatorInfo.Generator; IWriter?previousWriter = null; var generatorWriterSetups = GetWriterSetups(generatorInfo.GeneratorSetup.WriterSetups); for (int writerSetupIndex = 0; writerSetupIndex < generatorWriterSetups.Count; writerSetupIndex++) { var writerInfo = CreateWriterInfo( generatorWriterSetups[writerSetupIndex], generatorInfo.ToEnumerable(), setupInfo, writerSetupIndex, generatorSetupIndex, previousWriter); writerInfos.Add(writerInfo); previousWriter = writerInfo.Writer; } } }
public override async Task <IEntryModel> ParseAsync(string path) { checkLogin(); if (path == "" || path == Alias) { return(new DropBoxItemModel(this)); } string fullPath = ModelCache.GetUniqueId(ModelCache.CheckPath(path)); if (fullPath != null) { return(ModelCache.GetModel(fullPath)); } string remotePath = ConvertRemotePath(path); try { var fetchedMetadata = await GetClient().GetMetaDataTask(remotePath); return(ModelCache.RegisterModel( new DropBoxItemModel(this, fetchedMetadata, Path.GetDirectoryName(path)))); } catch { return(null); //Not found } }
public override async Task <IList <IEntryModel> > ListAsync(IEntryModel entry, CancellationToken ct, Func <IEntryModel, bool> filter = null, bool refresh = false) { await checkLoginAsync(); if (filter == null) { filter = e => true; } GoogleDriveItemModel dirModel = (GoogleDriveItemModel)entry; if (dirModel != null) { if (!refresh) { var cachedChild = ModelCache.GetChildModel(dirModel); if (cachedChild != null) { return(cachedChild.Where(m => filter(m)).Cast <IEntryModel>().ToList()); } } var listRequest = _driveService.Files.List(); listRequest.Q = String.Format("'{0}' in parents", dirModel.UniqueId); var listResult = (await listRequest.ExecuteAsync().ConfigureAwait(false)); var listResultItems = listResult.Items.ToList(); var outputModels = listResultItems.Select(f => new GoogleDriveItemModel(this, f, dirModel.FullPath)).ToArray(); ModelCache.RegisterChildModels(dirModel, outputModels); return(outputModels.Where(m => filter(m)).Cast <IEntryModel>().ToList()); } return(new List <IEntryModel>()); }
void ProcessZipEntry( string filename, byte[] data, ZipEntry entry ) { MemoryStream stream = new MemoryStream( data ); ModelCache cache = game.ModelCache; IGraphicsApi api = game.Graphics; switch( filename ) { case "terrain.png": game.ChangeTerrainAtlas( new Bitmap( stream ) ); break; case "mob/chicken.png": case "chicken.png": UpdateTexture( ref cache.ChickenTexId, stream, false ); break; case "mob/creeper.png": case "creeper.png": UpdateTexture( ref cache.CreeperTexId, stream, false ); break; case "mob/pig.png": case "pig.png": UpdateTexture( ref cache.PigTexId, stream, false ); break; case "mob/sheep.png": case "sheep.png": UpdateTexture( ref cache.SheepTexId, stream, false ); break; case "mob/skeleton.png": case "skeleton.png": UpdateTexture( ref cache.SkeletonTexId, stream, false ); break; case "mob/spider.png": case "spider.png": UpdateTexture( ref cache.SpiderTexId, stream, false ); break; case "mob/zombie.png": case "zombie.png": UpdateTexture( ref cache.ZombieTexId, stream, false ); break; case "mob/sheep_fur.png": case "sheep_fur.png": UpdateTexture( ref cache.SheepFurTexId, stream, false ); break; case "char.png": UpdateTexture( ref cache.HumanoidTexId, stream, true ); break; case "clouds.png": case "cloud.png": UpdateTexture( ref game.CloudsTexId, stream, false ); break; case "rain.png": UpdateTexture( ref game.RainTexId, stream, false ); break; case "snow.png": UpdateTexture( ref game.SnowTexId, stream, false ); break; case "gui.png": UpdateTexture( ref game.GuiTexId, stream, false ); break; case "gui_classic.png": UpdateTexture( ref game.GuiClassicTexId, stream, false ); break; case "animations.png": case "animation.png": game.Animations.SetAtlas( new Bitmap( stream ) ); break; case "animations.txt": case "animation.txt": StreamReader reader = new StreamReader( stream ); game.Animations.ReadAnimationsDescription( reader ); break; case "particles.png": UpdateTexture( ref game.ParticleManager.ParticlesTexId, stream, false ); break; case "default.png": SetFontBitmap( game, stream ); break; } }
public void TableName_Test() { var tableAttribute = ModelCache.GetTableAttribute(typeof(MockObject)); Assert.NotNull(tableAttribute); var tableAttributeFromModel = ModelCache.GetTableAttribute(typeof(MockObject)); Assert.Equal(tableAttributeFromModel, tableAttribute); var tableName = Model.TableName(typeof(MockObject)); var fullyQualifiedTableName = Model.TableNameFullyQualified(typeof(MockObject)); Assert.NotNull(tableName); Assert.NotEmpty(tableName); Assert.Equal(tableName, "MockObjects"); Assert.NotNull(fullyQualifiedTableName); Assert.NotEmpty(fullyQualifiedTableName); Assert.Equal(fullyQualifiedTableName, "DestrierTest.dbo.MockObjects"); Assert.True(tableAttribute.UseNoLock); var idTableAttribute = ModelCache.GetTableAttribute(typeof(Ids)); Assert.False(idTableAttribute.UseNoLock); Assert.False(Model.UseNoLock(typeof(Ids))); }
public void Dispose() { MapRenderer.Dispose(); TerrainAtlas.Dispose(); TerrainAtlas1D.Dispose(); ModelCache.Dispose(); Entities.Dispose(); WorldEvents.OnNewMap -= OnNewMapCore; WorldEvents.OnNewMapLoaded -= OnNewMapLoadedCore; Events.TextureChanged -= TextureChangedCore; for (int i = 0; i < Components.Count; i++) { Components[i].Dispose(); } Graphics.DeleteIb(ref defaultIb); Drawer2D.DisposeInstance(); Graphics.DeleteTexture(ref CloudsTex); Graphics.Dispose(); if (lastAtlas != null) { lastAtlas.Dispose(); } if (Options.OptionsChanged.Count == 0) { return; } Options.Load(); Options.Save(); }
public GeneratorInfo(ISetup setup, ModelCache modelCache, IGeneratorSetup generatorSetup, IGenerator <ISetup, IGeneratorSetup, ITarget, object, IRun, object> generator) { this.Setup = setup; this.ModelCache = modelCache; this.GeneratorSetup = generatorSetup; this.Generator = generator; }
public void Dispose() { ChunkUpdater.Dispose(); Atlas2D.Dispose(); Atlas1D.Dispose(); ModelCache.Dispose(); Entities.Dispose(); WorldEvents.OnNewMap -= OnNewMapCore; WorldEvents.OnNewMapLoaded -= OnNewMapLoadedCore; Events.TextureChanged -= TextureChangedCore; for (int i = 0; i < Components.Count; i++) { Components[i].Dispose(); } Drawer2D.DisposeInstance(); Graphics.Dispose(); // TODO: is this needed //window.Dispose(); if (!Options.HasChanged()) { return; } Options.Load(); Options.Save(); }
/// <summary> /// 创建 Info.cshtml 代码 /// </summary> /// <param name="Fields"></param> /// <param name="Temp"></param> /// <param name="TableName"></param> /// <returns></returns> public async Task <string> CreateInfoCode(List <string> Fields, string Temp, string TableName) { StringBuilder _Codes = new StringBuilder(); await Task.Run(() => { var _TableAll = ModelCache.All(); foreach (var item in Fields) { var _TableName = item.Split('/')[0]; var _FieldName = item.Split('/')[1]; List <ModelInfo> fieldInfos = null; if (_TableAll.ContainsKey(_TableName)) { fieldInfos = _TableAll[_TableName].ToList(); } if (fieldInfos == null) { continue; } var fieldInfo = fieldInfos.FirstOrDefault(w => w.Name == _FieldName); if (fieldInfo == null) { continue; } _Codes.Append(@$ " <div class=" "col-sm-12" ">
protected override void On_Load(object sender, EventArgs e) { m_MarioHeadModel = ModelCache.GetModel("data/player/mario_head_cap.bmd"); m_MarioBodyModel = ModelCache.GetModel("data/player/mario_model.bmd"); PrerenderMarioModel(); base.On_Load(sender, e); }
static public void TaxFormStatusChanged(string sponsorGUID) { ModelBase model; if (ModelCache.TryGetValue(sponsorGUID, out model)) { ((SponsorModel)model).RefreshTaxFormsList(); } }
public static void Boot() { Console.WriteLine("Booting..."); ModelCache.Reset(); ModelCache.StartAutoResetTask(); Console.WriteLine("Boot finished."); }
public static void Draw(Game game, byte block, float size, float x, float y) { info = game.BlockInfo; cache = game.ModelCache; atlas = game.TerrainAtlas1D; minBB = info.MinBB[block]; maxBB = info.MaxBB[block]; fullBright = info.FullBright[block]; if (info.IsSprite[block]) { minBB = Vector3.Zero; maxBB = Vector3.One; } if (info.IsAir[block]) { return; } index = 0; api = game.Graphics; // isometric coords size: cosY * -scale - sinY * scale // we need to divide by (2 * cosY), as the calling function expects size to be in pixels. scale = size / (2 * cosY); // screen to isometric coords (cos(-x) = cos(x), sin(-x) = -sin(x)) pos.X = x; pos.Y = y; pos.Z = 0; pos = Utils.RotateY(Utils.RotateX(pos, cosX, -sinX), cosY, -sinY); if (info.IsSprite[block]) { SpriteXQuad(block, TileSide.Right, false); SpriteZQuad(block, TileSide.Back, false); SpriteZQuad(block, TileSide.Back, true); SpriteXQuad(block, TileSide.Right, true); } else { XQuad(block, Make(maxBB.X), TileSide.Left); ZQuad(block, Make(minBB.Z), TileSide.Back); YQuad(block, Make(maxBB.Y), TileSide.Top); } if (index == 0) { return; } if (atlas.TexIds[texIndex] != lastTexId) { lastTexId = atlas.TexIds[texIndex]; api.BindTexture(lastTexId); } for (int i = 0; i < index; i++) { TransformVertex(ref cache.vertices[i]); } api.UpdateDynamicIndexedVb(DrawMode.Triangles, cache.vb, cache.vertices, index, index * 6 / 4); }
public void Core_Tests() { var members = ModelCache.GetColumnMemberLookup(typeof(MockObject)); var notNullable = members["MockObjectId"]; var nullable = members["NullableId"]; Assert.False(ReflectionHelper.IsNullableType(notNullable.Type)); Assert.True(ReflectionHelper.IsNullableType(nullable.Type)); }
public bool LoadCachedToken() { try { cache = new ModelCache(); return(cache.Credentials != null && api.Authenticate(cache.Credentials)); } catch (CacheException) { return(false); } }
public override async Task <IList <IEntryModel> > ListAsync(IEntryModel entry, CancellationToken ct, Func <IEntryModel, bool> filter = null, bool refresh = false) { await checkLoginAsync(); if (filter == null) { filter = e => true; } List <IEntryModel> retList = new List <IEntryModel>(); List <SkyDriveItemModel> cacheList = new List <SkyDriveItemModel>(); SkyDriveItemModel dirModel = entry as SkyDriveItemModel; if (dirModel != null) { if (!refresh) { var cachedChild = ModelCache.GetChildModel(dirModel); if (cachedChild != null) { return(cachedChild.Where(m => filter(m)).Cast <IEntryModel>().ToList()); } } LiveConnectClient client = new LiveConnectClient(Session); LiveOperationResult listOpResult = await client.GetAsync(dirModel.UniqueId + "/files", ct); if (ct.IsCancellationRequested) { return(retList); } dynamic listResult = listOpResult.Result; foreach (dynamic itemData in listResult.data) { SkyDriveItemModel retVal = null; retVal = new SkyDriveItemModel(this, itemData, dirModel.FullPath); if (retVal != null) { cacheList.Add(ModelCache.RegisterModel(retVal)); if (filter(retVal)) { retList.Add(retVal); } } } ModelCache.RegisterChildModels(dirModel, cacheList.ToArray()); } return(retList); }
private static GeneratorInfo CreateGeneratorInfo( SetupInfo setupInfo, ModelCache modelCache, IGeneratorSetup generatorSetup, int generatorSetupIndex, IGenerator?previousGenerator) { var generator = GeneratorFactory.CreateGenerator(generatorSetup.Generator, setupInfo, generatorSetupIndex, previousGenerator); return(new GeneratorInfo(setupInfo.Setup, modelCache, generatorSetup, generator)); }
public IModelCache Register <TModel>( ) { var type = typeof(TModel); if (!typeModelMap.TryGetValue(type.GetTypeData(), out ModelCache modelCache)) { modelCache = new ModelCache(type); typeModelMap.Add(modelCache.TypeData, modelCache); } return(modelCache); }
/// <summary> /// Creates an <see cref="IGeneratorRunner" />. /// </summary> /// <param name="setupInfos">The setupInfos.</param> /// <returns> /// An <see cref="IGeneratorRunner" />. /// </returns> public IGeneratorRunner Create(IEnumerable <SetupInfo> setupInfos) { List <WriterInfo> writerInfos = new List <WriterInfo>(); foreach (var setupInfo in setupInfos) { var modelCache = new ModelCache(ModelProviderFactory.CreateModelProvider(setupInfo), setupInfo.Setup); AddGlobalWriterSetups(setupInfo, modelCache, writerInfos); AddGeneratorSpecificWriterSetups(setupInfo, modelCache, writerInfos); } return(new GeneratorRunner(writerInfos)); }
void ProcessZipEntry(string filename, byte[] data, ZipEntry entry) { MemoryStream stream = new MemoryStream(data); ModelCache cache = game.ModelCache; // Ignore directories: convert x/name to name and x\name to name. string name = filename.ToLower(); int i = name.LastIndexOf('\\'); if (i >= 0) { name = name.Substring(i + 1, name.Length - 1 - i); } i = name.LastIndexOf('/'); if (i >= 0) { name = name.Substring(i + 1, name.Length - 1 - i); } switch (name) { case "terrain.png": Bitmap atlas = Platform.ReadBmp(stream); if (!game.ChangeTerrainAtlas(atlas)) { atlas.Dispose(); } break; case "clouds.png": case "cloud.png": game.UpdateTexture(ref game.CloudsTex, data, false); break; case "gui.png": game.UpdateTexture(ref game.GuiTex, data, false); break; case "gui_classic.png": game.UpdateTexture(ref game.GuiClassicTex, data, false); break; case "icons.png": game.UpdateTexture(ref game.IconsTex, data, false); break; case "particles.png": game.UpdateTexture(ref game.ParticleManager.ParticlesTexId, data, false); break; case "default.png": SetFontBitmap(game, stream); break; } game.Events.RaiseTextureChanged(name, data); }
public static UserSetting Find(int id) { var cached = ModelCache.Get("User", id); if (cached != null) { return((UserSetting)cached); } var item = UserSetting.Find(id); ModelCache.Store("User", item.id, item); return(UserSetting.Find(id)); }
public override void PrepareForClose() { base.PrepareForClose(); GL.DeleteLists(m_DisplayListMario, 1); if (m_MarioHeadModel != null) { ModelCache.RemoveModel(m_MarioHeadModel); } if (m_MarioBodyModel != null) { ModelCache.RemoveModel(m_MarioBodyModel); } }
public void UnLoad() { UnLoadSubClass(); ModelCache.Remove(GUID); //*** very crucial to eliminate this reference from a table object to an event handler on each corresponding model instance (otherwise it's a potential mem leak) //*** we want everything disconnected from an unloaded instance so it can be garbage collected if (_fields != null) { _fields.Row.Table.RowChanged -= FieldsTableRowChanged; _fields.DetachRow(); _fields = null; } }
public void LogOut() { if (cache != null) { cache.LogOut(); } api.LogOut(); cache = null; IsDataLoaded = false; MySets = new ObservableCollection <SetViewModel>(); FavouriteSets = new ObservableCollection <SetViewModel>(); RecentSets = new ObservableCollection <SetViewModel>(); Groups = new ObservableCollection <GroupViewModel>(); }
public string ConvertRemotePath(string path) { path = ModelCache.CheckPath(path); if (path == Alias) { return("/"); } if (path.StartsWith(Alias)) { return("/" + path.Substring(Alias.Length + 1)); } return("/" + path.TrimStart('/')); }
public static UserModel Find(int id) { var cached = ModelCache.Get("User", id); if (cached != null) { return((UserModel)cached); } var item = UserModel.Find(id); if (item != null) { ModelCache.Store("User", item.id, item); } return(item); }
public PageService(ApplicationSettings settings, IRepository repository, SearchService searchService, PageHistoryService historyService, IUserContext context, ListCache listCache, ModelCache modelCache, PageViewModelCache pageViewModelCache, SiteCache sitecache, IPluginFactory pluginFactory) : base(settings, repository) { _searchService = searchService; _markupConverter = new MarkupConverter(settings, repository, pluginFactory); _historyService = historyService; _context = context; _listCache = listCache; _modelCache = modelCache; _pageViewModelCache = pageViewModelCache; _siteCache = sitecache; _pluginFactory = pluginFactory; _markupLinkUpdater = new MarkupLinkUpdater(_markupConverter.Parser); }
public static UserModel FindByGuid(string guid) { var cached = ModelCache.Get("User", guid); if (cached != null) { return((UserModel)cached); } var item = UserModel.FindByGuid(guid); if (item != null) { ModelCache.Store("User", item.guid, item); } return(item); }
public bool LoadCachedToken() { try { cache = new ModelCache(); return cache.Credentials != null && api.Authenticate(cache.Credentials); } catch (CacheException) { return false; } }
public void LogOut() { if (cache != null) cache.LogOut(); api.LogOut(); cache = null; IsDataLoaded = false; MySets = new ObservableCollection<SetViewModel>(); FavouriteSets = new ObservableCollection<SetViewModel>(); RecentSets = new ObservableCollection<SetViewModel>(); Groups = new ObservableCollection<GroupViewModel>(); }
public void LoadData() { if (IsDataLoaded) return; try { Metrics.Measure("MainViewModel.LoadData()", delegate { Metrics.Measure("Load ModelCache", delegate { cache = api.Credentials != null ? new ModelCache(api.Credentials) : new ModelCache(); }); if (cache.Credentials == null) return; if (!api.Authenticate(cache.Credentials)) { cache.LogOut(); LogOut(); return; } UserName = cache.Credentials.UserName; Metrics.Measure("Create group view models", delegate { foreach (var si in cache.GetMySets()) MySets.Add(new SetViewModel(this, si)); foreach (var si in cache.GetRecentSets().Take(8)) RecentSets.Add(new SetViewModel(this, si)); foreach (var si in cache.GetFavourites()) FavouriteSets.Add(new SetViewModel(this, si) { Starred = true }); }); Metrics.Measure("Create group view models", delegate { foreach (var gi in cache.GetGroups()) Groups.Add(new GroupViewModel(this, gi)); }); Metrics.Measure("Load profile image", LoadProfileImage); IsDataLoaded = true; }); } catch (CacheIndexMissingException) { // XXX This will never happen } }
// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method. protected override bool AuthorizeCore(HttpContextBase context) { if (context == null) throw new ArgumentNullException("context"); if (context.Request.Cookies[ConfigurationManager.AppSettings["CookieKey"]] == null) return false; var cookieValue = context.Request.Cookies[ConfigurationManager.AppSettings["CookieKey"]].Value; var data = Encoding.UTF8.GetString(Convert.FromBase64String(cookieValue)).Split('-'); var userId = Convert.ToInt32(data[0]); var userEmail = data[1]; var enableProfiling = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableProfiling"]); IDisposable _step = null; if (enableProfiling) { var _profiler = MiniProfiler.Current; _step = _profiler.Step("Get Session In AuthenticateAttribute"); } var sessionRepository = new SessionRepository(ConfigurationManager.AppSettings["DataDbConnectionString"], userId); var session = sessionRepository.GetByKey(cookieValue); if (enableProfiling) { _step.Dispose(); } if (session == null) return false; // If caching is enabled, this is the only place we can reliably set up the dependencies // TODO: Could these be added on first Cache.Add() if not already present? if (ConfigurationManager.AppSettings["EnableCaching"] != null && Convert.ToBoolean(ConfigurationManager.AppSettings["EnableCaching"]) == true) { var cacheConfiguration = new ModelCacheConfiguration(); var cache = new ModelCache(cacheConfiguration); var cachingHelpers = new CachingHelpers(cacheConfiguration, userId); if (cache.Items.FirstOrDefault(x => x.Key == cachingHelpers.GetDependencyKey("all", userId.ToString())) == null) { // Add the cache dependency items to the cache // We have to manually add the user ID to the keys here because it wasn't necessarily present when the cache object was injected cache.Add(cachingHelpers.GetDependencyKey("all", userId.ToString()), Guid.NewGuid().ToString(), (int)CacheExpiry.FifteenMinutes); cache.Add(cachingHelpers.GetDependencyKey("user", userId.ToString()), Guid.NewGuid().ToString(), (int)CacheExpiry.FifteenMinutes); cache.Add(cachingHelpers.GetDependencyKey("transaction", userId.ToString()), Guid.NewGuid().ToString(), (int)CacheExpiry.FifteenMinutes); cache.Add(cachingHelpers.GetDependencyKey("budget", userId.ToString()), Guid.NewGuid().ToString(), (int)CacheExpiry.FifteenMinutes); cache.Add(cachingHelpers.GetDependencyKey("account", userId.ToString()), Guid.NewGuid().ToString(), (int)CacheExpiry.FifteenMinutes); cache.Add(cachingHelpers.GetDependencyKey("category", userId.ToString()), Guid.NewGuid().ToString(), (int)CacheExpiry.FifteenMinutes); } } context.Items.Add("UserID", userId); context.Items.Add("Email", userEmail); return true; }