public void RepositoryBase_GetPage_Overload_Calls_GetAllByScopeInternal_If_Cacheable_And_Cache_Expired()
        {
            //Arrange
            var cacheKey = CachingProvider.GetCacheKey(String.Format(Constants.CACHE_CatsKey + "_" + Constants.CACHE_ScopeModule + "_{0}", Constants.MODULE_ValidId));

            var mockHostController = MockComponentProvider.CreateNew <IHostController>();

            mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("0");

            var mockCache = MockComponentProvider.CreateDataCacheProvider();

            mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(cacheKey))).Returns(null);

            var mockRepository = new Mock <RepositoryBase <CacheableCat> >();

            mockRepository.Protected().Setup <IEnumerable <CacheableCat> >("GetByScopeInternal", ItExpr.IsAny <object>())
            .Returns(new List <CacheableCat>());

            var mockData = MockComponentProvider.CreateDataProvider();

            mockData.Setup(d => d.GetProviderPath()).Returns(String.Empty);

            //Act
            var cats = mockRepository.Object.GetPage <int>(Constants.MODULE_ValidId, Constants.PAGE_First, Constants.PAGE_RecordCount);

            //Assert
            mockRepository.Protected().Verify <IEnumerable <CacheableCat> >("GetByScopeInternal", Times.Once(), ItExpr.IsAny <object>());
        }
        public void RepositoryBase_GetPage_Does_Not_Call_GetAllByPageInternal_If_Cacheable_And_Cache_Valid()
        {
            //Arrange
            var mockHostController = MockComponentProvider.CreateNew <IHostController>();

            mockHostController.Setup(h => h.GetString("PerformanceSetting")).Returns("3");

            var mockCache = MockComponentProvider.CreateDataCacheProvider();

            mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)))
            .Returns(new List <CacheableDog>()
            {
                new CacheableDog()
            });

            var mockRepository = new Mock <RepositoryBase <CacheableDog> >();

            mockRepository.Protected().Setup <IPagedList <CacheableDog> >("GetPageInternal", ItExpr.IsAny <int>(), ItExpr.IsAny <int>());

            //Act
            var dogs = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount);

            //Assert
            mockRepository.Protected().Verify <IPagedList <CacheableDog> >("GetPageInternal", Times.Never(), ItExpr.IsAny <int>(), ItExpr.IsAny <int>());
        }
示例#3
0
        private void BindSupportedFileTypes()
        {
            List <FileTypeInfo> collFiles = new List <FileTypeInfo>();
            object objCache = DotNetNuke.Services.Cache.CachingProvider.Instance().GetItem(FILE_TYPES_CACHE_KEY);

            if (objCache != null)
            {
                collFiles = (List <FileTypeInfo>)objCache;
            }
            else
            {
                ICollection <string> arrModuleSupport = (ICollection <string>)(MediaController.MEDIA_FILE_TYPES.Replace(".", string.Empty).Replace(" ", string.Empty).Split(','));
                ICollection <string> arrHostSupport   = (ICollection <string>)(MediaController.SUPPORTED_MEDIA_FILE_TYPES.Split(','));

                foreach (string oString in arrModuleSupport)
                {
                    FileTypeInfo oFile = new FileTypeInfo
                    {
                        FileType      = oString.ToLower(),
                        ModuleSupport = true,
                        HostSupport   = arrHostSupport.Contains(oString)
                    };
                    collFiles.Add(oFile);
                }

                collFiles.Sort((p1, p2) => p1.FileType.CompareTo(p2.FileType));

                CachingProvider.Instance().Insert(FILE_TYPES_CACHE_KEY, collFiles);
            }

            rptMediaFileTypes.DataSource = collFiles;
            rptMediaFileTypes.DataBind();
        }
示例#4
0
 public static void ReRegisterServiceRoutesWhileSiteIsRunning()
 {
     //by clearing a "fake" key on the caching provider we can echo this
     //command to all the members of a web farm
     //the caching provider will call to make the actual registration of new routes
     CachingProvider.Instance().Clear("ServiceFrameworkRoutes", "-1");
 }
        public void ProcessRequest(HttpContext context)
        {
            //Validate the request for required inputs, return if no action possible
            if (string.IsNullOrWhiteSpace(context.Request.QueryString["command"]))
            {
                return; //No command we cannot process
            }
            if (string.IsNullOrWhiteSpace(context.Request.QueryString["detail"]))
            {
                return; //No action we cannot return
            }
            //Only continue if our provider is current
            if (!(CachingProvider.Instance() is Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider))
            {
                return;
            }

            //Get the values, noting that if in debug we are not encrypted
            var command = Host.DebugMode
                ? context.Request.QueryString["command"]
                : UrlUtils.DecryptParameter(context.Request.QueryString["command"], Host.GUID);

            var detail = Host.DebugMode
                ? context.Request.QueryString["detail"]
                : UrlUtils.DecryptParameter(context.Request.QueryString["detail"], Host.GUID);

            //Pass the action on, if the current caching provider is ours
            var provider = (Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)CachingProvider.Instance();

            provider.ProcessSynchronizationRequest(command, detail);
        }
示例#6
0
        public async Task <TileEmbedConfig> GetTileEmbedConfigAsync(int userId, string tileId, string dashboardId)
        {
            var model = (TileEmbedConfig)CachingProvider.Instance().GetItem($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{userId}_{Thread.CurrentThread.CurrentUICulture.Name}_Dashboard_{dashboardId}_Tile_{tileId}");

            if (model != null)
            {
                return(model);
            }

            model = new TileEmbedConfig();
            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                // The error message set in GetTokenCredentials
                model.ErrorMessage = "Authentication failed.";
                return(model);
            }
            // Create a Power BI Client object. It will be used to call Power BI APIs.
            using (var client = new PowerBIClient(new Uri(Settings.ApiUrl), tokenCredentials))
            {
                // Get a list of dashboards.
                var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(Guid.Parse(Settings.WorkspaceId)).ConfigureAwait(false);

                // Get the first report in the workspace.
                var dashboard = dashboards.Value.FirstOrDefault(r => r.Id.ToString().Equals(dashboardId, StringComparison.InvariantCultureIgnoreCase));
                if (dashboard == null)
                {
                    tileEmbedConfig.ErrorMessage = "Workspace has no dashboards.";
                    return(model);
                }
                var tiles = await client.Dashboards.GetTilesInGroupAsync(Guid.Parse(Settings.WorkspaceId), Guid.Parse(dashboardId)).ConfigureAwait(false);

                // Get the first tile in the workspace.
                var tile = tiles.Value.FirstOrDefault(x => x.Id.ToString() == tileId);
                // Generate Embed Token for a tile.
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Tiles.GenerateTokenInGroupAsync(Guid.Parse(Settings.WorkspaceId), dashboard.Id, tile.Id, generateTokenRequestParameters).ConfigureAwait(false);

                if (tokenResponse == null)
                {
                    tileEmbedConfig.ErrorMessage = "Failed to generate embed token.";
                    return(model);
                }

                // Generate Embed Configuration.
                tileEmbedConfig = new TileEmbedConfig()
                {
                    EmbedToken  = tokenResponse,
                    EmbedUrl    = tile.EmbedUrl,
                    Id          = tile.Id.ToString(),
                    dashboardId = dashboard.Id.ToString(),
                    ContentType = "tile"
                };
                CachingProvider.Instance().Insert($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{userId}_{Thread.CurrentThread.CurrentUICulture.Name}_Dashboard_{dashboardId}_Tile_{tileId}", model, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero);
            }
            return(model);
        }
        public HttpResponseMessage SavePowerBiObjectsPermissions(SavePowerBiObjectsPermissionsInput input)
        {
            try
            {
                var settings = SharedSettingsRepository.Instance.GetSettingsById(input.settingsId, PortalId);
                if (settings.InheritPermissions != input.inheritPermissions)
                {
                    settings.InheritPermissions = input.inheritPermissions;
                    SharedSettingsRepository.Instance.UpdateSettings(settings, PortalId);
                }
                foreach (var pbiObject in input.powerBiObjects)
                {
                    ObjectPermissionsRepository.Instance.DeleteObjectPermissions(pbiObject.Id, PortalSettings.PortalId);
                    foreach (var permission in pbiObject.Permissions.RolePermissions)
                    {
                        var p = permission.Permissions.FirstOrDefault();
                        if (p != null)
                        {
                            ObjectPermissionsRepository.Instance.CreateObjectPermission(pbiObject.Id
                                                                                        , p.PermissionId
                                                                                        , p.AllowAccess
                                                                                        , PortalSettings.PortalId
                                                                                        , permission.RoleId
                                                                                        , null);
                        }
                    }
                    foreach (var permission in pbiObject.Permissions.UserPermissions)
                    {
                        var p = permission.Permissions.FirstOrDefault();
                        if (p != null)
                        {
                            ObjectPermissionsRepository.Instance.CreateObjectPermission(pbiObject.Id
                                                                                        , p.PermissionId
                                                                                        , p.AllowAccess
                                                                                        , PortalSettings.PortalId
                                                                                        , null
                                                                                        , permission.UserId);
                        }
                    }
                }

                CachingProvider.Instance().Clear("Prefix", $"PBI_{PortalId}_");

                return(Request.CreateResponse(HttpStatusCode.OK, new
                {
                    Success = true
                }));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new
                {
                    Success = false,
                    Message = Components.Common.LocalizeGlobalString("ErrorGeneric"),
                    Error = ex
                }));
            }
        }
 private int GetPartitionGeneration(TPartition partition)
 {
     if (!GenerationalCachingEnabled)
     {
         return(1);                             // no need to use the caching provider
     }
     return(!CachingProvider.Get(GetPartitionGenerationKey(partition), out int generation) ? 1 : generation);
 }
示例#9
0
 public AppConfig()
 {
     ServiceResolver.Current.Register(null, Activator.CreateInstance(typeof(HashAlgorithm), new object[] { }));
     _cacheWrapperSetting = Configuration.Get <CachingProvider>();
     RegisterConfigInstance();
     RegisterLocalInstance("ICacheClient`1");
     InitSettingMethod();
 }
示例#10
0
        public void ThrowAPostNotFoundExceptionIfTheIdIsNotFound()
        {
            var id              = Guid.Parse("2C662C69-4A58-4DA8-9B9F-3F417841D6BF");
            var container       = (null as IServiceCollection).Create();
            var serviceProvider = container.BuildServiceProvider();
            var target          = new CachingProvider(serviceProvider);

            Assert.Throws <PostNotFoundException>(() => target.GetUrlByPostId(id));
        }
        public void ItShouldThrowOnCacheableWithCachingProviderCall()
        {
            Action act = () => CachingProvider.Cacheable(Enumerable.Empty <PersonEntity>().AsQueryable()).FirstOrDefault();

            act.Should()
            .Throw <InvalidOperationException>()
            .WithMessage(
                "There is no method 'Cacheable' on type 'NHibernate.Linq.LinqExtensionMethods' that matches the specified arguments");
        }
示例#12
0
        public void ItShouldThrowOnCacheableWithCachingProviderCall()
        {
            Action act = () => CachingProvider.Cacheable(Enumerable.Empty <PersonEntity>().AsQueryable()).FirstOrDefault();

            act.Should()
            .Throw <NotSupportedException>()
            .WithMessage(
                "The query.Provider does not support setting options. Please implement IQueryProviderWithOptions.");
        }
示例#13
0
        public static void ClearModuleCache(int TabId)
        {
            CachingProvider.Instance().Clear("Module", TabId.ToString());
            Dictionary <int, int> portals = PortalController.GetPortalDictionary();

            if (portals.ContainsKey(TabId))
            {
                OutputCachingProvider.RemoveItemFromAllProviders(TabId);
            }
        }
        private int GetGeneration()
        {
            if (!GenerationalCachingEnabled)
            {
                return(1);                             // no need to use the caching provider
            }
            int generation;

            return(!CachingProvider.Get(GetGenerationKey(), out generation) ? 1 : generation);
        }
示例#15
0
        public void ReturnTheCorrectUrlBasedOnThePostId(string idString, string url)
        {
            var id              = Guid.Parse(idString);
            var container       = (null as IServiceCollection).Create();
            var serviceProvider = container.BuildServiceProvider();
            var target          = new CachingProvider(serviceProvider);
            var actual          = target.GetUrlByPostId(id);

            Assert.Equal(url, actual);
        }
示例#16
0
        public void TestConstructor_PassEverything_ShouldInitializeCorrectly()
        {
            // Arrange
            var mockedHttpContextProvider = new Mock <IHttpContextProvider>();

            // Act
            var provider = new CachingProvider(mockedHttpContextProvider.Object);

            // Assert
            Assert.IsNotNull(provider);
        }
 protected void ClearCache(string cacheKey)
 {
     try
     {
         CachingProvider.Clear(cacheKey);
     }
     catch (Exception)
     {
         // don't let caching errors mess with the repository
     }
 }
示例#18
0
 public static void ClearHostCache(bool Cascade)
 {
     if (Cascade)
     {
         ClearCache();
     }
     else
     {
         CachingProvider.Instance().Clear("Host", "");
     }
 }
示例#19
0
 public static void SetCache(string CacheKey, object objObject, CommonLibrary.Services.Cache.CacheDependency objDependency, System.DateTime AbsoluteExpiration, System.TimeSpan SlidingExpiration, CacheItemPriority Priority, CacheItemRemovedCallback OnRemoveCallback)
 {
     if (objObject != null)
     {
         if (OnRemoveCallback == null)
         {
             OnRemoveCallback = ItemRemovedCallback;
         }
         CachingProvider.Instance().Insert(GetCacheKey(CacheKey), objObject, objDependency, AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback);
     }
 }
示例#20
0
        public void TestConstructor_ShouldBeInstanceOfICachingProvider()
        {
            // Arrange
            var mockedHttpContextProvider = new Mock <IHttpContextProvider>();

            // Act
            var provider = new CachingProvider(mockedHttpContextProvider.Object);

            // Assert
            Assert.IsInstanceOf <ICachingProvider>(provider);
        }
示例#21
0
 public static void ClearPortalCache(int PortalId, bool Cascade)
 {
     if (Cascade)
     {
         CachingProvider.Instance().Clear("PortalCascade", PortalId.ToString());
     }
     else
     {
         CachingProvider.Instance().Clear("Portal", PortalId.ToString());
     }
 }
示例#22
0
        public static void ClearCache()
        {
            CachingProvider.Instance().Clear("Prefix", "5EAGLES_");
            dictionaryCache.Clear();
            LogInfo objEventLogInfo = new LogInfo();

            objEventLogInfo.LogTypeKey = CommonLibrary.Services.Log.EventLog.EventLogController.EventLogType.CACHE_REFRESH.ToString();
            objEventLogInfo.LogProperties.Add(new LogDetailInfo("*", "Refresh"));
            EventLogController objEventLog = new EventLogController();

            objEventLog.AddLog(objEventLogInfo);
        }
示例#23
0
 static internal void ProcessEventInternal(CachingMessage message)
 {
     if (message.From != ServerController.GetExecutingServerName() &&
         !(string.IsNullOrEmpty(message.Message)) && !(string.IsNullOrEmpty(message.Data)))
     {
         var cachingProvider = CachingProvider.Instance();
         if (cachingProvider is ServiceBusCachingProvider)
         {
             (cachingProvider as ServiceBusCachingProvider).ProcessMessage(message.Message, message.Data);
         }
     }
 }
示例#24
0
        private void Consumer()

        {
            List <E_TRANSFER_COMMISSION_SPLIT> splitFormular         = CachingProvider.GetCachedData <List <E_TRANSFER_COMMISSION_SPLIT> >("Transfer");
            List <E_FUNDGATE_COMMISSION_SPLIT> fundGatesplitFormular = CachingProvider.GetCachedData <List <E_FUNDGATE_COMMISSION_SPLIT> >("FundGate");

            List <CommissionMapViewModel> commission         = AutoMapper.Mapper.Map <List <CommissionMapViewModel> >(splitFormular);
            List <CommissionMapViewModel> fundGatecommission = AutoMapper.Mapper.Map <List <CommissionMapViewModel> >(fundGatesplitFormular);

            using (EtzbkDataContext etzbk = new EtzbkDataContext())
            {
                try
                {
                    etzbk.Configuration.AutoDetectChangesEnabled = false;

                    int i = 0;
                    foreach (var item in enqueData.GetConsumingEnumerable())
                    {
                        List <E_FEE_DETAIL_BK> feeDetailList = new List <E_FEE_DETAIL_BK>();
                        if (item.CHANNELID == "09")
                        {
                            feeDetailList = FeeProcessing.ProcessCardloadSplit(item, fundGatecommission);
                        }
                        else
                        {
                            feeDetailList = FeeProcessing.ProcessCardloadSplit(item, commission);
                        }

                        etzbk.E_FEE_DETAIL_BK.AddRange(feeDetailList);

                        E_SETTLEMENT_DOWNLOAD_BK e_settlement = AutoMapper.Mapper.Map <E_SETTLEMENT_DOWNLOAD_BK>(item);
                        decimal bankFee = feeDetailList.Where(fee => fee.MERCHANT_CODE.EndsWith("9999")).Select(FEE => FEE.FEE).FirstOrDefault();
                        e_settlement.BANK_FEE = bankFee;
                        etzbk.E_SETTLEMENT_DOWNLOAD_BK.Add(e_settlement);


                        if (i % 50 == 0)
                        {
                            etzbk.SaveChanges();
                        }
                        i++;
                    }
                    etzbk.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logger logger = new Logger();
                    Console.WriteLine("Exception from EtranzactChannelTransaction Run " + ExceptionExtensions.GetFullMessage(ex));
                    logger.LogInfoMessage("Exception from Run " + nameof(EtranzactChannelTransaction) + " " + ExceptionExtensions.GetFullMessage(ex));
                }
            }
        }
示例#25
0
        public void RepositoryBase_GetPage_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped()
        {
            // Arrange
            var mockCache = MockComponentProvider.CreateDataCacheProvider();

            var mockRepository = new Mock <RepositoryBase <CacheableCat> >();

            // Act
            var cats = mockRepository.Object.GetPage(Constants.PAGE_First, Constants.PAGE_RecordCount);

            // Assert
            mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never());
        }
示例#26
0
        public void RepositoryBase_GetById_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped()
        {
            // Arrange
            var mockCache = MockComponentProvider.CreateDataCacheProvider();

            var mockRepository = new Mock <RepositoryBase <CacheableCat> >();

            // Act
            var cat = mockRepository.Object.GetById(Constants.PETAPOCO_ValidCatId);

            // Assert
            mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never());
        }
示例#27
0
        public void RepositoryBase_Get_Does_Not_Check_Cache_If_Not_Cacheable()
        {
            // Arrange
            var mockCache = MockComponentProvider.CreateDataCacheProvider();

            var mockRepository = new Mock <RepositoryBase <Dog> >();

            // Act
            var list = mockRepository.Object.Get();

            // Assert
            mockCache.Verify(c => c.GetItem(CachingProvider.GetCacheKey(Constants.CACHE_DogsKey)), Times.Never());
        }
示例#28
0
 public ConfigurationWatchProvider(CPlatformContainer serviceProvider, ILogger <ConfigurationWatchProvider> logger, IServiceCacheManager serviceCacheManager)
 {
     if (serviceProvider.IsRegistered <IConfigurationWatchManager>())
     {
         serviceProvider.GetInstances <IConfigurationWatchManager>().Register(this);
     }
     _logger                       = logger;
     _cachingProvider              = AppConfig.Configuration.Get <CachingProvider>();
     _serviceCacheManager          = serviceCacheManager;
     _serviceCacheManager.Changed += ServiceCacheManager_Removed;
     _serviceCacheManager.Removed += ServiceCacheManager_Removed;
     _serviceCacheManager.Created += ServiceCacheManager_Add;
 }
示例#29
0
        private static bool CheckCancelledCallBack(ExportImportJob job)
        {
            var job2 = CachingProvider.Instance().GetItem(Util.GetExpImpJobCacheKey(job)) as ExportImportJob;

            if (job2 == null)
            {
                job2            = EntitiesController.Instance.GetJobById(job.JobId);
                job.IsCancelled = job2.IsCancelled;
                AddJobToCache(job2);
            }

            return(job2.IsCancelled);
        }
示例#30
0
 public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, CacheItemPriority Priority,
                             CacheItemRemovedCallback OnRemoveCallback)
 {
     if (objObject != null)
     {
         //if no OnRemoveCallback value is specified, use the default method
         if (OnRemoveCallback == null)
         {
             OnRemoveCallback = ItemRemovedCallback;
         }
         CachingProvider.Instance().Insert(GetDnnCacheKey(CacheKey), objObject, objDependency, AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback);
     }
 }
 public GeoProvider(CachingProvider cachingProvider, GeoRepository repository)
 {
     _cachingProvider = cachingProvider;
     _repository = repository;
 }