コード例 #1
0
ファイル: SonicCache.cs プロジェクト: kaylynb/SonicMetro
        public SonicCache(Guid cacheId, SonicAPI.Query query)
        {
            ThrowIf.Null(query, "query");

            Query = query;
            CacheID = cacheId;

            CacheFolder = ApplicationData.Current.LocalFolder.CreateFolderAsync(
                string.Format(CultureInfo.InvariantCulture, "cache\\{0}", CacheID), CreationCollisionOption.OpenIfExists).AsTask().Result;

            var factory = new SonicApiDataSourceFactory(this);

            MusicFolders = factory.GenerateDefaultSonicApiDataSource<IEnumerable<MusicFolder>, SonicAPI.RESTSchema.MusicFolders>(
                x => Task.FromResult(x.musicFolder.Select(y => new MusicFolder(this, y.id.ToString(CultureInfo.InvariantCulture), y.name))),
                () => Task.FromResult(Query.GetMusicFoldersQuery()));

            Indexes = factory.GenerateDefaultSonicApiDataSource<IEnumerable<Index>, string, SonicAPI.RESTSchema.Indexes>(
                x => Task.FromResult(x.index.Select(index => new Index(this, index.name, index.artist.Select(a => a.id).ToList()))),
                x => Task.FromResult(Query.GetIndexesQuery(x)));

            MusicDirectory = factory.GenerateDefaultSonicApiDataSource<MusicDirectory, string, SonicAPI.RESTSchema.Directory>(
                x => Task.FromResult(new MusicDirectory(this, x.id, x.name, x.child)),
                x => Task.FromResult(Query.GetMusicDirectoryQuery(x)));

            CoverArt = new MemoryCache<BitmapImage, string>(
                new ConvertingDataSource<byte[], BitmapImage, string, string>(
                    x => x.ConvertToBitmapImageAsync(),
                    Task.FromResult,
                        new FileCache<byte[], string, ByteArrayFileConverter>(CacheFolder.CreateFolderAsync("coverArt", CreationCollisionOption.OpenIfExists).AsTask().Result,
                            new CoverArtDataSource(Query))));
        }
コード例 #2
0
 public void Constructor_SetEntryLifetime_Success()
 {
     TimeSpan entryLifetime = TimeSpan.FromMinutes(1);
     var cache = new MemoryCache<int, string>(entryLifetime);
     Assert.AreEqual(entryLifetime, cache.EntryLifetime);
     Assert.AreEqual(DefaultMaxSize, cache.MaxSize);
 }
コード例 #3
0
        public void Removes_an_object_from_the_cache_by_its_key()
        {
            ICache caching = new MemoryCache(mockLogger);
            bool removed = caching.Remove("firstItem");

            Assert.IsTrue(removed);
        }
コード例 #4
0
        public void Add_AddMoreThanAvailable_Success()
        {
            var cache = new MemoryCache<int, string>();
            for (int i = 0; i < DefaultMaxSize; ++i)
            {
                KeyValuePair<int, string>? removed;
                bool wasSaved = cache.Save(i, i.ToString(), out removed);
                Assert.IsTrue(wasSaved);
                Assert.IsNull(removed);
            }
            List<KeyValuePair<int, string>> values = cache.GetAll().ToList();
            Assert.AreEqual(DefaultMaxSize, values.Count);

            for (int i = 0; i < DefaultMaxSize; ++i)
            {
                KeyValuePair<int, string>? removed;
                bool wasAdded = cache.Save(i, i.ToString(), out removed);
                Assert.IsTrue(wasAdded);
                Assert.IsNotNull(removed);
                Assert.AreEqual(i, removed.Value.Key);
                Assert.AreEqual(i.ToString(), removed.Value.Value);
            }
            values = cache.GetAll().ToList();
            Assert.AreEqual(DefaultMaxSize, values.Count);
        }
コード例 #5
0
        public void TileFetcherShouldBehaveProperlyWithNoisyResponses()
        {
            // Arrange
            var schema = new GlobalSphericalMercator();
            var tileSource = new TileSource(new SometimesFailingTileProvider(), schema);
            var memoryCache = new MemoryCache<Feature>(14, 17);
            var tileFetcher = new TileFetcher(tileSource, memoryCache);
            var random = new Random(31747074);

            // Act
            for (int i = 0; i < 100; i++)
            {
                var randomLevel = "5";
                var randomCol = random.Next(schema.GetMatrixWidth(randomLevel));
                var randomRow = random.Next(schema.GetMatrixHeight(randomLevel));
                var tileRange = new TileRange(randomCol - 2, randomRow - 2, 5, 5);
                var unitsPerPixel = schema.Resolutions[randomLevel].UnitsPerPixel;
                var extent = TileTransform.TileToWorld(tileRange, randomLevel, schema);
                tileFetcher.ViewChanged(TileTransform.TileToWorld(tileRange, randomLevel, schema).ToBoundingBox(),unitsPerPixel );
                var tileInfos = schema.GetTileInfos(extent, randomLevel);
                foreach (var tileInfo in tileInfos)
                {
                    var tiles = memoryCache.Find(tileInfo.Index);

                }
            }

            // Assert
            Assert.True(memoryCache.TileCount == 0);
        }
コード例 #6
0
        public void CachedClientCachesResultsInMemoryCache()
        {
            // Arrange
            var uri = new Uri(@"http://nuget.org");
            var webResponse = new Mock<WebResponse>(MockBehavior.Strict);
            webResponse.Setup(s => s.ResponseUri).Returns(uri)
                                                 .Verifiable();
            var client = new Mock<HttpClient>(MockBehavior.Strict, uri);
            client.Setup(s => s.GetResponse()).Returns(webResponse.Object);
            var memoryCache = new MemoryCache();

            var redirectedClient1 = new Mock<RedirectedHttpClient>(uri, memoryCache) { CallBase = true };
            redirectedClient1.Setup(r => r.EnsureClient()).Returns(client.Object).Verifiable();

            var redirectedClient2 = new Mock<RedirectedHttpClient>(uri, memoryCache) { CallBase = true };

            
            // Act
            var result1 = redirectedClient1.Object.CachedClient;
            var result2 = redirectedClient2.Object.CachedClient;

            // Assert
            Assert.Same(result1, result2);
            redirectedClient1.Verify(r => r.EnsureClient(), Times.Once());
            redirectedClient2.Verify(r => r.EnsureClient(), Times.Never());
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: vagelious/ergotaxionion
        public static void Main(string[] args)
        {
            // Runs several concurrent threads that access an item that periodically expires and is re-created.
            MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            string key = "MyKey";

            var tasks = new List<Task>();
            for (int threads = 0; threads < 100; threads++)
            {
                var task = Task.Run(() =>
                {
                    for (int i = 0; i < 110000; i++)
                    {
                        cache.GetOrSet(key, context =>
                        {
                            context.SetAbsoluteExpiration(TimeSpan.FromMilliseconds(50));
                            // Fake expensive object creation.
                            for (int j = 0; j < 1000000; j++)
                            {
                            }
                            return new object();
                        });
                    }
                });
                tasks.Add(task);
            }

            Console.WriteLine("Running");
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("Done");
        }
コード例 #8
0
ファイル: CalculationEngine.cs プロジェクト: kityandhero/Jace
        /// <summary>
        /// Creates a new instance of the <see cref="CalculationEngine"/> class.
        /// </summary>
        /// <param name="cultureInfo">
        /// The <see cref="CultureInfo"/> required for correctly reading floating poin numbers.
        /// </param>
        /// <param name="executionMode">The execution mode that must be used for formula execution.</param>
        /// <param name="cacheEnabled">Enable or disable caching of mathematical formulas.</param>
        /// <param name="optimizerEnabled">Enable or disable optimizing of formulas.</param>
        public CalculationEngine(CultureInfo cultureInfo, ExecutionMode executionMode, bool cacheEnabled, bool optimizerEnabled)
        {
            this.executionFormulaCache = new MemoryCache<string, Func<Dictionary<string, double>, double>>();
            this.FunctionRegistry = new FunctionRegistry(false);
            this.ConstantRegistry = new ConstantRegistry(false);
            this.cultureInfo = cultureInfo;
            this.cacheEnabled = cacheEnabled;
            this.optimizerEnabled = optimizerEnabled;

            if (executionMode == ExecutionMode.Interpreted)
                executor = new Interpreter();
            else if (executionMode == ExecutionMode.Compiled)
                executor = new DynamicCompiler();
            else
                throw new ArgumentException(string.Format("Unsupported execution mode \"{0}\".", executionMode),
                    "executionMode");

            optimizer = new Optimizer(new Interpreter()); // We run the optimizer with the interpreter

            // Register the default constants of Jace.NET into the constant registry
            RegisterDefaultConstants();

            // Register the default functions of Jace.NET into the function registry
            RegisterDefaultFunctions();
        }
コード例 #9
0
        public void ClientIsNotCachedIfExceptionOccursWhen()
        {
            // Arrange
            var uri = new Uri(@"http://nuget.org");
            var webResponse = new Mock<WebResponse>(MockBehavior.Strict);
            webResponse.Setup(s => s.ResponseUri).Returns(uri)
                                                 .Verifiable();
            var client = new Mock<HttpClient>(MockBehavior.Strict, uri);
            client.Setup(s => s.GetResponse()).Returns(webResponse.Object);
            var memoryCache = new MemoryCache();

            var redirectedClient1 = new Mock<RedirectedHttpClient>(uri, memoryCache) { CallBase = true };
            redirectedClient1.Setup(r => r.EnsureClient()).Throws(new Exception("Na na na na na")).Verifiable();

            var redirectedClient2 = new Mock<RedirectedHttpClient>(uri, memoryCache) { CallBase = true };
            redirectedClient2.Setup(r => r.EnsureClient()).Returns(client.Object);

            // Act and Assert
            ExceptionAssert.Throws<Exception>(() => redirectedClient1.Object.CachedClient.ToString(), "Na na na na na");
            var result2 = redirectedClient2.Object.CachedClient;

            // Assert
            Assert.Same(client.Object, result2);
            redirectedClient1.Verify(r => r.EnsureClient(), Times.Once());
            redirectedClient2.Verify(r => r.EnsureClient(), Times.Once());
        }
コード例 #10
0
        public void Test002_NoEvictionCacheJustKeepsGrowing()
        {
            var noEvictionCache = new MemoryCache<int, int>();
            Assert.AreEqual(noEvictionCache.Capacity, AbstractCache.DefaultCapacity);

            noEvictionCache.Add(19, 19);
            noEvictionCache.Add(1, 1);
            noEvictionCache.Add(6, 6);
            noEvictionCache.Add(2, 2);
            noEvictionCache.Add(16, 16);
            noEvictionCache.Add(5, 5);
            noEvictionCache.Add(18, 18);
            noEvictionCache.Add(7, 7);
            noEvictionCache.Add(15, 15);
            noEvictionCache.Add(4, 4);
            noEvictionCache.Add(14, 14);
            noEvictionCache.Add(9, 9);
            noEvictionCache.Add(13, 13);
            noEvictionCache.Add(17, 17);
            noEvictionCache.Add(12, 12);
            noEvictionCache.Add(3, 3);
            Assert.AreEqual(noEvictionCache.Count, 16);

            noEvictionCache.Add(10, 10);
            noEvictionCache.Add(11, 11);
            noEvictionCache.Add(8, 8);
            Assert.AreEqual(noEvictionCache.Count, 19);

            var expectedArray = Enumerable.Range(1, 19).ToArray();
            var cacheArray = noEvictionCache.OrderBy(i => i).ToArray();
            Assert.AreEqual(expectedArray, cacheArray);
        }
コード例 #11
0
        private static void DrawRecursive(Graphics graphics, ITileSchema schema, IViewport viewport, 
            MemoryCache<Feature> cache, Extent extent, int level)
        {
            var tileInfos = schema.GetTilesInView(extent, level);

            foreach (TileInfo info in tileInfos)
            {
                var feature = cache.Find(info.Index);
                if (feature == null)
                {
                    if (level > 0) DrawRecursive(graphics, schema, viewport, cache, info.Extent.Intersect(extent), level - 1);
                }
                else
                {
                    var image = ((IRaster)feature.Geometry).Data;
                    RectangleF dest = WorldToView(info.Extent, viewport);
                    dest = RoundToPixel(dest);
                    RectangleF clip = WorldToView(extent, viewport);
                    clip = RoundToPixel(clip);

                    if (!Contains(clip, dest))
                    {
                        clip = Intersect(clip, dest);
                        if (clip.IsEmpty) continue;
                        DrawImage(graphics, new Bitmap(image), dest, clip);
                    }
                    else
                    {
                        //Not using a clip at all sometimes performs better than using screenwide clip.
                        DrawImage(graphics, new Bitmap(image), dest);
                    }
                }
            }
        }
コード例 #12
0
 public void Constructor_SetCacheMaxSize_Success()
 {
     const int maxSize = 1024;
     var cache = new MemoryCache<int, string>(maxSize);
     Assert.AreEqual(DefaultEntryLifetime, cache.EntryLifetime);
     Assert.AreEqual(maxSize, cache.MaxSize);
 }
コード例 #13
0
        private static void RenderTile(WriteableBitmap bitmap, ITileSchema schema, IViewport viewport, MemoryCache<Feature> memoryCache)
        {
            int level = BruTile.Utilities.GetNearestLevel(schema.Resolutions, viewport.Resolution);
            var tiles = schema.GetTilesInView(viewport.Extent.ToExtent(), level);

            foreach (TileInfo tile in tiles)
            {
                var p = NativeCache.Find(tile.Index);
                if (p != null)
                {
                    bitmap.Render(p, null);
                    continue;
                }

                var image = memoryCache.Find(tile.Index);

                if (image != null)
                {
                    Rect dest = WorldToView(tile.Extent, viewport);
                    dest = GeometryRenderer.RoundToPixel(dest);

                    //See here the clumsy way to write a bitmap in SL/WPF
                    var path = new System.Windows.Shapes.Path();
                    path.Data = new RectangleGeometry { Rect = dest };
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(((IRaster)image.Geometry).Data);
                    path.Fill = new ImageBrush { ImageSource = bitmapImage };
                    path.CacheMode = new BitmapCache();
                    bitmap.Render(path, null);
                }
            }
        }
コード例 #14
0
        public void Gets_the_object_from_the_cache()
        {
            ICache caching = new MemoryCache(mockLogger);

            MyClass mc = caching.Get<MyClass>("firstItem");

            Assert.IsNotNull(mc);
        }
コード例 #15
0
        public void CacheSet_Pass()
        {
            ICache cache = new MemoryCache();
            cache.Set("Item", "Value");
            var item = cache.Get<String>("Item");

            Assert.AreEqual(item, "Value");
        }
コード例 #16
0
        public void Test002_CannotSetThePolicyOfANonEmptyCache()
        {
            var nonEmptyCache = new MemoryCache<int, int>();
            nonEmptyCache.SetPolicy(typeof(NoEvictionPolicy<,>));

            nonEmptyCache.Add(1, 1);
            nonEmptyCache.Policy = null;
        }
コード例 #17
0
ファイル: Renderer.cs プロジェクト: x-cubed/JC2MapViewer
 public void Render(Canvas canvas, TileSchema schema, ITransform transform, MemoryCache<MemoryStream> cache, List<Marker> markerCache)
 {
     CollapseAll(canvas);
     int level = BruTile.Utilities.GetNearestLevel(schema.Resolutions, transform.Resolution);
     DrawRecursive(canvas, schema, transform, cache, transform.Extent, level);
     DrawMarkers(canvas, schema, transform, markerCache, transform.Extent, level);
     RemoveCollapsed(canvas);
 }
コード例 #18
0
        public void AddGenericTest()
        {
            var adapter = new MemoryCache();
            var value = new { Some = "string" };

            adapter.Add("asdf", value);

            adapter.Get<object>("asdf").Should().Be(value);
        }
コード例 #19
0
		public InMemoryPublicKeyCache(
			MemoryCache cache
		) {
			if( cache == null ) {
				throw new ArgumentNullException( "cache" );
			}

			m_cache = cache;
		}
コード例 #20
0
 public ApplicationPage()
 {
     this.navigationHelper = new NavigationHelper(this);
     this.navigationHelper.LoadState += this.NavigationHelper_LoadState; //Done
     this.navigationHelper.SaveState += this.NavigationHelper_SaveState; //Done
     this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Disabled;
     Cache = new MemoryCache();
     TitleTemplateSelector = new TitleOnlyTitleBarTemplateSelector();
 }
コード例 #21
0
        public void Adding_an_object_to_the_cache_by_key()
        {
            ICache caching = new MemoryCache(mockLogger);

            var mc = new MyClass();
            bool added = caching.Add("firstItem", mc);

            Assert.IsTrue(added);
        }
コード例 #22
0
        public void Adding_an_object_with_an_sliding_expiration_date()
        {
            ICache caching = new MemoryCache(mockLogger);

            var mc = new MyClass();

            bool added = caching.AddAndKeepWhileUsed("thirdItem", mc, new TimeSpan(0, 2, 0));

            Assert.IsTrue(added);
        }
コード例 #23
0
        public void Adding_an_object_with_an_absolute_expiration_date()
        {
            ICache caching = new MemoryCache(mockLogger);

            var mc = new MyClass();

            bool added = caching.AddAndKeepFor("secondItem", mc, new TimeSpan(0, 2, 0));

            Assert.IsTrue(added);
        }
コード例 #24
0
        public void TestCacheCleanupBiggerThanCacheSize()
        {
            MemoryCache<string, int> cache = new MemoryCache<string, int>(1, 3);
            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);

            Assert.IsTrue(cache.ContainsKey("test3"));
            Assert.AreEqual(1, cache.Count);
        }
コード例 #25
0
        public TileFetcher(ITileSource tileSource, MemoryCache<Feature> memoryCache, int maxRetries = 2)
        {
            if (tileSource == null) throw new ArgumentException("TileProvider can not be null");
            this.tileSource = tileSource;

            if (memoryCache == null) throw new ArgumentException("MemoryCache can not be null");
            this.memoryCache = memoryCache;

            this.maxRetries = maxRetries;
        }
コード例 #26
0
        public void TestCacheCleanupOnlyAdd()
        {
            MemoryCache<string, int> cache = new MemoryCache<string, int>(3, 1);
            cache.GetOrAdd("test1", k => 1);
            cache.GetOrAdd("test2", k => 2);
            cache.GetOrAdd("test3", k => 3);
            cache.GetOrAdd("test4", k => 3);

            Assert.IsFalse(cache.ContainsKey("test1"));
            Assert.AreEqual(3, cache.Count);
        }
コード例 #27
0
		public MemoryCacheContainer (MemoryCache owner, int id, MemoryCachePerformanceCounters perfCounters)
		{
			if (owner == null)
				throw new ArgumentNullException ("owner");
			
			this.owner = owner;
			this.ID = id;
			this.perfCounters = perfCounters;
			cache = new SortedDictionary <string, MemoryCacheEntry> ();
			lru = new MemoryCacheLRU (this, DEFAULT_LRU_LOWER_BOUND);
		}
コード例 #28
0
ファイル: TileFetcher.cs プロジェクト: jdeksup/Mapsui.Net4
 public TileFetcher(ITileSource tileSource, MemoryCache<Feature> memoryCache, int maxAttempts = DefaultMaxAttempts, int maxThreads = DefaultMaxThreads, IFetchStrategy strategy = null)
 {
     if (tileSource == null) throw new ArgumentException("TileProvider can not be null");
     if (memoryCache == null) throw new ArgumentException("MemoryCache can not be null");
     
     _tileSource = tileSource;
     _memoryCache = memoryCache;
     _maxAttempts = maxAttempts;
     _maxThreads = maxThreads;
     _strategy = strategy ?? new FetchStrategy();
 }
コード例 #29
0
            public void LoadFromUnderlyingStoreIfNotCached()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                decoratedAggregateStore.Setup(mock => mock.Get(typeof(FakeAggregate), aggregate.Id)).Returns(aggregate);

                cachedAggregateStore.Get(typeof(FakeAggregate), aggregate.Id);

                decoratedAggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), aggregate.Id), Times.Once());
            }
コード例 #30
0
            public void UseCachedAggregateIfAvailable()
            {
                var aggregate = new FakeAggregate();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var memoryCache = new MemoryCache(Guid.NewGuid().ToString());
                var cachedAggregateStore = new CachedAggregateStore(decoratedAggregateStore.Object, TimeSpan.FromMinutes(1), memoryCache);

                memoryCache.Add(aggregate.CacheKey, aggregate, new CacheItemPolicy());

                Assert.Same(aggregate, cachedAggregateStore.Get(typeof(FakeAggregate), aggregate.Id));

                decoratedAggregateStore.Verify(mock => mock.Get(typeof(FakeAggregate), aggregate.Id), Times.Never());
            }
コード例 #31
0
        public void RegisterServices(IServiceCollection services, IConfiguration configuration)
        {
            var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

            services.AddSingleton <IMemoryCache>(memoryCache);
            services.Configure <AzureAdConfiguration>(options =>
            {
                configuration.GetSection("AzureAd").Bind(options);
            });
            services.Configure <ServicesConfiguration>(options =>
            {
                configuration.GetSection("VhServices").Bind(options);
            });

            var serviceConfiguration = new ServicesConfiguration();

            configuration.GetSection("VhServices").Bind(serviceConfiguration);

            services.AddScoped <IAzureTokenProvider, AzureTokenProvider>();

            services.AddLogging(builder =>
                                builder.AddApplicationInsights(configuration["ApplicationInsights:InstrumentationKey"])
                                );

            services.AddScoped <ICloseConferenceService, CloseConferenceService>();
            services.AddScoped <IClearConferenceChatHistoryService, ClearConferenceChatHistoryService>();
            services.AddScoped <IAnonymiseHearingsConferencesDataService, AnonymiseHearingsConferencesDataService>();
            services.AddScoped <IRemoveHeartbeatsForConferencesService, RemoveHeartbeatsForConferencesService>();
            services.AddScoped <IELinksService, ELinksService>();

            services.AddTransient <VideoServiceTokenHandler>();
            services.AddTransient <BookingsServiceTokenHandler>();
            services.AddTransient <UserServiceTokenHandler>();
            services.AddTransient <ELinksApiDelegatingHandler>();

            services.AddHttpClient <IVideoApiClient, VideoApiClient>()
            .AddHttpMessageHandler <VideoServiceTokenHandler>()
            .AddTypedClient(httpClient =>
            {
                var client     = VideoApiClient.GetClient(httpClient);
                client.BaseUrl = serviceConfiguration.VideoApiUrl;
                client.ReadResponseAsString = true;
                return((IVideoApiClient)client);
            });

            services.AddHttpClient <IBookingsApiClient, BookingsApiClient>()
            .AddHttpMessageHandler <BookingsServiceTokenHandler>()
            .AddTypedClient(httpClient =>
            {
                var client     = BookingsApiClient.GetClient(httpClient);
                client.BaseUrl = serviceConfiguration.BookingsApiUrl;
                client.ReadResponseAsString = true;
                return((IBookingsApiClient)client);
            });

            services.AddHttpClient <IUserApiClient, UserApiClient>()
            .AddHttpMessageHandler <UserServiceTokenHandler>()
            .AddTypedClient(httpClient =>
            {
                var client     = UserApiClient.GetClient(httpClient);
                client.BaseUrl = serviceConfiguration.UserApiUrl;
                client.ReadResponseAsString = true;
                return((IUserApiClient)client);
            });

            services.AddHttpClient <IELinksApiClient, ELinksApiClient>()
            .AddHttpMessageHandler <ELinksApiDelegatingHandler>()
            .AddTypedClient(httpClient =>
            {
                var eLinksApiClient = new ELinksApiClient(httpClient)
                {
                    BaseUrl = serviceConfiguration.ELinksApiUrl
                };
                return((IELinksApiClient)eLinksApiClient);
            });
        }
コード例 #32
0
        /// <summary>
        /// Runs a PowerShell script with parameters and prints the resulting pipeline objects to the console output.
        /// </summary>
        /// <param name="scriptId">The script file contents.</param>
        /// <param name="scriptParameters">A dictionary of parameter names and parameter values.</param>
        /// <param name="outputHandler">The outputHandler to send the script output to.</param>
        private async Task StreamPowerShell(string scriptId, Dictionary <string, object> scriptParameters, Action <object> outputHandler)
        {
            string cacheKey = $"{Context.ConnectionId}|CancellationTokenSource";

            try
            {
                var script = ScriptService.GetScript(scriptId);

                outputHandler(new OutputRecord(OutputLevelName.System, "Loading script..."));
                Logger.Log(LogLevel.Information, $"{Context.User.Identity.Name} attempting to run {script.Name}");

                string scriptContents = script.GetContents();

                // Setup a custom runspace pool if configured on the script
                if (script.Runspace != null)
                {
                    InitializeRunspaces(script.Runspace);
                }

                // create a new hosted PowerShell instance potentially with a custom runspace.
                // wrap in a using statement to ensure resources are cleaned up.
                using (PowerShell ps = PowerShell.Create())
                {
                    // use the runspace pool, if it was created.
                    if (RsPool != null)
                    {
                        ps.RunspacePool = RsPool;
                    }

                    // specify the script code to run.
                    ps.AddScript(scriptContents);

                    // specify the parameters to pass into the script.
                    ps.AddParameters(scriptParameters);

                    // Subscribe to events from output
                    var output = new PSDataCollection <PSObject>();
                    output.DataAdded += (object sender, DataAddedEventArgs e) => WriteOutput <PSObject>(sender, e, outputHandler);

                    // subscribe to events from some of the streams

                    /// Handles data-added events for the error stream.
                    /// Note: Uncaught terminating errors will stop the pipeline completely.
                    /// Non-terminating errors will be written to this stream and execution will continue.
                    ps.Streams.Error.DataAdded   += (object sender, DataAddedEventArgs e) => WriteOutput <ErrorRecord>(sender, e, outputHandler);
                    ps.Streams.Warning.DataAdded += (object sender, DataAddedEventArgs e) => WriteOutput <WarningRecord>(sender, e, outputHandler);
                    /// Handles data-added events for the information stream.
                    /// Note: Write-Host and Write-Information messages will end up in the information stream.
                    ps.Streams.Information.DataAdded += (object sender, DataAddedEventArgs e) => WriteOutput <InformationRecord>(sender, e, outputHandler);
                    ps.Streams.Progress.DataAdded    += (object sender, DataAddedEventArgs e) => WriteOutput <ProgressRecord>(sender, e, outputHandler);
                    ps.Streams.Verbose.DataAdded     += (object sender, DataAddedEventArgs e) => WriteOutput <VerboseRecord>(sender, e, outputHandler);
                    ps.Streams.Debug.DataAdded       += (object sender, DataAddedEventArgs e) => WriteOutput <DebugRecord>(sender, e, outputHandler);

                    outputHandler(new OutputRecord(OutputLevelName.System, "Beginning script execution..."));

                    // setup our cancellation token for possible use later to cancel
                    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                    // We basically want to cache the cancellationTokenSource until the script finishes (or is canceled)
                    var cacheExpiryOptions = new MemoryCacheEntryOptions
                    {
                        AbsoluteExpiration = DateTime.Now.AddDays(1),
                        Priority           = CacheItemPriority.High
                    };
                    MemoryCache.Set(cacheKey, cancellationTokenSource, cacheExpiryOptions);

                    // NOTE: the 'await' call is gone here so we can access the task object.
                    Task <PSDataCollection <PSObject> > asyncTask = ps.InvokeAsync();
                    asyncTask.Wait(cancellationTokenSource.Token); // Wait on the task until natural completion OR cancel token fires.
                    output = asyncTask.Result;                     // this object should contain the original PSObject results (pipeline output).
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Error, ex, ex.Message);
                outputHandler(new OutputRecord(OutputLevelName.Error, ex.Message));
            }
            finally
            {
                outputHandler(new OutputRecord(OutputLevelName.System, "Script execution ended."));
                MemoryCache.Remove(cacheKey);
            }
        }
コード例 #33
0
        public static object GetValue(string key)
        {
            MemoryCache memoryCache = Default;

            return(memoryCache.Get(key));
        }
コード例 #34
0
ファイル: UserCache.cs プロジェクト: IPleshivtsev/PW
 /// <summary>
 /// Инициализация сервиса кэша пользователей.
 /// </summary>
 public UserCache()
 {
     memoryCache = MemoryCache.Default;
 }
コード例 #35
0
        public static void Delete(string key)
        {
            MemoryCache memoryCache = Default;

            memoryCache.Remove(key);
        }
コード例 #36
0
ファイル: Startup.cs プロジェクト: wafdwafdba/Blog.Core
        // This method gets called by the runtime. Use this method to add services to the container.
        /// <summary>
        /// ConfigureServices 方法
        /// </summary>
        /// <param name="services"></param>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //将 TService 中指定的类型的范围服务添加到实现
            services.AddScoped <ICaching, MemoryCaching>();//记得把缓存注入!!!

            #region 配置信息
            //Blog.Core.Repository.BaseDBConfig.ConnectionString = Configuration.GetSection("AppSettings:SqlServerConnection").Value;
            #endregion

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v0.1.0",
                    Title          = "Blog.Core API",
                    Description    = "框架说明文档",
                    TermsOfService = "None",
                    Contact        = new Swashbuckle.AspNetCore.Swagger.Contact {
                        Name = "Blog.Core", Email = "*****@*****.**", Url = "https://www.jianshu.com/u/94102b59cc2a"
                    }
                });

                //就是这里

                #region 读取xml信息
                var basePath     = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath      = Path.Combine(basePath, "Blog.Core.xml");       //这个就是刚刚配置的xml文件名
                var xmlModelPath = Path.Combine(basePath, "Blog.Core.Model.xml"); //这个就是Model层的xml文件名
                c.IncludeXmlComments(xmlPath, true);                              //默认的第二个参数是false,这个是controller的注释,记得修改
                c.IncludeXmlComments(xmlModelPath);
                #endregion

                #region Token绑定到ConfigureServices
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Blog.Core", new string[] { } },
                };
                c.AddSecurityRequirement(security);
                //方案名称“Blog.Core”可自定义,上下一致即可
                c.AddSecurityDefinition("Blog.Core", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入{token}\"",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
                #endregion
            });
            #endregion

            #region Token服务注册
            services.AddSingleton <IMemoryCache>(factory =>
            {
                var cache = new MemoryCache(new MemoryCacheOptions());
                return(cache);
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Admin", policy => policy.RequireClaim("AdminType").Build());//注册权限管理,可以自定义多个
            });
            #endregion

            #region AutoFac
            //实例化 AutoFac  容器
            var builder = new ContainerBuilder();
            //注册要通过反射创建的组件
            //builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
            builder.RegisterType <BlogCacheAOP>();//可以直接替换其他拦截器
            var assemblysServices = Assembly.Load("Blog.Core.Services");
            //builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces();//指定已扫描程序集中的类型注册为提供所有其实现的接口。

            builder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope()
            .EnableInterfaceInterceptors()          //引用Autofac.Extras.DynamicProxy;
            .InterceptedBy(typeof(BlogCacheAOP));   //允许将拦截器服务的列表分配给注册。可以直接替换其他拦截器

            var assemblysRepository = Assembly.Load("Blog.Core.Repository");
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();

            //将services填充到Autofac容器生成器中
            builder.Populate(services);

            //使用已进行的组件登记创建新容器
            var ApplicationContainer = builder.Build();

            #endregion

            return(new AutofacServiceProvider(ApplicationContainer));//第三方IOC接管 core内置DI容器
        }
コード例 #37
0
ファイル: RazorViewEngine.cs プロジェクト: billrob/aspnetcore
 internal void ClearCache()
 {
     ViewLookupCache = new MemoryCache(new MemoryCacheOptions());
 }
コード例 #38
0
ファイル: MemoryCacheStorage.cs プロジェクト: justinvp/dotnet
 /// <summary>
 /// Creates a memory cache provider, storing each result in a MemoryCache for the specified duration.
 /// </summary>
 /// <param name="cacheDuration">The duration to cache each profiler, before it expires from cache.</param>
 public MemoryCacheStorage(TimeSpan cacheDuration)
 {
     _cache        = new MemoryCache("MiniProfilerCache");
     CacheDuration = cacheDuration;
 }
        public async Task ABP_New_Loaded_Device_With_Fcnt_1_Or_0_Should_Reset_Fcnt_And_Send_To_IotHub(
            string twinGatewayID,
            uint payloadFcntUp,
            uint?deviceTwinFcntUp,
            uint?deviceTwinFcntDown)
        {
            var simulatedDevice = new SimulatedDevice(TestDeviceInfo.CreateABPDevice(1, gatewayID: null));

            var devEUI  = simulatedDevice.LoRaDevice.DeviceID;
            var devAddr = simulatedDevice.LoRaDevice.DevAddr;

            // message will be sent
            LoRaDeviceTelemetry loRaDeviceTelemetry = null;

            this.LoRaDeviceClient.Setup(x => x.SendEventAsync(It.IsNotNull <LoRaDeviceTelemetry>(), null))
            .Callback <LoRaDeviceTelemetry, Dictionary <string, string> >((t, _) => loRaDeviceTelemetry = t)
            .ReturnsAsync(true);

            // C2D message will be checked
            this.LoRaDeviceClient.Setup(x => x.ReceiveAsync(It.IsNotNull <TimeSpan>()))
            .ReturnsAsync((Message)null);

            // twin will be loaded
            var initialTwin = new Twin();

            initialTwin.Properties.Desired[TwinProperty.DevEUI]  = devEUI;
            initialTwin.Properties.Desired[TwinProperty.AppEUI]  = simulatedDevice.LoRaDevice.AppEUI;
            initialTwin.Properties.Desired[TwinProperty.AppKey]  = simulatedDevice.LoRaDevice.AppKey;
            initialTwin.Properties.Desired[TwinProperty.NwkSKey] = simulatedDevice.LoRaDevice.NwkSKey;
            initialTwin.Properties.Desired[TwinProperty.AppSKey] = simulatedDevice.LoRaDevice.AppSKey;
            initialTwin.Properties.Desired[TwinProperty.DevAddr] = devAddr;
            if (twinGatewayID != null)
            {
                initialTwin.Properties.Desired[TwinProperty.GatewayID] = twinGatewayID;
            }
            initialTwin.Properties.Desired[TwinProperty.SensorDecoder] = simulatedDevice.LoRaDevice.SensorDecoder;
            if (deviceTwinFcntDown.HasValue)
            {
                initialTwin.Properties.Reported[TwinProperty.FCntDown] = deviceTwinFcntDown.Value;
            }
            if (deviceTwinFcntUp.HasValue)
            {
                initialTwin.Properties.Reported[TwinProperty.FCntUp] = deviceTwinFcntUp.Value;
            }

            this.LoRaDeviceClient.Setup(x => x.GetTwinAsync()).ReturnsAsync(initialTwin);

            // twin will be updated with new fcnt
            int?fcntUpSavedInTwin   = null;
            int?fcntDownSavedInTwin = null;

            var shouldSaveTwin = (deviceTwinFcntDown ?? 0) != 0 || (deviceTwinFcntUp ?? 0) != 0;

            if (shouldSaveTwin)
            {
                this.LoRaDeviceClient.Setup(x => x.UpdateReportedPropertiesAsync(It.IsNotNull <TwinCollection>()))
                .Callback <TwinCollection>((t) =>
                {
                    fcntUpSavedInTwin   = (int)t[TwinProperty.FCntUp];
                    fcntDownSavedInTwin = (int)t[TwinProperty.FCntDown];
                })
                .ReturnsAsync(true);
            }

            // multi gateway will reset the fcnt
            if (shouldSaveTwin)
            {
                this.LoRaDeviceApi.Setup(x => x.ABPFcntCacheResetAsync(devEUI))
                .ReturnsAsync(true);
            }

            // device api will be searched for payload
            this.LoRaDeviceApi.Setup(x => x.SearchByDevAddrAsync(devAddr))
            .ReturnsAsync(new SearchDevicesResult(new IoTHubDeviceInfo(devAddr, devEUI, "abc").AsList()));

            var memoryCache    = new MemoryCache(new MemoryCacheOptions());
            var deviceRegistry = new LoRaDeviceRegistry(this.ServerConfiguration, memoryCache, this.LoRaDeviceApi.Object, this.LoRaDeviceFactory);

            // Send to message processor
            var messageDispatcher = new MessageDispatcher(
                this.ServerConfiguration,
                deviceRegistry,
                this.FrameCounterUpdateStrategyProvider);

            // sends unconfirmed message
            var unconfirmedMessagePayload = simulatedDevice.CreateUnconfirmedDataUpMessage("hello", fcnt: payloadFcntUp);
            var rxpk    = unconfirmedMessagePayload.SerializeUplink(simulatedDevice.AppSKey, simulatedDevice.NwkSKey).Rxpk[0];
            var request = this.CreateWaitableRequest(rxpk);

            messageDispatcher.DispatchRequest(request);
            Assert.True(await request.WaitCompleteAsync());
            Assert.Null(request.ResponseDownlink);

            // Ensure that a telemetry was sent
            Assert.NotNull(loRaDeviceTelemetry);

            // Ensure that the device twins were saved
            if (shouldSaveTwin)
            {
                Assert.NotNull(fcntDownSavedInTwin);
                Assert.NotNull(fcntUpSavedInTwin);
                Assert.Equal(0, fcntDownSavedInTwin.Value);
                Assert.Equal(0, fcntUpSavedInTwin.Value);
            }

            // verify that the device in device registry has correct properties and frame counters
            var devicesForDevAddr = deviceRegistry.InternalGetCachedDevicesForDevAddr(devAddr);

            Assert.Single(devicesForDevAddr);
            Assert.True(devicesForDevAddr.TryGetValue(devEUI, out var loRaDevice));
            Assert.Equal(devAddr, loRaDevice.DevAddr);
            Assert.Equal(devEUI, loRaDevice.DevEUI);
            Assert.True(loRaDevice.IsABP);
            Assert.Equal(payloadFcntUp, loRaDevice.FCntUp);
            Assert.Equal(0U, loRaDevice.FCntDown);
            if (payloadFcntUp == 0)
            {
                Assert.False(loRaDevice.HasFrameCountChanges); // no changes
            }
            else
            {
                Assert.True(loRaDevice.HasFrameCountChanges); // should have changes!
            }
            this.LoRaDeviceClient.VerifyAll();
            this.LoRaDeviceApi.VerifyAll();
        }
コード例 #40
0
 public MemoryCacheTest()
 {
     _cache = MemoryCache.Default;
 }
コード例 #41
0
    /// <summary>A MemoryCache extension method that adds an or get existing.</summary>
    /// <typeparam name="TValue">Type of the value.</typeparam>
    /// <param name="cache">The cache to act on.</param>
    /// <param name="key">The key.</param>
    /// <param name="value">The value.</param>
    /// <returns>A TValue.</returns>
    public static TValue AddOrGetExisting <TValue>(this MemoryCache cache, string key, TValue value)
    {
        object item = cache.AddOrGetExisting(key, value, new CacheItemPolicy()) ?? value;

        return((TValue)item);
    }
コード例 #42
0
 public void Dispose()
 {
     MemoryCache.Dispose();
     SqlCache.Dispose();
 }
コード例 #43
0
        public EventEnricherTests()
        {
            var cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

            sut = new EventEnricher(cache, userResolver);
        }
コード例 #44
0
        protected virtual async Task ShowPlaceholder(string path, string key, ImageSource source, bool isLoadingPlaceholder)
        {
            if (Parameters.Preload)
            {
                return;
            }

            if (!await TryLoadFromMemoryCacheAsync(key, false, false, isLoadingPlaceholder).ConfigureAwait(false))
            {
                try
                {
                    var customResolver = isLoadingPlaceholder ? Parameters.CustomLoadingPlaceholderDataResolver : Parameters.CustomErrorPlaceholderDataResolver;
                    var loadResolver   = customResolver ?? DataResolverFactory.GetResolver(path, source, Parameters, Configuration);
                    loadResolver = new WrappedDataResolver(loadResolver);
                    DataResolverResult loadImageData;
                    TImageContainer    loadImage;

                    if (!await _placeholdersResolveLock.WaitAsync(TimeSpan.FromSeconds(10), CancellationTokenSource.Token).ConfigureAwait(false))
                    {
                        return;
                    }

                    try
                    {
                        ThrowIfCancellationRequested();

                        if (await TryLoadFromMemoryCacheAsync(key, false, false, isLoadingPlaceholder).ConfigureAwait(false))
                        {
                            if (isLoadingPlaceholder)
                            {
                                _isLoadingPlaceholderLoaded = true;
                                Parameters.OnLoadingPlaceholderSet?.Invoke();
                            }

                            return;
                        }

                        ThrowIfCancellationRequested();
                        loadImageData = await loadResolver.Resolve(path, Parameters, CancellationTokenSource.Token).ConfigureAwait(false);

                        ThrowIfCancellationRequested();

                        if (loadImageData.Stream != null)
                        {
                            using (loadImageData.Stream)
                            {
                                loadImage = await GenerateImageAsync(path, source, loadImageData.Stream, loadImageData.ImageInformation, TransformPlaceholders, true).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            loadImage = loadImageData.ImageContainer as TImageContainer;
                        }

                        if (loadImage != default(TImageContainer))
                        {
                            MemoryCache.Add(key, loadImageData.ImageInformation, loadImage);
                        }
                    }
                    finally
                    {
                        _placeholdersResolveLock.Release();
                    }

                    ThrowIfCancellationRequested();

                    if (isLoadingPlaceholder)
                    {
                        PlaceholderWeakReference = new WeakReference <TImageContainer>(loadImage);
                    }

                    if (Target != null)
                    {
                        await SetTargetAsync(loadImage, false).ConfigureAwait(false);
                    }

                    if (isLoadingPlaceholder)
                    {
                        _isLoadingPlaceholderLoaded = true;
                        Parameters.OnLoadingPlaceholderSet?.Invoke();
                    }
                }
                catch (Exception ex)
                {
                    if (ex is OperationCanceledException)
                    {
                        throw;
                    }

                    Logger.Error("Setting placeholder failed", ex);
                }
            }
            else if (isLoadingPlaceholder)
            {
                _isLoadingPlaceholderLoaded = true;
                Parameters.OnLoadingPlaceholderSet?.Invoke();
            }
        }
コード例 #45
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            #region 添加SQL数据库连接

            var sqlConnection = Configuration.GetConnectionString("SqlServerConnection");
            Console.WriteLine(sqlConnection);
            services.AddDbContext <UserDbContext>(option => option.UseSqlServer(sqlConnection));
            #endregion

            #region 添加Swagger配置
            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc("sparktodo", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "SparkTodo API",
                    Description = "API for SparkTodo",
                    Contact     = new OpenApiContact()
                    {
                        Name = "WeihanLi", Email = "*****@*****.**"
                    }
                });

                // include document file
                option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true);


                #region Token绑定到ConfigureServices


                // 开启加权小锁
                option.OperationFilter <AddResponseHeadersFilter>();
                option.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token,传递到后台
                option.OperationFilter <SecurityRequirementsOperationFilter>();

                // Jwt Bearer 认证,必须是 oauth2
                option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
                    Name        = "Authorization",          //jwt默认的参数名称
                    In          = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = SecuritySchemeType.ApiKey
                });
                #endregion
            });
            #endregion

            #region 注册Mapper服务
            services.AddAutoMapper(typeof(ServiceProfiles));
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                //一般采用这种方法
                c.AddPolicy("LimitRequests", policy =>
                {
                    policy
                    .WithOrigins("http://localhost:8080")
                    .AllowAnyHeader()//Ensures that the policy allows any header.
                    .AllowAnyMethod()
                    .AllowCredentials();
                });
            });
            #endregion

            #region MVC + GlobalExceptions

            //注入全局异常捕获
            services.AddControllers(o =>
            {
                // 全局异常过滤
                o.Filters.Add(typeof(GlobalExceptionsFilter));
                // 全局路由权限公约
                o.Conventions.Insert(0, new GlobalRouteAuthorizeConvention());
                // 全局路由前缀,统一修改路由
                //  o.Conventions.Insert(0, new GlobalRoutePrefixFilter(new RouteAttribute(RoutePrefix.Name)));
            })
            //全局配置Json序列化处理
            .AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            });

            #endregion

            #region 部分服务注入-netcore自带方法
            // 缓存注入
            services.AddScoped <ICaching, MemoryCaching>();
            services.AddSingleton <IMemoryCache>(factory =>
            {
                var cache = new MemoryCache(new MemoryCacheOptions());
                return(cache);
            });
            // log日志注入
            services.AddSingleton <ILoggerHelper, LogHelper>();
            #endregion

            #region Authorize 权限认证三步走
            #region 参数
            //读取配置文件
            var audienceConfig       = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var keyByteArray         = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey           = new SymmetricSecurityKey(keyByteArray);

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            //如果要数据库动态绑定,这里先留个空,后边处理器里动态赋值
            var permission = new List <PermissionItem>();

            //角色与接口的权限要求参数
            var permissionRequirement = new PermissionRequirement(
                "/api/denied",                            // 拒绝授权的跳转地址(目前无用)
                permission,
                ClaimTypes.Role,                          //基于角色的授权
                audienceConfig["Issuer"],                 //发行人
                audienceConfig["Audience"],               //听众
                signingCredentials,                       //签名凭据
                expiration: TimeSpan.FromSeconds(60 * 60) //接口的过期时间
                );
            #endregion
            Console.WriteLine("权限第一步:参数");
            #region 授权
            //【授权】
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Permissions.Name,
                                  policy => policy.Requirements.Add(permissionRequirement));
            });
            #endregion
            Console.WriteLine("权限第二步:授权");
            #region 认证
            // 令牌验证参数
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer           = audienceConfig["Issuer"],   //发行人
                ValidateAudience      = true,
                ValidAudience         = audienceConfig["Audience"], //订阅人
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.FromSeconds(30),
                RequireExpirationTime = true,
            };
            services.AddAuthentication("Bearer")
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            })
            .AddScheme <AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);
            #endregion
            Console.WriteLine("权限第三步:认证");
            #endregion
        }
コード例 #46
0
ファイル: CacheService.cs プロジェクト: Jarris752/portfolio
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheService"/> class using the default <see cref="MemoryCache"/>.
 /// </summary>
 public CacheService()
 {
     this.memoryCache = MemoryCache.Default;
 }
コード例 #47
0
        public async virtual Task <bool> TryLoadFromMemoryCacheAsync()
        {
            try
            {
                if (Parameters.Preload && Parameters.CacheType.HasValue &&
                    (Parameters.CacheType.Value == CacheType.Disk || Parameters.CacheType.Value == CacheType.None))
                {
                    return(false);
                }

                ThrowIfCancellationRequested();

                bool isFadeAnimationEnabledForCached = Parameters.FadeAnimationForCachedImagesEnabled.HasValue ? Parameters.FadeAnimationForCachedImagesEnabled.Value : Configuration.FadeAnimationForCachedImages;
                var  result = await TryLoadFromMemoryCacheAsync(Key, true, isFadeAnimationEnabledForCached, false).ConfigureAwait(false);

                if (result)
                {
                    Logger.Debug(string.Format("Image loaded from cache: {0}", Key));
                    IsCompleted = true;

                    if (Configuration.ExecuteCallbacksOnUIThread && (Parameters?.OnSuccess != null || Parameters?.OnFinish != null))
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            Parameters?.OnSuccess?.Invoke(ImageInformation, LoadingResult.MemoryCache);
                            Parameters?.OnFinish?.Invoke(this);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        Parameters?.OnSuccess?.Invoke(ImageInformation, LoadingResult.MemoryCache);
                        Parameters?.OnFinish?.Invoke(this);
                    }
                }
                else
                {
                    ThrowIfCancellationRequested();
                    // Loading placeholder if enabled
                    if (!_isLoadingPlaceholderLoaded && !string.IsNullOrWhiteSpace(Parameters.LoadingPlaceholderPath))
                    {
                        await ShowPlaceholder(Parameters.LoadingPlaceholderPath, KeyForLoadingPlaceholder,
                                              Parameters.LoadingPlaceholderSource, true).ConfigureAwait(false);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                if (Configuration.ClearMemoryCacheOnOutOfMemory && ex is OutOfMemoryException)
                {
                    MemoryCache.Clear();
                }

                if (ex is OperationCanceledException)
                {
                    if (Configuration.VerboseLoadingCancelledLogging)
                    {
                        Logger.Debug(string.Format("Image loading cancelled: {0}", Key));
                    }
                }
                else
                {
                    Logger.Error(string.Format("Image loading failed: {0}", Key), ex);

                    if (Configuration.ExecuteCallbacksOnUIThread && Parameters?.OnError != null)
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            Parameters?.OnError?.Invoke(ex);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        Parameters?.OnError?.Invoke(ex);
                    }
                }
            }

            return(false);
        }
コード例 #48
0
ファイル: AppCache.cs プロジェクト: Dastus/KuPro
        public object GetValue(string name)
        {
            MemoryCache memoryCache = MemoryCache.Default;

            return(memoryCache.Get(name));
        }
コード例 #49
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "V1.0",
                    Title       = "ExampleDemo.Api",
                    Description = "实例演示"
                });

                //读取注释
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "ExampleDemo.Core.xml");
                c.IncludeXmlComments(xmlPath, true);

                //添加header验证信息
                //var security = new Dictionary<string, IEnumerable<string>> { { "liang", new string[] { } }, };
                ////添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是liang
                //c.AddSecurityRequirement(security);

                //c.AddSecurityDefinition("liang", new OpenApiSecurityScheme {
                //    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: liang {token}\"",
                //    Name = "Authorization",//jwt默认的参数名称
                //    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                //    Type =SecuritySchemeType.ApiKey,
                //    BearerFormat="JWT",
                //    Scheme="liang"
                //});
                //c.AddSecurityRequirement(new OpenApiSecurityRequirement
                //{
                //    {
                //        new OpenApiSecurityScheme{
                //           Reference=new OpenApiReference {
                //           Type=ReferenceType.SecurityScheme,
                //           Id="liang" }},new string[]{ }
                //    }
                //});
            });

            #endregion

            #region MemoryCache
            services.AddSingleton <IMemoryCache>(factory =>
            {
                var cache = new MemoryCache(new MemoryCacheOptions());
                return(cache);
            });
            #endregion

            #region JWT认证
            //services.AddAuthorization(x =>
            //{
            //    //options.AddPolicy("System", policy => policy.RequireClaim("SystemType").Build());
            //    //options.AddPolicy("Client", policy => policy.RequireClaim("ClientType").Build());
            //    //options.AddPolicy("Admin", policy => policy.RequireClaim("AdminType").Build());


            //});
            #endregion

            services.AddControllers();

            SqlSugarBase._connectionString = Configuration["connectionString"];
        }
コード例 #50
0
ファイル: AppCache.cs プロジェクト: Dastus/KuPro
        public void Update(string name, object value, int minutes)
        {
            MemoryCache memoryCache = MemoryCache.Default;

            memoryCache.Set(name, value, DateTime.Now.AddMinutes(minutes));
        }
コード例 #51
0
        public static bool Add(string key, object value, DateTimeOffset absExpiration)
        {
            MemoryCache memoryCache = Default;

            return(memoryCache.Set(key, value, absExpiration) == value);
        }
コード例 #52
0
 public CacheHelp(MyMemoryCache memoryCache, IRoleService roleService, IAuthService authService)
 {
     _cache       = memoryCache.Cache;
     _roleService = roleService;
     _authService = authService;
 }
コード例 #53
0
ファイル: CacheService.cs プロジェクト: Jarris752/portfolio
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheService"/> class.
 /// </summary>
 /// <param name="memoryCache">The memory cache.</param>
 public CacheService(MemoryCache memoryCache)
 {
     this.memoryCache = memoryCache;
 }
コード例 #54
0
        public LocalCacheProvider()
        {
            MemoryCacheOptions options = new MemoryCacheOptions();

            _Cache = new MemoryCache(options);
        }
コード例 #55
0
 /// <summary>
 /// Construct a new FluentMemoryCache from the specified MemoryCache
 /// </summary>
 public FluentMemoryCache(MemoryCache memoryCache) : base(memoryCache)
 {
 }
コード例 #56
0
        public async Task RunAsync()
        {
            LoadingResult loadingResult = LoadingResult.Failed;
            bool          success       = false;

            try
            {
                // LOAD IMAGE
                if (!(await TryLoadFromMemoryCacheAsync().ConfigureAwait(false)))
                {
                    if (Parameters.DelayInMs.HasValue && Parameters.DelayInMs.Value > 0)
                    {
                        await Task.Delay(Parameters.DelayInMs.Value).ConfigureAwait(false);
                    }
                    else if (!Parameters.Preload && Configuration.DelayInMs > 0)
                    {
                        await Task.Delay(Configuration.DelayInMs).ConfigureAwait(false);
                    }

                    Logger.Debug(string.Format("Generating/retrieving image: {0}", Key));
                    var resolver = Parameters.CustomDataResolver ?? DataResolverFactory.GetResolver(Parameters.Path, Parameters.Source, Parameters, Configuration);
                    resolver = new WrappedDataResolver(resolver);
                    var imageData = await resolver.Resolve(Parameters.Path, Parameters, CancellationTokenSource.Token).ConfigureAwait(false);

                    loadingResult = imageData.LoadingResult;

                    ImageInformation = imageData.ImageInformation;
                    ImageInformation.SetKey(Key, Parameters.CustomCacheKey);
                    ImageInformation.SetPath(Parameters.Path);
                    ThrowIfCancellationRequested();

                    // Preload
                    if (Parameters.Preload && Parameters.CacheType.HasValue && Parameters.CacheType.Value == CacheType.Disk)
                    {
                        if (loadingResult == LoadingResult.Internet)
                        {
                            Logger?.Debug(string.Format("DownloadOnly success: {0}", Key));
                        }

                        success = true;

                        return;
                    }

                    ThrowIfCancellationRequested();

                    TImageContainer image;

                    if (imageData.Stream != null)
                    {
                        using (imageData.Stream)
                        {
                            image = await GenerateImageAsync(Parameters.Path, Parameters.Source, imageData.Stream, imageData.ImageInformation, true, false).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        image = imageData.ImageContainer as TImageContainer;
                    }

                    ThrowIfCancellationRequested();

                    try
                    {
                        BeforeLoading(image, false);

                        if (image != default(TImageContainer) && CanUseMemoryCache)
                        {
                            MemoryCache.Add(Key, imageData.ImageInformation, image);
                        }

                        ThrowIfCancellationRequested();

                        bool isFadeAnimationEnabled = Parameters.FadeAnimationEnabled ?? Configuration.FadeAnimationEnabled;

                        if (Target != null)
                        {
                            await SetTargetAsync(image, isFadeAnimationEnabled).ConfigureAwait(false);
                        }
                    }
                    finally
                    {
                        AfterLoading(image, false);
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException || ex is ObjectDisposedException)
                {
                    if (Configuration.VerboseLoadingCancelledLogging)
                    {
                        Logger.Debug(string.Format("Image loading cancelled: {0}", Key));
                    }
                }
                else
                {
                    if (Configuration.ClearMemoryCacheOnOutOfMemory && ex is OutOfMemoryException)
                    {
                        MemoryCache.Clear();
                    }

                    Logger.Error(string.Format("Image loading failed: {0}", Key), ex);

                    if (Configuration.ExecuteCallbacksOnUIThread && Parameters?.OnError != null)
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            Parameters?.OnError?.Invoke(ex);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        Parameters?.OnError?.Invoke(ex);
                    }

                    try
                    {
                        // Error placeholder if enabled
                        if (!Parameters.Preload && !string.IsNullOrWhiteSpace(Parameters.ErrorPlaceholderPath))
                        {
                            await ShowPlaceholder(Parameters.ErrorPlaceholderPath, KeyForErrorPlaceholder,
                                                  Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex2)
                    {
                        if (!(ex2 is OperationCanceledException))
                        {
                            Logger.Error(string.Format("Image loading failed: {0}", Key), ex);
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    if (CancellationTokenSource?.IsCancellationRequested == false)
                    {
                        CancellationTokenSource.Cancel();
                    }
                }
                catch (Exception)
                {
                }

                IsCompleted = true;

                using (Parameters)
                {
                    if (Configuration.ExecuteCallbacksOnUIThread && Parameters?.OnFinish != null)
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            if (success)
                            {
                                Parameters?.OnSuccess?.Invoke(ImageInformation, loadingResult);
                            }
                            Parameters?.OnFinish?.Invoke(this);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        if (success)
                        {
                            Parameters?.OnSuccess?.Invoke(ImageInformation, loadingResult);
                        }
                        Parameters?.OnFinish?.Invoke(this);
                    }

                    ImageService.RemovePendingTask(this);
                }
            }
        }
コード例 #57
0
 public InProcessCache(string name)
 {
     this.Cache = new MemoryCache(name);
 }
コード例 #58
0
    /// <summary>A TKey extension method that from cache.</summary>
    /// <typeparam name="TKey">Type of the key.</typeparam>
    /// <typeparam name="TValue">Type of the value.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cache">The cache.</param>
    /// <param name="valueFactory">The value factory.</param>
    /// <returns>A TValue.</returns>
    public static TValue FromCache <TKey, TValue>(this TKey @this, MemoryCache cache, Expression <Func <TKey, TValue> > valueFactory)
    {
        string key = string.Concat("Z.Caching.FromCache;", typeof(TKey).FullName, valueFactory.ToString());

        return(@this.FromCache(cache, key, valueFactory));
    }
コード例 #59
0
 /// <summary>
 /// Clear all items from the cache
 /// </summary>
 public void ResetCache()
 {
     _cache.Dispose();
     _cache = new MemoryCache("CustomCache");
 }
コード例 #60
0
ファイル: AppCache.cs プロジェクト: Dastus/KuPro
        public bool Add(string name, object value, int minutes)
        {
            MemoryCache memoryCache = MemoryCache.Default;

            return(memoryCache.Add(name, value, DateTime.Now.AddMinutes(minutes)));
        }