public void TestCacheSomeItemsAccessedJustBeforeGC() { Cache cache = new Cache(); for (int i = 0; i < 5; i++) { cache.Add(i, new byte[1024]); } var value1 = cache[1]; var value3 = cache[3]; Assert.AreEqual(5, cache.Count); Assert.AreEqual(5, cache.ActiveCount); Assert.IsNotNull(cache[0]); Assert.IsNotNull(cache[1]); Assert.IsNotNull(cache[2]); Assert.IsNotNull(cache[3]); Assert.IsNotNull(cache[4]); GC.Collect(); Assert.AreEqual(5, cache.Count); Assert.AreEqual(2, cache.ActiveCount); Assert.IsNull(cache[0]); Assert.IsNotNull(cache[1]); Assert.IsNull(cache[2]); Assert.IsNotNull(cache[3]); Assert.IsNull(cache[4]); }
public ObjectCreator(Manifest manifest, FileSystem.FileSystem modFiles) { typeCache = new Cache<string, Type>(FindType); ctorCache = new Cache<Type, ConstructorInfo>(GetCtor); // Allow mods to load types from the core Game assembly, and any additional assemblies they specify. var assemblyList = new List<Assembly>() { typeof(Game).Assembly }; foreach (var path in manifest.Assemblies) { var data = modFiles.Open(path).ReadAllBytes(); // .NET doesn't provide any way of querying the metadata of an assembly without either: // (a) loading duplicate data into the application domain, breaking the world. // (b) crashing if the assembly has already been loaded. // We can't check the internal name of the assembly, so we'll work off the data instead var hash = CryptoUtil.SHA1Hash(data); Assembly assembly; if (!ResolvedAssemblies.TryGetValue(hash, out assembly)) { assembly = Assembly.Load(data); ResolvedAssemblies.Add(hash, assembly); } assemblyList.Add(assembly); } AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly; assemblies = assemblyList.SelectMany(asm => asm.GetNamespaces().Select(ns => Pair.New(asm, ns))).ToArray(); AppDomain.CurrentDomain.AssemblyResolve -= ResolveAssembly; }
public TemplateViewFolder(IEnumerable<ITemplate> templates) { _templates = templates; _listViews = new Cache<string, IList<string>>(listViews); _hasView = new Cache<string, bool>(hasView); _getViewSource = new Cache<string, FileSystemViewFile>(getViewSource); }
static void Main(string[] args) { var couchbaseConfig = new Couchbase.Configuration.CouchbaseClientConfiguration(); couchbaseConfig.Bucket = "larm"; couchbaseConfig.Urls.Add(new Uri("http://10.0.252.63:8091/pools")); var cache = new Cache(new Couchbase.CouchbaseClient(couchbaseConfig)); var portalRepository = new PortalRepository().WithConfiguration("user id=larm-app;password=0n44Fx4f4m2jNtuLuA6ym88mr3h40D;server=mysql01.cpwvkgghf9fg.eu-west-1.rds.amazonaws.com;persist security info=True;database=larm-portal;Allow User Variables=True;CharSet=utf8;"); var portal = new PortalApplication(cache, new ViewManager(new Dictionary<string, IView>(), cache), portalRepository, new DatabaseLoggerFactory(portalRepository)); var mcm = new McmModule(); mcm.Load(portal); const uint PageSize = 100; var indexedCount = 0; for (uint i = 0; ; i++) { var objects = mcm.McmRepository.ObjectGet(null, i, PageSize, true, true, true, true, true, null); portal.ViewManager.GetView("Search").Index(objects); portal.ViewManager.GetView("Object").Index(objects); Console.SetCursorPosition(0,Console.CursorTop); Console.Write("Objects indexed: {0}", ++indexedCount); if (objects.Count != PageSize) break; } }
public TerrainRenderer(World world, WorldRenderer wr) { this.world = world; this.map = world.Map; var tileSize = new Size( Game.CellSize, Game.CellSize ); var tileMapping = new Cache<TileReference<ushort,byte>, Sprite>( x => Game.modData.SheetBuilder.Add(world.TileSet.GetBytes(x), tileSize)); var vertices = new Vertex[4 * map.Bounds.Height * map.Bounds.Width]; terrainSheet = tileMapping[map.MapTiles.Value[map.Bounds.Left, map.Bounds.Top]].sheet; int nv = 0; var terrainPalette = wr.Palette("terrain").Index; for( int j = map.Bounds.Top; j < map.Bounds.Bottom; j++ ) for( int i = map.Bounds.Left; i < map.Bounds.Right; i++ ) { var tile = tileMapping[map.MapTiles.Value[i, j]]; // TODO: move GetPaletteIndex out of the inner loop. Util.FastCreateQuad(vertices, Game.CellSize * new float2(i, j), tile, terrainPalette, nv, tile.size); nv += 4; if (tileMapping[map.MapTiles.Value[i, j]].sheet != terrainSheet) throw new InvalidOperationException("Terrain sprites span multiple sheets"); } vertexBuffer = Game.Renderer.Device.CreateVertexBuffer( vertices.Length ); vertexBuffer.SetData( vertices, nv ); }
public BusSubscriptionCache(SubscriptionObserver observer) { _observer = observer; _subscriptions = new ConcurrentCache<SubscriptionKey, BusSubscription>( x => new BusSubscription(x.MessageName, x.CorrelationId, _observer)); }
private Cache<int, string> CreateCacheContainingFirstThousandCountingNumbers() { Cache<int, string> c = new Cache<int, string>(); foreach (KeyValuePair<int, string> entry in Enumerable.Range(1, 1000).Select(i => new KeyValuePair<int, string>(i, i.ToString()))) c.Add(entry); return c; }
static RequestContextValueProvider() { _values = new Cache<string, Func<RequestContext, object>>(); AddRequestProperty(r => r.AcceptTypes); AddRequestProperty(r => r.ContentEncoding); AddRequestProperty(r => r.ContentLength); AddRequestProperty(r => r.ContentType); AddRequestProperty(r => r.Cookies); AddRequestProperty(r => r.HasEntityBody); AddRequestProperty(r => r.Headers); AddRequestProperty(r => r.HttpMethod); AddRequestProperty(r => r.IsAuthenticated); AddRequestProperty(r => r.IsLocal); AddRequestProperty(r => r.IsSecureConnection); AddRequestProperty(r => r.KeepAlive); AddRequestProperty(r => r.LocalEndpoint); AddRequestProperty(r => r.ProtocolVersion); AddRequestProperty(r => r.QueryString); AddRequestProperty(r => r.RawUrl); AddRequestProperty(r => r.RemoteEndpoint); AddRequestProperty(r => r.Url); AddRequestProperty(r => r.UrlReferrer); AddRequestProperty(r => r.UserAgent); AddRequestProperty(r => r.UserHostAddress); AddRequestProperty(r => r.UserHostName); AddRequestProperty(r => r.UserLanguages); }
public CsdlSemanticsAssertTypeExpression(CsdlAssertTypeExpression expression, IEdmEntityType bindingContext, CsdlSemanticsSchema schema) : base(schema, expression) { this.operandCache = new Cache<CsdlSemanticsAssertTypeExpression, IEdmExpression>(); this.typeCache = new Cache<CsdlSemanticsAssertTypeExpression, IEdmTypeReference>(); this.expression = expression; this.bindingContext = bindingContext; }
// Called before the action in the inherited controller is executed, allowing certain members to be set protected override void OnActionExecuting(ActionExecutingContext ctx) { base.OnActionExecuting(ctx); this.db = HengeApplication.DataProvider; this.globals = HengeApplication.Globals; // If the user has logged in then add their name to the view data if (this.User.Identity.IsAuthenticated) { this.user = this.db.Get<User>(x => x.Name == this.User.Identity.Name); this.avatar = Session["Avatar"] as Avatar; if(this.avatar != null && this.avatar.User != this.user) { this.avatar = null; } this.cache = Session["Cache"] as Cache; this.ViewData["User"] = this.User.Identity.Name; this.ViewData["Character"] = (this.avatar != null) ? string.Format("{0} of {1}", this.avatar.Name, this.user.Clan) : null; } else { this.user = null; this.avatar = null; } }
public static CounterCache GetCounterCache(Cache cache, SessionManager manager) { try { if (s_CounterCache.Expired) { lock (s_CounterCache) { if (s_CounterCache.Expired) { s_CounterCache.Flush(manager); } } } } catch(Exception ex) { manager.BlogService.EventLogWriteEntry(string.Format("GetCounterCache failed to flush the cache. {0}", ex.Message), EventLogEntryType.Error); s_CounterCache = new CounterCache(); } return s_CounterCache; }
static PluginCache() { _setterRules = new List<Predicate<PropertyInfo>>(); _plugins = new Cache<Type, Plugin>(t => { var plugin = new Plugin(t); foreach (var rule in _setterRules) { plugin.UseSetterRule(rule); } return plugin; }); _builders = new Cache<Type, IInstanceBuilder>(t => { try { Plugin plugin = _plugins[t]; return BuilderCompiler.CreateBuilder(plugin); } catch (Exception e) { throw new StructureMapException(245, e, t.AssemblyQualifiedName); } }); }
public async Task should_keep_cache_if_versions_same() { var cacheConfiguration = new CacheConfiguration(1024, 5, 1024, 5); var cacheContainer = InitializeCacheContainer(); var storage = (TestStorage)cacheContainer.Resolve<IStorage>(); cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version(1, 1)); using (var cache = new Cache(cacheContainer, cacheConfiguration)) { await cache.Initialize(); //when at least one value set cache is written await cache.Set("some_entry", 42); } //cache should not be cleanued up if versions in storage and executing assembly differ cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version(1, 1)); using (var cache = new Cache(cacheContainer, cacheConfiguration)) { await cache.Initialize(); storage.KeyToStreams.Should().NotBeEmpty(); cache.Get<Int32>("some_entry").Result.Value.Should().Be(42); } }
public PersistentQueues(ILogger logger, IDelayedMessageCache<MessageId> delayedMessages, LightningQueueSettings settings) { _logger = logger; _delayedMessages = delayedMessages; _queueManagerConfiguration = settings.ToConfiguration(); _queueManagers = new Cache<int, QueueManager>(port => new QueueManager(new IPEndPoint(IPAddress.Any, port), EsentPath + "." + port, _queueManagerConfiguration)); }
/*[Test] public void RunTest100000() { MaxIterations = 100000; RunTest(); }*/ /*[Test] public void RunTest10000000() { MaxIterations = 10000000; RunTest(); }*/ private void RunTest() { NumIterations = 0; Cache = new Cache<long, CachedObject>(CreateForCache); Exception = null; CreatedObjects = new HashSet<long>(); List<Thread> threads = new List<Thread>(); for (int ctr = 0; ctr < Environment.ProcessorCount; ctr++) { Thread thread = new Thread(RunTestThread); thread.Name = "Cache test thread " + ctr.ToString(); thread.Start(); threads.Add(thread); } foreach (Thread thread in threads) thread.Join(); if (null != Exception) throw Exception; }
public static IList<DataServicePackage> GetPackages(Cache cache) { // Try to load if from the cache var packages = (IList<DataServicePackage>)cache.Get("packages"); // Double check lock if (packages == null) { lock (_lockObject) { packages = (IList<DataServicePackage>)cache.Get("packages"); if (packages == null) { // If we still don't have anything cached then get the package list and store it. packages = _repository.GetPackages().AsEnumerable().Cast<DataServicePackage>().ToList(); cache.Insert("packages", packages, null, DateTime.Now + TimeSpan.FromSeconds(20), Cache.NoSlidingExpiration); } } } return packages; }
public TextureFactory(Engine engine) { _missingTexture = engine.Content.Load<Texture2D>("Textures\\missing-texture"); _landCache = new Cache<int, Texture2D>(TimeSpan.FromMinutes(5), 0x1000); _lastCacheClean = DateTime.MinValue; _textures = new Textures(engine); }
public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetCaching"); //m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name); if (name == Name) { IConfig assetConfig = source.Configs["AssetCache"]; if (assetConfig == null) { m_log.Error("[ASSET CACHE]: AssetCache missing from OpenSim.ini"); return; } m_Cache = new Cache(CacheMedium.Memory, CacheStrategy.Aggressive, CacheFlags.AllowUpdate); m_Enabled = true; m_log.Info("[ASSET CACHE]: Core asset cache enabled"); m_Cache.Size = assetConfig.GetInt("CacheBuckets", 32768); } } }
static Cache<string, List<Actor>> GatherOwnedPrerequisites(Player player) { var ret = new Cache<string, List<Actor>>(x => new List<Actor>()); if (player == null) return ret; // Add all actors that provide prerequisites var prerequisites = player.World.ActorsWithTrait<ITechTreePrerequisite>() .Where(a => a.Actor.Owner == player && a.Actor.IsInWorld && !a.Actor.IsDead); foreach (var b in prerequisites) { foreach (var p in b.Trait.ProvidesPrerequisites) { // Ignore bogus prerequisites if (p == null) continue; ret[p].Add(b.Actor); } } // Add buildables that have a build limit set and are not already in the list player.World.ActorsWithTrait<Buildable>() .Where(a => a.Actor.Owner == player && a.Actor.IsInWorld && !a.Actor.IsDead && !ret.ContainsKey(a.Actor.Info.Name) && a.Actor.Info.TraitInfo<BuildableInfo>().BuildLimit > 0) .Do(b => ret[b.Actor.Info.Name].Add(b.Actor)); return ret; }
public void CacheBeforeExpiration() { var target = new Cache<string>(); target.GetOrAdd("k", () => "v1", () => DateTime.UtcNow.AddMinutes(1)); var actual = target.GetOrAdd("k", () => { throw new InvalidOperationException(); }, () => { throw new InvalidOperationException(); }); Assert.AreEqual("v1", actual); }
internal DbUser(UserStruct? user, ParentClass parent, ConnectionStringStruct connection, DataAccessErrorDelegate errorMessageDelegate, bool standAlone) { this.parent = parent; connectionString = connection; ErrorMessageDelegate = errorMessageDelegate; cache = new Cache(true); if (!user.HasValue) throw new NoValidUserException(); this.authenticationStruct = user.Value; this.username = user.Value.UserName; this.hashedPassword = user.Value.Password; this.standAlone = standAlone; this.user = user; securityFramework = MLifter.DAL.Security.SecurityFramework.GetDataAdapter(this); if (username != null && securityFramework != null) { try { securityToken = securityFramework.CreateSecurityToken(this.username); securityToken.IsCaching = cachePermissions; } catch (Exception ex) { Debug.WriteLine("Failed to create security token! (" + ex.Message + ")"); } } Login(); }
/// <summary> /// Initializes a new instance of the <see cref="BusSubscriptionConnector"/> class. /// </summary> /// <param name="bus">The bus.</param> public BusSubscriptionConnector(IServiceBus bus) { _dataBusSubscriptionCache = new EndpointSubscriptionConnectorCache(bus); _controlBusSubscriptionCache = new EndpointSubscriptionConnectorCache(bus.ControlBus); _connectionCache = new ConcurrentCache<Guid, UnsubscribeAction>(); }
public void SetUp() { testee = new Cache<string, string>(8); var field = testee.GetType().GetField("items", BindingFlags.Instance | BindingFlags.NonPublic); items = field.GetValue(testee) as List<CacheItem<string, string>>; }
public EventListenerRequest(IEventContract contract, Cache cache) : base(contract.Reference, HttpMethod.Get) { this.contract = contract; this.cache = cache; cts = new CancellationTokenSource(); }
public LuaScriptContext() { Log.Write("debug", "Creating Lua script context"); Lua = new Lua(); Lua.HookException += OnLuaException; functionCache = new Cache<string, LuaFunction>(Lua.GetFunction); }
public CsdlSemanticsPropertyValueBinding(CsdlSemanticsTypeAnnotation context, CsdlPropertyValue property) : base(property) { this.valueCache = new Cache<CsdlSemanticsPropertyValueBinding, IEdmExpression>(); this.boundPropertyCache = new Cache<CsdlSemanticsPropertyValueBinding, IEdmProperty>(); this.context = context; this.property = property; }
public SubscriptionCache(ChannelGraph graph, IEnumerable<ITransport> transports) { if (!transports.Any()) { throw new Exception( "No transports are registered. FubuTransportation cannot function without at least one ITransport"); } _graph = graph; _transports = transports; _volatileNodes = new Cache<Uri, ChannelNode>(uri => { var transport = _transports.FirstOrDefault(x => x.Protocol == uri.Scheme); if (transport == null) { throw new UnknownChannelException(uri); } var node = new ChannelNode { Uri = uri, Key = uri.ToString() }; node.Channel = transport.BuildDestinationChannel(node.Uri); return node; }); }
public void ValueAndIsDirtyTest() { int value = 3; int factoryCallCount = 0; var cache = new Cache<int>(() => { factoryCallCount++; return value; }); Assert.IsTrue(cache.IsDirty); Assert.AreEqual(0, factoryCallCount); Assert.AreEqual(3, cache.Value); Assert.IsFalse(cache.IsDirty); Assert.AreEqual(1, factoryCallCount); // Now the cached value is used. Assert.AreEqual(3, cache.Value); Assert.IsFalse(cache.IsDirty); Assert.AreEqual(1, factoryCallCount); value = 4; cache.SetDirty(); Assert.IsTrue(cache.IsDirty); Assert.AreEqual(4, cache.Value); Assert.IsFalse(cache.IsDirty); Assert.AreEqual(2, factoryCallCount); AssertHelper.ExpectedException<ArgumentNullException>(() => new Cache<int>(null)); }
public void for_each_attribute() { var cache = new Cache<string, string> { OnMissing = key => { Assert.Fail(key + " does not exist"); return null; } }; var node = new JsonNode("Test"); node.InnerText = "something"; node["a"] = "1"; node["b"] = "2"; node["c"] = "3"; node.ForEachAttribute((key, value) => cache[key] = value); cache.Count.ShouldEqual(3); cache["a"].ShouldEqual("1"); cache["b"].ShouldEqual("2"); cache["c"].ShouldEqual("3"); }
public NugetService(Solution solution) { //_defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl); var factory = new PackageRepositoryFactory(); _remoteRepository = factory.CreateRepository(GalleryUrl); _localRepository = factory.CreateRepository(solution.PackagesFolder()); _sourceRepository = new AggregateRepository(new[] { _remoteRepository, _localRepository }); _fileSystem = new PhysicalFileSystem(solution.PackagesFolder()); _pathResolver = new DefaultPackagePathResolver(_fileSystem); _console = new Console(); _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){ Logger = _console }; _packages = new Cache<NugetDependency, IPackage>(dep => { Install(dep); return _sourceRepository.FindPackage(dep.Name, dep.Version); }); }
public MessageListViewModel(string folderId, FolderType folderType, MailBoxViewModel mailBox, IProfileDataQueryFactory queryFactory, IMailService mailService, ViewModelActivator activator) { var canExecute = this.WhenAnyObservable(x => x.Cache.SelectionChanged) .Select(x => x.IndexCount() > 0) .Publish(); Activator = activator; Archive = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); await mailService.MoveMessage(messageIds, FolderType.Archive); }, canExecute); Delete = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); if (folderType != FolderType.DeletedItems) { await mailService.MoveMessage(messageIds, FolderType.DeletedItems); } }, canExecute); MarkAsRead = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); await mailService.UpdateMessage(messageIds) .Set(m => m.IsRead, true) .ExecuteAsync(); }, canExecute); MarkAsUnread = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); await mailService.UpdateMessage(messageIds) .Set(m => m.IsRead, false) .ExecuteAsync(); }, canExecute); SetFlag = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); await mailService.UpdateMessage(messageIds) .Set(m => m.IsFlagged, true) .ExecuteAsync(); }, canExecute); ClearFlag = ReactiveCommand.Create <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); await mailService.UpdateMessage(messageIds) .Set(m => m.IsFlagged, false) .ExecuteAsync(); }, canExecute); Move = ReactiveCommand.CreateFromTask <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); var selectionResult = await mailBox.PromptUserToSelectFolder( messageIds.Count == 1 ? "Move a message" : $"Move {messageIds.Count} messages", "Select another folder to move to:", includeRoot: false, destinationFolder => CanMoveTo(folderId, destinationFolder)); if (!selectionResult.IsCancelled) { await mailService.MoveMessage(messageIds, selectionResult.SelectedFolder.Id); } }, canExecute); MoveToJunk = ReactiveCommand.CreateFromTask <IReadOnlyList <string> >(async messageIds => { PrepareMessageIds(ref messageIds); await mailService.MoveMessage(messageIds, FolderType.Junk); }, canExecute); this.WhenActivated(disposables => { canExecute.Connect() .DisposeWith(disposables); Archive.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); Delete.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); SetFlag.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); ClearFlag.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); MarkAsRead.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); MarkAsUnread.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); Move.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); MoveToJunk.ThrownExceptions .Do(this.Log().Error) .Subscribe() .DisposeWith(disposables); Observable.CombineLatest( this.WhenAnyValue(x => x.Order), this.WhenAnyValue(x => x.Filter), (order, filter) => (Order: order, Filter: filter)) .DistinctUntilChanged() .Where(x => x.Order != MessageOrder.Sender) .Subscribe(x => { Cache?.Dispose(); Cache = new VirtualizingCache <MessageSummary, MessageSummaryViewModel, string>( new PersistentVirtualizingSource <MessageSummary, string>(queryFactory, GetItemSpecification(folderId, x.Order, x.Filter), GetIndexSpecification(folderId, x.Order, x.Filter)), mailService.MessageChanges .Select(changes => FilterChanges(changes.ForFolder(folderId), x.Filter)), state => new MessageSummaryViewModel(state, this, queryFactory)); }) .DisposeWith(disposables); this.WhenAnyObservable(x => x.Cache.SelectionChanged) .Select(ranges => ranges.Sum(r => r.Length)) .Do(x => SelectionCount = x) .Subscribe() .DisposeWith(disposables); Disposable.Create(() => { Filter = MessageFilter.None; Cache?.Dispose(); Cache = null; IsSelecting = false; SelectionCount = 0; }) .DisposeWith(disposables); }); }
private async Task <TModel> Create <TModel>(Type rootModelType, object model) { ThrowIfDisposed(); // set Id if unset var modelId = model == null ? Guid.NewGuid() : ModelRegistry.GetOrCreateId(model); if (modelId == Guid.Empty) { modelId = Guid.NewGuid(); ModelRegistry.SetId(model, modelId); } // Create a new model instance if not already existing if (model == null) { model = Activator.CreateInstance <TModel>(); ModelRegistry.SetId(model, modelId); } if (ModelRegistry.IsManagedModel(model)) { throw new ManagedModelCreationException(model.GetType(), modelId); } // all unmanaged models in the object graph, including root var allModels = ModelRegistry.IncludedModelsCreate(model); foreach (var newModel in allModels) { var newResource = BuildModelResource(newModel); // Update the model instance in the argument var initialize = newModel.GetType().GetInitializeMethod(); initialize.Invoke(newModel, new object[] { newResource, this }); } var rootResource = ModelRegistry.GetResource(model); var includes = allModels.Where(x => x != model).Select(ModelRegistry.GetResource).ToArray(); if (Log.IsDebugEnabled()) { Log.Debug(() => $"preparing to POST {rootResource.Type}:{{{rootResource.Id}}}"); foreach (var include in includes) { Log.Debug(() => $"preparing to POST included {include.Type}:{{{include.Id}}}"); } } var root = ResourceRootSingle.FromResource(rootResource, includes); var request = await HttpRequestBuilder.CreateResource(root); var response = await HttpClient.SendAsync(request).ConfigureAwait(false); HttpResponseListener.CreateResource(response.StatusCode, root); response.CheckStatusCode(); if (response.StatusCode == HttpStatusCode.Created) { var responseRoot = await response.GetContentModel <ResourceRootSingle>(JsonSettings); // Update the model instance in the argument var initialize = rootModelType.GetInitializeMethod(); initialize.Invoke(model, new object[] { responseRoot.Data, this }); } // create and cache includes await Task.WhenAll(allModels.Select(x => Task.Run(() => { var resource = ModelRegistry.GetResource(x); Cache.Update(resource.Id, x); }))); return((TModel)model); }
/// <summary> /// 从缓存中删除指定项 /// </summary> /// <param name="shortKey"></param> public static async Task RemoveFromCacheAsync(string shortKey) { var cacheKey = GetBagCacheKey(shortKey); await Cache.RemoveFromCacheAsync(cacheKey); }
/// <summary> /// 从缓存中删除指定项 /// </summary> /// <param name="shortKey"></param> public static void RemoveFromCache(string shortKey) { var cacheKey = GetBagCacheKey(shortKey); Cache.RemoveFromCache(cacheKey); }
public AssetValueBusiness(ILoggerFactory loggerFactory, Cache cache, INodeServices nodeServices) : base(loggerFactory, cache, nodeServices) { }
public void Authorized(IConnection connection, string accountName) { connection.Account = Cache.GetAccount(accountName); }
public Wpt(XmlNode node) { Coordinates.Lat = node.Attributes?["lat"].Value; Coordinates.Lon = node.Attributes?["lon"].Value; foreach (XmlNode childNode in node.ChildNodes) { switch (childNode.Name) { case "time": Time = childNode.InnerText; break; case "name": Name = childNode.InnerText; break; case "desc": Desc = childNode.InnerText; break; case "url": Url = childNode.InnerText; break; case "urlname": UrlName = childNode.InnerText; break; case "sym": Sym = childNode.InnerText; break; case "type": Type = childNode.InnerText; break; case "ele": Ele = childNode.InnerText; break; case "cmt": Cmt = childNode.InnerText; break; case "groundspeak:cache": GroundspeakCache = new Cache(childNode); break; case "ox:opencaching": foreach (XmlNode openCachingChildNode in childNode.ChildNodes) { switch (openCachingChildNode.Name) { case "ox:ratings": foreach (XmlNode openCachingRatingsChildNode in openCachingChildNode.ChildNodes) { switch (openCachingRatingsChildNode.Name) { case "ox:awesomeness": OpencachingAwesomeness = openCachingRatingsChildNode.InnerText; break; case "ox:difficulty": OpencachingDifficulty = openCachingRatingsChildNode.InnerText; break; case "ox:terrain": OpencachingTerrain = openCachingRatingsChildNode.InnerText; break; case "ox:size": OpencachingSize = openCachingRatingsChildNode.InnerText; break; default: throw new Exception("Unhandled for Child Object: " + openCachingRatingsChildNode.Name); } } break; case "ox:tags": foreach (XmlNode openCachingTagNode in openCachingChildNode.ChildNodes) { switch (openCachingTagNode.Name) { case "ox:tag": OpencachingTags.Add(openCachingTagNode.InnerXml); break; default: throw new Exception("Unhandled for Child Object: " + openCachingTagNode.Name); } } break; case "ox:verification": foreach (XmlNode openCachingVerificationNode in openCachingChildNode.ChildNodes) { switch (openCachingVerificationNode.Name) { case "ox:phrase": OpencachingVerificationPhrase = openCachingChildNode.InnerText; break; case "ox:number": OpencachingVerificationNumber = openCachingChildNode.InnerText; break; case "ox:QR": OpencachingVerificationQr = openCachingChildNode.InnerText; break; case "ox:chirp": OpencachingVerificationChirp = openCachingChildNode.InnerText; break; default: throw new Exception("Unhandled for Child Object: " + openCachingVerificationNode.Name); } } break; case "ox:series": OpencachingSeriesName = openCachingChildNode.InnerText; OpencachingSeriesId = openCachingChildNode.Attributes?["id"].Value; break; default: throw new Exception("Unhandled for Child Object: " + openCachingChildNode.Name); } } break; default: throw new Exception("Unhandled for Child Object: " + childNode.Name); } } }
/// <summary> /// 分页查询文章列表 /// </summary> /// <param name="input"></param> /// <param name="factory"></param> /// <returns></returns> public async Task <ServiceResult <PagedList <QueryPostDto> > > QueryPostsAsync(PagingInput input, Func <Task <ServiceResult <PagedList <QueryPostDto> > > > factory) { return(await Cache.GetOrAddAsync(KEY_QueryPosts.FormatWith(input.Page, input.Limit), factory, CacheStrategy.ONE_DAY)); }
public GetUsersResponse FetchUsers() { var cache = Cache.Get("users", () => _dbService.GetUsers(), 1); //maybe do paging return(cache); }
/// <summary> /// 通过标签名称查询文章列表 /// </summary> /// <param name="name"></param> /// <param name="factory"></param> /// <returns></returns> public async Task <ServiceResult <IEnumerable <QueryPostDto> > > QueryPostsByTagAsync(string name, Func <Task <ServiceResult <IEnumerable <QueryPostDto> > > > factory) { return(await Cache.GetOrAddAsync(KEY_QueryPostsByTag.FormatWith(name), factory, CacheStrategy.ONE_DAY)); }
public FrameCache(IReadOnlyFileSystem fileSystem, ISpriteLoader[] loaders) { TypeDictionary metadata; frames = new Cache <string, ISpriteFrame[]>(filename => FrameLoader.GetFrames(fileSystem, filename, loaders, out metadata)); }
/// <summary> /// 根据URL获取文章详情 /// </summary> /// <param name="url"></param> /// <param name="factory"></param> /// <returns></returns> public async Task <ServiceResult <PostDetailDto> > GetPostDetailAsync(string url, Func <Task <ServiceResult <PostDetailDto> > > factory) { return(await Cache.GetOrAddAsync(KEY_GetPostDetail.FormatWith(url), factory, CacheStrategy.ONE_DAY)); }
public void Update(IInvalidator invalidator, LiveSplitState state, float width, float height, LayoutMode mode) { Cache.Restart(); var timingMethod = state.CurrentTimingMethod; if (Settings.TimingMethod == "Real Time") { timingMethod = TimingMethod.RealTime; } else if (Settings.TimingMethod == "Game Time") { timingMethod = TimingMethod.GameTime; } var timeValue = GetTime(state, timingMethod); if (timeValue == null && timingMethod == TimingMethod.GameTime) { timeValue = GetTime(state, TimingMethod.RealTime); } if (timeValue != null) { var timeString = Formatter.Format(timeValue, CurrentTimeFormat); int dotIndex = timeString.IndexOf("."); BigTextLabel.Text = timeString.Substring(0, dotIndex); if (CurrentAccuracy == TimeAccuracy.Hundredths) { SmallTextLabel.Text = timeString.Substring(dotIndex); } else if (CurrentAccuracy == TimeAccuracy.Tenths) { SmallTextLabel.Text = timeString.Substring(dotIndex, 2); } else { SmallTextLabel.Text = ""; } } else { SmallTextLabel.Text = TimeFormatConstants.DASH; BigTextLabel.Text = ""; } if (state.CurrentPhase == TimerPhase.NotRunning || state.CurrentTime[timingMethod] < TimeSpan.Zero) { TimerColor = state.LayoutSettings.NotRunningColor; } else if (state.CurrentPhase == TimerPhase.Paused) { TimerColor = state.LayoutSettings.PausedColor; } else if (state.CurrentPhase == TimerPhase.Ended) { if (state.Run.Last().Comparisons[state.CurrentComparison][timingMethod] == null || state.CurrentTime[timingMethod] < state.Run.Last().Comparisons[state.CurrentComparison][timingMethod]) { TimerColor = state.LayoutSettings.PersonalBestColor; } else { TimerColor = state.LayoutSettings.BehindLosingTimeColor; } } else if (state.CurrentPhase == TimerPhase.Running) { if (state.CurrentSplit.Comparisons[state.CurrentComparison][timingMethod] != null) { TimerColor = LiveSplitStateHelper.GetSplitColor(state, state.CurrentTime[timingMethod] - state.CurrentSplit.Comparisons[state.CurrentComparison][timingMethod], state.CurrentSplitIndex, true, false, state.CurrentComparison, timingMethod) ?? state.LayoutSettings.AheadGainingTimeColor; } else { TimerColor = state.LayoutSettings.AheadGainingTimeColor; } } if (Settings.OverrideSplitColors) { BigTextLabel.ForeColor = Settings.TimerColor; SmallTextLabel.ForeColor = Settings.TimerColor; } else { BigTextLabel.ForeColor = TimerColor; SmallTextLabel.ForeColor = TimerColor; } Cache["TimerText"] = BigTextLabel.Text + SmallTextLabel.Text; if (BigTextLabel.Brush != null && invalidator != null) { Cache["TimerColor"] = BigTextLabel.ForeColor.ToArgb(); } if (invalidator != null && Cache.HasChanged) { invalidator.Invalidate(0, 0, width, height); } }
public static void RunMMPTest(Action <string> test, string directoryName = null) { test(Cache.CreateTemporaryDirectory(directoryName)); }
private IEnumerable <ITagSpan <IClassificationTag> > GetTagsImpl( Cache doc, NormalizedSnapshotSpanCollection spans) { var snapshot = spans[0].Snapshot; IEnumerable <ClassifiedSpan> identifiers = GetIdentifiersInSpans(doc.Workspace, doc.SemanticModel, spans); foreach (var id in identifiers) { var node = GetExpression(doc.SyntaxRoot.FindNode(id.TextSpan)); var symbol = doc.SemanticModel.GetSymbolInfo(node).Symbol; if (symbol == null) { symbol = doc.SemanticModel.GetDeclaredSymbol(node); } if (symbol == null) { continue; } switch (symbol.Kind) { case SymbolKind.Field: if (symbol.ContainingType.TypeKind != TypeKind.Enum) { yield return(id.TextSpan.ToTagSpan(snapshot, fieldType)); } else { yield return(id.TextSpan.ToTagSpan(snapshot, enumFieldType)); } break; case SymbolKind.Method: if (IsExtensionMethod(symbol)) { yield return(id.TextSpan.ToTagSpan(snapshot, extensionMethodType)); } else if (symbol.IsStatic) { yield return(id.TextSpan.ToTagSpan(snapshot, staticMethodType)); } else { yield return(id.TextSpan.ToTagSpan(snapshot, normalMethodType)); } break; case SymbolKind.TypeParameter: yield return(id.TextSpan.ToTagSpan(snapshot, typeParameterType)); break; case SymbolKind.Parameter: yield return(id.TextSpan.ToTagSpan(snapshot, parameterType)); break; case SymbolKind.Namespace: yield return(id.TextSpan.ToTagSpan(snapshot, namespaceType)); break; case SymbolKind.Property: yield return(id.TextSpan.ToTagSpan(snapshot, propertyType)); break; case SymbolKind.Local: yield return(id.TextSpan.ToTagSpan(snapshot, localType)); break; case SymbolKind.NamedType: if (isSpecialType(symbol)) { yield return(id.TextSpan.ToTagSpan(snapshot, typeSpecialType)); } else { yield return(id.TextSpan.ToTagSpan(snapshot, typeNormalType)); } break; } } }
/// <summary>Saves an object.</summary> /// <param name="obj">Object.</param> /// <param name="ent">Entity.</param> /// <param name="hasMaterialBase">Determines if the base class table is material.</param> /// <param name="isBase">Determines if the the object is the base class table.</param> private static void _Save(object obj, __Entity ent, bool hasMaterialBase, bool isBase) { if (Cache != null) { if (!Cache.HasChanged(obj)) { return; } } IDbCommand cmd = Connection.CreateCommand(); string update = ""; string insert = ""; cmd.CommandText = ("INSERT INTO " + ent.TableName + " ("); if (hasMaterialBase) { cmd.CommandText += ent.ChildKey + ", "; update = "ON CONFLICT (" + ent.ChildKey + ") DO UPDATE SET "; insert = (":ck, "); IDataParameter k = cmd.CreateParameter(); k.ParameterName = ":ck"; k.Value = ent.PrimaryKey.GetValue(obj); cmd.Parameters.Add(k); } else { update = "ON CONFLICT (" + ent.PrimaryKey.ColumnName + ") DO UPDATE SET "; } IDataParameter p; bool first = true; for (int i = 0; i < ent.LocalInternals.Length; i++) { if (i > 0) { cmd.CommandText += ", "; insert += ", "; } cmd.CommandText += ent.LocalInternals[i].ColumnName; insert += (":v" + i.ToString()); p = cmd.CreateParameter(); p.ParameterName = (":v" + i.ToString()); p.Value = ent.LocalInternals[i].ToColumnType(ent.LocalInternals[i].GetValue(obj)); cmd.Parameters.Add(p); if (!ent.LocalInternals[i].IsPrimaryKey) { if (first) { first = false; } else { update += ", "; } update += (ent.LocalInternals[i].ColumnName + " = " + (":w" + i.ToString())); p = cmd.CreateParameter(); p.ParameterName = (":w" + i.ToString()); p.Value = ent.LocalInternals[i].ToColumnType(ent.LocalInternals[i].GetValue(obj)); cmd.Parameters.Add(p); } } cmd.CommandText += (") VALUES (" + insert + ") " + update); cmd.ExecuteNonQuery(); cmd.Dispose(); if (!isBase) { foreach (__Field i in ent.Externals) { i.UpdateReferences(obj); } } if (Cache != null) { Cache.Put(obj); } }
protected void Page_Load(object sender, EventArgs e) { ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None; Cache.Remove("List"); }
public ArticulosServicio(IAlmacenamiento almacenamiento, ILogging logging, Cache cache) { _logging = logging; _almacenamiento = almacenamiento; _cache = cache; }
/// <summary> /// 静态构造函数 /// </summary> static CacheHelper() { _cache = HttpRuntime.Cache; }
public Result <ServiceResponse> ResetPassword(ResetPasswordRequest request, [FromServices] ISqlConnections sqlConnections) { return(this.InTransaction("Default", uow => { if (request is null) { throw new ArgumentNullException(nameof(request)); } if (string.IsNullOrEmpty(request.Token)) { throw new ArgumentNullException("token"); } var bytes = HttpContext.RequestServices .GetDataProtector("ResetPassword").Unprotect(Convert.FromBase64String(request.Token)); int userId; using (var ms = new MemoryStream(bytes)) using (var br = new BinaryReader(ms)) { var dt = DateTime.FromBinary(br.ReadInt64()); if (dt < DateTime.UtcNow) { throw new ValidationError(Texts.Validation.InvalidResetToken.ToString(Localizer)); } userId = br.ReadInt32(); } UserRow user; if (sqlConnections is null) { throw new ArgumentNullException(nameof(sqlConnections)); } using (var connection = sqlConnections.NewFor <UserRow>()) { user = connection.TryById <UserRow>(userId); if (user == null) { throw new ValidationError(Texts.Validation.InvalidResetToken.ToString(Localizer)); } } if (request.ConfirmPassword != request.NewPassword) { throw new ValidationError("PasswordConfirmMismatch", Localizer.Get("Validation.PasswordConfirm")); } request.NewPassword = UserRepository.ValidatePassword(request.NewPassword, Localizer); string salt = null; var hash = UserRepository.GenerateHash(request.NewPassword, ref salt); UserRepository.CheckPublicDemo(user.UserId); uow.Connection.UpdateById(new UserRow { UserId = user.UserId.Value, PasswordSalt = salt, PasswordHash = hash }); Cache.InvalidateOnCommit(uow, UserRow.Fields); return new ServiceResponse(); })); }
/// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="cacheKey"></param> /// <param name="objObject"></param> /// <param name="absoluteExpiration"></param> /// <param name="slidingExpiration"></param> public static void SetCache(string cacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { Cache objCache = HttpRuntime.Cache; objCache.Insert(cacheKey, objObject, null, absoluteExpiration, slidingExpiration); }
internal void AddCache(string cacheId, Cache cache) { _caches[cacheId.ToLower()] = cache; }
public void MakeGantt() { UC = (UserConfig)HttpContext.Current.Session["userconfig"]; DataSet prjInfo = DatabaseConnection.CreateDataset(@"SELECT PROJECT.TITLE, ACCOUNT.NAME + ' ' + ACCOUNT.SURNAME AS OWNERNAME FROM PROJECT INNER JOIN ACCOUNT ON PROJECT.OWNER = ACCOUNT.UID WHERE ID=" + prjID); DataSet sections = DatabaseConnection.CreateDataset(String.Format(@"SELECT PROJECT_SECTION.ID,PROJECT_SECTION.TITLE,PROJECT_SECTION.DESCRIPTION,PROJECT_SECTION.PARENT,PROJECT_TIMING.PROGRESS,PROJECT_TIMING.PLANNEDSTARTDATE, PROJECT_TIMING.PLANNEDENDDATE, PROJECT_SECTION.MEMBERID, ACCOUNT.NAME+' '+ACCOUNT.SURNAME AS OWNERNAME, PROJECT_TIMING.PLANNEDMINUTEDURATION, PROJECT_SECTION.COLOR FROM PROJECT_SECTION LEFT OUTER JOIN PROJECT_TIMING ON (PROJECT_SECTION.ID=PROJECT_TIMING.IDRIF AND PROJECT_TIMING.RIFTYPE=0) INNER JOIN ACCOUNT ON PROJECT_SECTION.MEMBERID=ACCOUNT.UID WHERE PROJECT_SECTION.PARENT IS NULL AND PROJECT_SECTION.IDRIF={0} ORDER BY PROJECT_SECTION.SECTIONORDER; SELECT PROJECT_SECTION.ID,PROJECT_SECTION.TITLE,PROJECT_SECTION.DESCRIPTION,PROJECT_SECTION.PARENT,PROJECT_TIMING.PROGRESS,PROJECT_TIMING.PLANNEDSTARTDATE, PROJECT_TIMING.PLANNEDENDDATE, PROJECT_SECTION.MEMBERID, ACCOUNT.NAME+' '+ACCOUNT.SURNAME AS OWNERNAME, PROJECT_TIMING.PLANNEDMINUTEDURATION, PROJECT_SECTION.COLOR FROM PROJECT_SECTION LEFT OUTER JOIN PROJECT_TIMING ON (PROJECT_SECTION.ID=PROJECT_TIMING.IDRIF AND PROJECT_TIMING.RIFTYPE=0) INNER JOIN ACCOUNT ON PROJECT_SECTION.MEMBERID=ACCOUNT.UID WHERE PROJECT_SECTION.PARENT IS NOT NULL AND PROJECT_SECTION.IDRIF={0} ORDER BY PROJECT_SECTION.SECTIONORDER;", prjID)); if (sections.Tables[0].Rows.Count > 0) { DigiGantt.CoordsMaps rects = new DigiGantt.CoordsMaps(); DigiGantt dg = new DigiGantt(); DataRow startdates = DatabaseConnection.CreateDataset(string.Format(@"SELECT TOP 1 PLANNEDSTARTDATE, (select top 1 newstartdate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=1) inner join PROJECT_SECTION_MEMBERS on PROJECT_TIMING.idrif=PROJECT_SECTION_MEMBERS.id inner join PROJECT_SECTION on (PROJECT_SECTION_MEMBERS.IDSectionRif = PROJECT_SECTION.id) where PROJECT_SECTION.IDRIF={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=1 order by newstartdate asc) as variation, (select top 1 newstartdate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=0) inner join PROJECT_SECTION on (PROJECT_Timing.idrif = PROJECT_SECTION.id) where PROJECT_SECTION.IDRIF={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=0 order by newstartdate asc) as globalvariation FROM PROJECT_SECTION INNER JOIN PROJECT_TIMING ON (PROJECT_SECTION.ID=PROJECT_TIMING.IDRIF AND RIFTYPE=0) WHERE PROJECT_SECTION.IDRIF={0} AND PLANNEDSTARTDATE IS NOT NULL ORDER BY PLANNEDSTARTDATE ASC;", prjID)).Tables[0].Rows[0]; DateTime firststartDate = UC.LTZ.ToLocalTime((DateTime)startdates[0]); DateTime startDate; if (startdates[1] != System.DBNull.Value) { if (startdates[2] != System.DBNull.Value && ((DateTime)startdates[1]) < ((DateTime)startdates[2])) { startDate = UC.LTZ.ToLocalTime((DateTime)startdates[1]); } else { startDate = UC.LTZ.ToLocalTime((DateTime)startdates[2]); } } else if (startdates[2] != System.DBNull.Value && firststartDate < ((DateTime)startdates[2])) { startDate = firststartDate; } else if (startdates[2] != System.DBNull.Value) { startDate = UC.LTZ.ToLocalTime((DateTime)startdates[2]); } else { startDate = firststartDate; } DataRow enddates = DatabaseConnection.CreateDataset(string.Format(@"SELECT top 1 PLANNEDENDDATE, (select top 1 newplanneddate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=1) inner join PROJECT_SECTION_MEMBERS on PROJECT_TIMING.idrif=PROJECT_SECTION_MEMBERS.id inner join PROJECT_SECTION on (PROJECT_SECTION_MEMBERS.IDSectionRif = PROJECT_SECTION.id) where PROJECT_SECTION.IDRIF={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=1 order by newplanneddate desc) as variation, (select top 1 newplanneddate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=0) inner join PROJECT_SECTION on (PROJECT_Timing.idrif = PROJECT_SECTION.id) where PROJECT_SECTION.IDRIF={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=0 order by newplanneddate desc) as globalvariation FROM PROJECT_SECTION JOIN PROJECT_TIMING ON (PROJECT_SECTION.ID=PROJECT_TIMING.IDRIF AND RIFTYPE=0) WHERE PROJECT_SECTION.IDRIF={0} AND PLANNEDSTARTDATE IS NOT NULL ORDER BY PLANNEDENDDATE DESC;", prjID)).Tables[0].Rows[0]; DateTime firstendDate = UC.LTZ.ToLocalTime((DateTime)enddates[0]); DateTime endDate = firstendDate; if (enddates[1] != System.DBNull.Value) { if (enddates[2] != System.DBNull.Value && ((DateTime)enddates[1]) > ((DateTime)enddates[2])) { endDate = UC.LTZ.ToLocalTime((DateTime)enddates[1]); } else if (enddates[2] != System.DBNull.Value) { endDate = UC.LTZ.ToLocalTime((DateTime)enddates[2]); } else if (((DateTime)enddates[1]) > firstendDate) { endDate = UC.LTZ.ToLocalTime((DateTime)enddates[1]); } } else if (enddates[2] != System.DBNull.Value && firstendDate > ((DateTime)enddates[2])) { endDate = firstendDate; } else if (enddates[2] != System.DBNull.Value) { endDate = UC.LTZ.ToLocalTime((DateTime)enddates[2]); } System.Drawing.Image img = dg.DrawSchema(out rects, 2000, startDate.AddDays(-2), endDate.AddDays(2), DigiGantt.RowsFlags.NoYears); rects.Add(dg.DrawProject(startDate, endDate, 1)); if (firstendDate != endDate) { rects.Add(dg.DrawExpected(firstendDate, Color.LightGreen, 1, 0, "Variazione data")); } int j = 2; ArrayList arsections = new ArrayList(); ArrayList arsections2 = new ArrayList(); ArrayList arsections3 = new ArrayList(); ArrayList arsections4 = new ArrayList(); ArrayList arsections5 = new ArrayList(); arsections.Add("Descrizione"); arsections2.Add("Inizio"); arsections3.Add("Fine"); arsections4.Add("Durata"); arsections5.Add("Responsabile"); arsections.Add("{P00}" + prjInfo.Tables[0].Rows[0][0].ToString()); arsections2.Add(startDate.ToString(@"dd/MM/yy")); arsections3.Add(endDate.ToString(@"dd/MM/yy")); arsections4.Add(DatabaseConnection.SqlScalar(string.Format(@"SELECT SUM(PLANNEDMINUTEDURATION) FROM PROJECT_SECTION INNER JOIN PROJECT_TIMING ON (PROJECT_TIMING.IDRIF=PROJECT_SECTION.ID AND PROJECT_TIMING.RIFTYPE=0) WHERE PROJECT_SECTION.IDRIF={0}", prjID))); arsections5.Add(prjInfo.Tables[0].Rows[0][1].ToString()); foreach (DataRow dr in sections.Tables[0].Rows) { j = MakeGanttBar(ref rects, ref dg, j, ref arsections, ref arsections2, ref arsections3, ref arsections4, ref arsections5, dr, 0, sections); } DataTable dtrelations = DatabaseConnection.CreateDataset("SELECT * FROM PROJECT_RELATIONS WHERE PROJECTID=" + prjID + " ORDER BY ID").Tables[0]; foreach (DataRow drrelations in dtrelations.Rows) { int r1 = 0; int r2 = 0; foreach (string i in connectors) { string[] s = i.Split('|'); if (s[0] == drrelations["FIRSTRIFID"].ToString()) { r1 = int.Parse(s[1]); break; } } foreach (string i in connectors) { string[] s = i.Split('|'); if (s[0] == drrelations["SECONDRIFID"].ToString()) { r2 = int.Parse(s[1]); break; } } DateTime d1 = new DateTime(); if (drrelations["RELATIONTYPE"].ToString() == "0") { d1 = UC.LTZ.ToLocalTime((DateTime)DatabaseConnection.SqlScalartoObj("SELECT PLANNEDSTARTDATE FROM PROJECT_TIMING WHERE RIFTYPE=0 AND IDRIF=" + drrelations["FIRSTRIFID"].ToString())); } else { d1 = UC.LTZ.ToLocalTime((DateTime)DatabaseConnection.SqlScalartoObj("SELECT PLANNEDENDDATE FROM PROJECT_TIMING WHERE RIFTYPE=0 AND IDRIF=" + drrelations["FIRSTRIFID"].ToString())); object variationend = DatabaseConnection.SqlScalartoObj(String.Format(@"select top 1 newplanneddate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=1) inner join PROJECT_SECTION_MEMBERS on PROJECT_TIMING.idrif=PROJECT_SECTION_MEMBERS.id inner join PROJECT_SECTION on (PROJECT_SECTION_MEMBERS.IDSectionRif = PROJECT_SECTION.id) where PROJECT_SECTION.ID={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=1 order by newplanneddate desc", drrelations["FIRSTRIFID"].ToString())); object variationend2 = DatabaseConnection.SqlScalartoObj(String.Format(@"select top 1 newplanneddate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=0) inner join PROJECT_SECTION on (PROJECT_TIMING.idrif = PROJECT_SECTION.id) where PROJECT_SECTION.ID={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=0 order by newplanneddate desc", drrelations["FIRSTRIFID"].ToString())); if (variationend != null && variationend != System.DBNull.Value) { if ((variationend2 != null && variationend2 != System.DBNull.Value) && ((DateTime)variationend2) > ((DateTime)variationend)) { d1 = UC.LTZ.ToLocalTime(Convert.ToDateTime(variationend2)); } else { d1 = UC.LTZ.ToLocalTime(Convert.ToDateTime(variationend)); } } else if (variationend2 != null && variationend2 != System.DBNull.Value) { d1 = UC.LTZ.ToLocalTime(Convert.ToDateTime(variationend2)); } } DateTime d2 = UC.LTZ.ToLocalTime((DateTime)DatabaseConnection.SqlScalartoObj("SELECT PLANNEDSTARTDATE FROM PROJECT_TIMING WHERE RIFTYPE=0 AND IDRIF=" + drrelations["SECONDRIFID"].ToString())); object variationstart = DatabaseConnection.SqlScalartoObj(String.Format(@"select top 1 newstartdate from PROJECT_TIMING_VARIATION inner join PROJECT_TIMING on (PROJECT_TIMING_VARIATION.idtiming=PROJECT_TIMING.ID AND PROJECT_TIMING.RIFTYPE=0) inner join PROJECT_SECTION on (PROJECT_TIMING.idrif = PROJECT_SECTION.id) where PROJECT_SECTION.ID={0} AND PROJECT_TIMING_VARIATION.RIFTYPE=0 order by newstartdate desc", drrelations["SECONDRIFID"].ToString())); if (variationstart != null && variationstart != System.DBNull.Value) { d2 = UC.LTZ.ToLocalTime(Convert.ToDateTime(variationstart)); } dg.DrawConnector(d1, r1, d2, r2); } img = dg.CloseGanttChart(img, j); string[][] mdArr = new string[5][] { ((string[])arsections.ToArray(typeof(System.String))), ((string[])arsections2.ToArray(typeof(System.String))), ((string[])arsections3.ToArray(typeof(System.String))), ((string[])arsections4.ToArray(typeof(System.String))), ((string[])arsections5.ToArray(typeof(System.String))) }; System.Drawing.Image img2 = dg.DrawLegend(ref rects, mdArr, 0); if (NoRender) { this.Img1 = img; this.Img2 = img2; } else { Cache.Add("Projectimg1_" + prjID, dg.ConvertImageToByteArray(img, System.Drawing.Imaging.ImageFormat.Png), null, DateTime.Now.AddSeconds(30), TimeSpan.Zero, CacheItemPriority.NotRemovable, null); Cache.Add("Projectimg2_" + prjID, dg.ConvertImageToByteArray(img2, System.Drawing.Imaging.ImageFormat.Png), null, DateTime.Now.AddSeconds(30), TimeSpan.Zero, CacheItemPriority.NotRemovable, null); litGantt.Text = dg.ImageMapRender("/project/GanttImg.aspx?prjID=" + prjID, rects); } } else { litGantt.Text = "<span style=\"color:red\"> Nessuna sezione in questo progetto.</span>"; } }
public virtual void Clear() => Cache.Clear();
/// <summary> /// Link the Http context cache to a Bugg repository. /// </summary> /// <param name="InCache">The current Http context cache.</param> /// <param name="InBuggRepository">The repository to associate the cache with.</param> public CachedDataService(Cache InCache, BuggRepository InBuggRepository) { CacheInstance = InCache; Buggs = InBuggRepository; }
/// <summary> /// 获取当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="cacheKey"></param> /// <returns></returns> public static object GetCache(string cacheKey) { Cache objCache = HttpRuntime.Cache; return objCache[cacheKey]; }
private void LogicQ() { var t = TargetSelector.GetTarget(Q.Range, TargetSelector.DamageType.Magical); var t1 = TargetSelector.GetTarget(Q1.Range, TargetSelector.DamageType.Magical); if (t.IsValidTarget()) { missileManager.Target = t; if (Program.Combo && Player.Mana > RMANA + QMANA) { Program.CastSpell(Q, t); } else if (Program.Harass && Config.Item("Harass" + t.ChampionName).GetValue <bool>() && Player.Mana > RMANA + WMANA + QMANA + QMANA && OktwCommon.CanHarras()) { Program.CastSpell(Q, t); } else if (OktwCommon.GetKsDamage(t, Q) * 2 > t.Health) { Program.CastSpell(Q, t); } if (Player.Mana > RMANA + QMANA + WMANA) { foreach (var enemy in HeroManager.Enemies.Where(enemy => enemy.IsValidTarget(Q.Range) && !OktwCommon.CanMove(enemy))) { Q.Cast(enemy, true, true); } } } else if (t1.IsValidTarget()) { missileManager.Target = t1; if (Program.Combo && Player.Mana > RMANA + QMANA) { Program.CastSpell(Q1, t1); } else if (Program.Harass && Config.Item("Harass" + t1.ChampionName).GetValue <bool>() && Player.Mana > RMANA + WMANA + QMANA + QMANA && OktwCommon.CanHarras()) { Program.CastSpell(Q1, t1); } else if (OktwCommon.GetKsDamage(t1, Q1) * 2 > t1.Health) { Program.CastSpell(Q1, t1); } if (Player.Mana > RMANA + QMANA + WMANA) { foreach (var enemy in HeroManager.Enemies.Where(enemy => enemy.IsValidTarget(Q1.Range) && !OktwCommon.CanMove(enemy))) { Q1.Cast(enemy, true, true); } } } else if (FarmSpells && Config.Item("farmQ", true).GetValue <bool>()) { var allMinionsQ = Cache.GetMinions(Player.ServerPosition, Q1.Range); var Qfarm = Q.GetLineFarmLocation(allMinionsQ, 100); if (Qfarm.MinionsHit >= FarmMinions) { Q.Cast(Qfarm.Position); } } }
private void InvalidateCache() { Cache.ClearCacheItem(GetCacheKey(this.Id)); }
void BindGrid() { if (Session[_FilterSessionName] != null) { var DictionarySession = (Dictionary <string, object>)Session[_FilterSessionName]; if (DictionarySession.Count != 0) { TxtRowIndexFilter.Text = DictionarySession["RowIndex"]._ToString(); //DlistCallCenterTypeFilter.SelectedValue = DictionarySession["CallCenterTypeID"]._ToString(); DListComplaintTypeFilter.SelectedValue = DictionarySession["ComplaintTypeID"]._ToString(); TxtApplicantFullnameFilter.Text = DictionarySession["ApplicantFullname"]._ToString(); DListApplicantGenderTypeFilter.SelectedValue = DictionarySession["GenderTypeID"]._ToString(); DListApplicantSocialStatusFilter.SelectedValue = DictionarySession["SocialStatusID"]._ToString(); TxtPhoneNumberFilter.Text = DictionarySession["PhoneNumber"]._ToString(); TxtVictimsFullnameFilter.Text = DictionarySession["VictimsFullname"]._ToString(); DListComplaintResultTypeFilter.SelectedValue = DictionarySession["ComplaintResultTypeID"]._ToString(); TxtResultsFilter.Text = DictionarySession["Results"]._ToString(); TxtCallDtStartFilter.Text = DictionarySession["StartCall_Dt"]._ToString(); TxtCallDtEndFilter.Text = DictionarySession["EndCall_Dt"]._ToString(); TxtStartPunishmentPeriodFilter.Text = DictionarySession["StartPunishmentPeriod"]._ToString(); TxtEndPunishmentPeriodFilter.Text = DictionarySession["EndPunishmentPeriod"]._ToString(); DListDatePriority.SelectedValue = DictionarySession["DatePriority"]._ToString(); DListPageSize.SelectedValue = DictionarySession["PageSize"]._ToString(); } } #region BetweenDateFromat string DatePunishmentPeriod = ""; string DatePunishmentPeriod1 = "19000101"; string DatePunishmentPeriod2 = DateTime.Now.ToString("yyyyMMdd"); object DtStartPunishmentPeriod = Config.DateTimeFormat(TxtStartPunishmentPeriodFilter.Text.Trim()); object DtEndPunishmentPeriod = Config.DateTimeFormat(TxtEndPunishmentPeriodFilter.Text.Trim()); if (DtStartPunishmentPeriod == null && DtEndPunishmentPeriod == null) { DatePunishmentPeriod = ""; } else { if (DtStartPunishmentPeriod != null) { DatePunishmentPeriod1 = ((DateTime)DtStartPunishmentPeriod).ToString("yyyyMMdd"); } if (DtEndPunishmentPeriod != null) { DatePunishmentPeriod2 = ((DateTime)DtEndPunishmentPeriod).ToString("yyyyMMdd"); } DatePunishmentPeriod = DatePunishmentPeriod1 + "&" + DatePunishmentPeriod2; } string Date = ""; string Dt1 = "19000101"; string Dt2 = DateTime.Now.ToString("yyyyMMdd"); object DateFilter1 = Config.DateTimeFormat(TxtCallDtStartFilter.Text.Trim()); object DateFilter2 = Config.DateTimeFormat(TxtCallDtEndFilter.Text.Trim()); if (DateFilter1 == null && DateFilter2 == null) { Date = ""; } else { if (DateFilter1 != null) { Dt1 = ((DateTime)DateFilter1).ToString("yyyyMMdd"); } if (DateFilter2 != null) { Dt2 = ((DateTime)DateFilter2).ToString("yyyyMMdd"); } Date = Dt1 + "&" + Dt2; } #endregion var Dictionary = new Dictionary <string, object>() { // {"CallCenterTypeID",int.Parse(DlistCallCenterTypeFilter.SelectedValue)}, { "ComplaintTypeID", int.Parse(DListComplaintTypeFilter.SelectedValue) }, { "(LIKE)ApplicantFullname", TxtApplicantFullnameFilter.Text }, { "GenderTypeID", int.Parse(DListApplicantGenderTypeFilter.SelectedValue) }, { "SocialStatusID", int.Parse(DListApplicantSocialStatusFilter.SelectedValue) }, { "PhoneNumber", TxtPhoneNumberFilter.Text }, { "VictimsFullname", TxtVictimsFullnameFilter.Text }, { "ComplaintResultTypeID", DListComplaintResultTypeFilter.SelectedValue }, { "(LIKE)Results", TxtResultsFilter.Text }, { "Call_Dt(BETWEEN)", Date }, { "StartPunishmentPeriod(BETWEEN)", DatePunishmentPeriod }, { "EndPunishmentPeriod(BETWEEN)", DatePunishmentPeriod } }; //Sira sayina gore filteri elave olaraq gonderirik int RowIndex = -1; if (!int.TryParse(TxtRowIndexFilter.Text, out RowIndex)) { RowIndex = -1; } int PageNum; int RowNumber = 30; if (DListPageSize.SelectedValue == "20") { RowNumber = 10000; } string OrderByType = "desc"; if (DListDatePriority.SelectedValue == "20") { OrderByType = "asc"; } if (!int.TryParse(Config._GetQueryString("p"), out PageNum)) { PageNum = 1; } // Axirinci sehifeni secmedikce Cache temizlemirik herdefe count almasin deye if (PageNum >= (Cache[_CountCacheName]._ToInt32() / RowNumber)) { Cache.Remove(_CountCacheName); } HdnPageNumber.Value = PageNum.ToString(); DALC.DataTableResult ApplicationsList = DALC.GetCallCenter(Dictionary, PageNum, RowNumber, new object[] { RowIndex }, OrderByType); if (ApplicationsList.Count == -1) { return; } if (ApplicationsList.Dt.Rows.Count < 1 && PageNum > 1) { Config.RedirectURL(string.Format("/tools/CallCenter/?p={0}", PageNum - 1)); } int Total_Count = ApplicationsList.Count % RowNumber > 0 ? (ApplicationsList.Count / RowNumber) + 1 : ApplicationsList.Count / RowNumber; HdnTotalCount.Value = Total_Count.ToString(); PnlPager.Visible = ApplicationsList.Count > RowNumber; GrdCallCenter.DataSource = ApplicationsList.Dt; GrdCallCenter.DataBind(); LblCountInfo.Text = string.Format("Axtarış üzrə nəticə: {0}", ApplicationsList.Count); }
/// <summary> /// Link the Http context cache to a crash repository. /// </summary> /// <param name="InCache">The current Http context cache.</param> /// <param name="InCrashRepository">The repository to associate the cache with.</param> public CachedDataService(Cache InCache, CrashRepository InCrashRepository) { CacheInstance = InCache; Crashes = InCrashRepository; }