public static void SetCacheFactory(CacheFactory factory)
        {
            if (factory == null)
                throw new ArgumentNullException(nameof(factory));

            _cachefactory = factory;
        }
示例#2
0
        public void TestGetCacheFromMeekCacheFactory()
        {
            var cacheId = Guid.NewGuid().ToString();
            var factory = new CacheFactory();
            var expected = factory.GetCache(cacheId);
            var result = factory.GetCache(cacheId);

            Assert.IsTrue(result == expected);
        }
示例#3
0
 public void TestGetCacheFromMeekCacheFactoryThrowsArgumentNullException()
 {
     try
     {
         var factory = new CacheFactory();
         var cache = factory.GetCache(null);
     }
     catch (Exception ex)
     {
         Assert.IsTrue(ex is ArgumentNullException);
     }
 }
示例#4
0
        public void TestDefaultCacheFactoryDispose()
        {
            try
            {
                var factory = new CacheFactory();
                factory.Dispose();
                Assert.IsTrue(true);
            }
            catch (Exception)
            {

                Assert.IsTrue(false);
            }
        }
示例#5
0
 static WidgetBasePartService()
 {
     PageWidgetCacheManage = CacheFactory.Build <IEnumerable <WidgetBase> >(setting => setting.WithDictionaryHandle("PageWidgets"));
 }
示例#6
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper, string connectionString, HangfireLauncher hangfireLauncher, string modulesPath)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionString))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching

            //Cure for System.Runtime.Caching.MemoryCache freezing
            //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol
            app.SanitizeThreadCulture();
            ICacheManager <object> cacheManager = null;

            //Try to load cache configuration from web.config first
            //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
            var cacheManagerSection = ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) as CacheManagerSection;
            if (cacheManagerSection != null && cacheManagerSection.CacheManagers.Any(p => p.Name.EqualsInvariant("platformCache")))
            {
                var configuration = ConfigurationBuilder.LoadConfiguration("platformCache");

                if (configuration != null)
                {
                    configuration.LoggerFactoryType          = typeof(CacheManagerLoggerFactory);
                    configuration.LoggerFactoryTypeArguments = new object[] { container.Resolve <ILog>() };
                    cacheManager = CacheFactory.FromConfiguration <object>(configuration);
                }
            }
            if (cacheManager == null)
            {
                cacheManager = CacheFactory.Build("platformCache", settings =>
                {
                    settings.WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                    .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(5));
                });
            }

            container.RegisterInstance(cacheManager);

            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Profile",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                ValueType = ModuleSetting.TypeJson,
                                Title     = "Persisted state of main menu"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Language",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Language",
                                Description  = "Default language (two letter code from ISO 639-1, case-insensitive). Example: en, de",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.RegionalFormat",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Regional format",
                                Description  = "Default regional format (CLDR locale code, with dash or underscore as delemiter, case-insensitive). Example: en, en_US, sr_Cyrl, sr_Cyrl_RS",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.TimeZone",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Time zone",
                                Description = "Default time zone (IANA time zone name [tz database], exactly as in database, case-sensitive). Examples: America/New_York, Europe/Moscow"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.UseTimeAgo",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Use time ago format when is possible",
                                Description  = "When set to true (by default), system will display date in format like 'a few seconds ago' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.FullDateThreshold",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Full date threshold",
                                Description = "Number of units after time ago format will be switched to full date format"
                            },
                            new ModuleSetting
                            {
                                Name          = "VirtoCommerce.Platform.UI.FullDateThresholdUnit",
                                ValueType     = ModuleSetting.TypeString,
                                Title         = "Full date threshold unit",
                                Description   = "Unit of full date threshold",
                                DefaultValue  = "Never",
                                AllowedValues = new[]
                                {
                                    "Never",
                                    "Seconds",
                                    "Minutes",
                                    "Hours",
                                    "Days",
                                    "Weeks",
                                    "Months",
                                    "Quarters",
                                    "Years"
                                }
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Interface",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Customization",
                                ValueType    = ModuleSetting.TypeJson,
                                Title        = "Customization",
                                Description  = "JSON contains personalization settings of manager UI",
                                DefaultValue = "{\n" +
                                               "  \"title\": \"Virto Commerce\",\n" +
                                               "  \"logo\": \"Content/themes/main/images/logo.png\",\n" +
                                               "  \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\"\n" +
                                               "}"
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationHelper.GetConnectionStringValue("AssetsConnectionString"));

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(pathMapper, blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }


            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationHelper.SplitAppSettingsStringValue("VirtoCommerce:ModulesDataSources");
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionString));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
示例#7
0
        /// <summary>
        /// 超速报警短信通知
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            ICache cache = null;
            string type  = "超速";

            try
            {
                foreach (string saas in ConfigHelper.GetSaasList())
                {
                    try
                    {
                        MyWorkerRequest.CreateHttpContext(saas, "", "");

                        SmsInfoManager      sim       = new SmsInfoManager();
                        OPUserManager       oum       = new OPUserManager();
                        DataTable           users     = oum.GetReceiveSMSUsers();
                        VehicleAlarmManager vam       = new VehicleAlarmManager();
                        VehicleManager      vm        = new VehicleManager();
                        DataTable           dataTable = vam.GetOverSpeedList();
                        if (dataTable != null && dataTable.Rows.Count > 0)
                        {
                            cache = CacheFactory.GetCache();
                            foreach (DataRow row in dataTable.Rows)
                            {
                                string    vehicleID  = row[0].ToString();
                                Hashtable vehicle    = vm.GetVehicleInfoByID(vehicleID);
                                string    gpsNum     = SiteHelper.GetHashTableValueByKey(vehicle, "VehicleGPSNum").ToUpper();
                                string    name       = SiteHelper.GetHashTableValueByKey(vehicle, "Name").ToUpper();
                                string    alarmCount = row[1].ToString();
                                if (!string.IsNullOrEmpty(alarmCount))
                                {
                                    int count = 0;
                                    int.TryParse(alarmCount, out count);
                                    if (count >= 3)
                                    {
                                        if (users != null && users.Rows.Count > 0)
                                        {
                                            foreach (DataRow user in users.Rows)
                                            {
                                                string mobile     = user[0].ToString();
                                                string key        = "over_speed_alarm_" + mobile + "_" + vehicleID;
                                                string code_value = cache.Get <string>(key);
                                                if (string.IsNullOrEmpty(code_value))
                                                {
                                                    bool sendResult = sim.SendAlarm(mobile, gpsNum, name, type);
                                                    if (sendResult)
                                                    {
                                                        Logger.Warn(string.Format("车辆{0},{1}发生{2}报警,发送给{3}成功。", name, gpsNum, type, mobile));
                                                        DateTime dt = DateTime.Now.AddMinutes(20);
                                                        cache.Set(key, 1, dt - DateTime.Now);
                                                    }
                                                    else
                                                    {
                                                        Logger.Warn(string.Format("车辆{0},{1}发生{2}报警,发送给{3}失败。", name, gpsNum, type, mobile));
                                                    }
                                                }
                                                else
                                                {
                                                    Logger.Warn(string.Format("车辆{0},{1}发生{2}报警,发送给{3}未超过两小时。", name, gpsNum, type, mobile));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (cache != null)
                            {
                                cache.Dispose();
                            }
                        }
                    }
                    catch
                    {
                        if (cache != null)
                        {
                            cache.Dispose();
                        }
                        Logger.Info("车辆超速报警发送短信失败");
                    }
                }
            }
            catch
            {
                if (cache != null)
                {
                    cache.Dispose();
                }
                Logger.Info("车辆超速报警发送短信失败");
            }
        }
示例#8
0
        public void TestListeners()
        {
            IConfigurableCacheFactory ccf = CacheFactory.ConfigurableCacheFactory;

            IXmlDocument config =
                XmlHelper.LoadXml("assembly://Coherence.Tests/Tangosol.Resources/s4hc-near-cache-config.xml");

            ccf.Config = config;

            INamedCache cache = CacheFactory.GetCache("dist-extend-direct");

            cache.Clear();

            SyncListener listen = new SyncListener();

            cache.AddCacheListener(listen);
            Assert.IsNull(listen.CacheEvent);
            cache.Insert("global", "yes");
            Assert.IsNotNull(listen.CacheEvent);
            Assert.AreEqual(listen.CacheEvent.EventType, CacheEventType.Inserted);
            listen.CacheEvent = null;
            cache.RemoveCacheListener(listen);

            cache.AddCacheListener(listen, "test", false);
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("t", "a");
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("tes", "b");
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("test", "c");
            Assert.IsNotNull(listen.CacheEvent);
            Assert.AreEqual(listen.CacheEvent.EventType, CacheEventType.Inserted);

            listen.CacheEvent = null;
            Assert.IsNull(listen.CacheEvent);
            cache["test"] = "d";
            Assert.IsNotNull(listen.CacheEvent);
            Assert.AreEqual(listen.CacheEvent.EventType, CacheEventType.Updated);

            listen.CacheEvent = null;
            Assert.IsNull(listen.CacheEvent);
            var newValue = (String)cache["test"];

            Assert.AreEqual("d", newValue);
            Assert.IsNull(listen.CacheEvent);

            cache.Remove("test");
            Assert.IsNotNull(listen.CacheEvent);
            Assert.AreEqual(listen.CacheEvent.EventType, CacheEventType.Deleted);

            cache.RemoveCacheListener(listen, "test");
            CacheEventFilter likeFilter =
                new CacheEventFilter(new LikeFilter(IdentityExtractor.Instance, "%ic", '\\', false));

            cache.AddCacheListener(listen, likeFilter, false);

            listen.CacheEvent = null;
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("key1", "Ratko");
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("key2", "PerIc");
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("key3", "RatkoviC");
            Assert.IsNull(listen.CacheEvent);

            cache.Insert("key4", "Perovic");
            Assert.IsNotNull(listen.CacheEvent);
            Assert.AreEqual(listen.CacheEvent.EventType, CacheEventType.Inserted);

            CacheFactory.Shutdown();
        }
示例#9
0
        public void Coh8796()
        {
            LocalNamedCache localcache = new LocalNamedCache();
            INamedCache     safecache  = CacheFactory.GetCache("dist-extend-direct");
            NearCache       nearcache  = new NearCache(localcache, safecache, CompositeCacheStrategyType.ListenLogical);

            safecache.Clear();

            ICache cacheFront = nearcache.FrontCache;
            ICache cacheBack  = nearcache.BackCache;
            int    cPuts      = 1000;

            for (int i = 0; i < cPuts; i++)
            {
                cacheBack.Insert(i, i, 10000);
                if (i % 2 == 0)
                {
                    Object o = nearcache[i];
                    Assert.AreEqual(i, o);
                }
            }

            Assert.AreEqual(cPuts / 2, cacheFront.Count);
            Assert.AreEqual(cPuts, cacheBack.Count);

            // expire the back map
            Thread.Sleep(15000);

            // calling Count expires the entries in the back and sends out synthetic deletes
            Assert.AreEqual(0, cacheBack.Count);

            // ensure that synthetic deletes are filtered out;
            // front map values for evens are still there
            for (int i = 0; i < cPuts; i++)
            {
                if (i % 2 == 0)
                {
                    Assert.AreEqual(i, cacheFront[i]);
                }
                else
                {
                    Assert.IsNull(cacheFront[i]);
                }
            }

            Assert.AreEqual(cPuts / 2, cacheFront.Count); // 0, 2, 4, ...
            Assert.AreEqual(0, cacheBack.Count);

            // ensure that Insert works, and that a value update is properly
            // raised to both the front and back maps
            for (int i = 0; i < cPuts; i++)
            {
                int nKey = i * 4;

                nearcache.Insert(nKey, nKey);

                Assert.AreEqual(nKey, cacheFront[nKey]);
                Assert.AreEqual(nKey, cacheBack[nKey]);

                cacheBack.Insert(nKey, nKey + 1);

                Assert.IsNull(cacheFront[nKey]);
                Assert.AreEqual(nKey + 1, cacheBack[nKey]);

                nearcache.Insert(nKey, nKey);

                Assert.AreEqual(nKey, cacheFront[nKey]);
                Assert.AreEqual(nKey, cacheBack[nKey]);

                cacheBack.Remove(nKey);

                Assert.IsFalse(cacheBack.Contains(nKey));
                Assert.IsFalse(cacheFront.Contains(nKey));
                Assert.IsNull(cacheBack[nKey]);
                Assert.IsNull(cacheFront[nKey]);
            }
            nearcache.Release();
            // fresh reference to the cache
            safecache = CacheFactory.GetCache(CacheName);
            safecache.Destroy();
            CacheFactory.Shutdown();
        }
示例#10
0
        public ActionResult OrganizeTreeJson(string userGroupId)
        {
            var existAuthorizeData = permissionBLL.GetAuthorizeDataList(userGroupId);
            var organizedata       = organizeBLL.GetList();
            var departmentdata     = CacheFactory.Cache().GetCache <IEnumerable <DepartmentEntity> >(departmentBLL.cacheKey); //departmentCache.GetList(roleEntity.OrganizeId);

            if (departmentdata == null)
            {
                departmentdata = departmentBLL.GetList();
            }
            var treeList = new List <TreeEntity>();

            foreach (OrganizeEntity item in organizedata)
            {
                TreeEntity tree        = new TreeEntity();
                bool       hasChildren = organizedata.Count(t => t.ParentId == item.OrganizeId) == 0 ? false : true;
                if (hasChildren == false)
                {
                    hasChildren = departmentdata.Count(t => t.OrganizeId == item.OrganizeId) == 0 ? false : true;
                    if (hasChildren == false)
                    {
                        continue;
                    }
                }
                tree.id       = item.OrganizeId;
                tree.text     = item.FullName;
                tree.value    = item.OrganizeId;
                tree.parentId = item.ParentId;
                if (item.ParentId == "0")
                {
                    tree.img = "fa fa-sitemap";
                }
                else
                {
                    tree.img = "fa fa-home";
                }
                tree.checkstate  = existAuthorizeData.Count(t => t.ResourceId == item.OrganizeId);
                tree.showcheck   = true;
                tree.isexpand    = true;
                tree.complete    = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            foreach (DepartmentEntity item in departmentdata)
            {
                TreeEntity tree        = new TreeEntity();
                bool       hasChildren = departmentdata.Count(t => t.ParentId == item.DepartmentId) == 0 ? false : true;
                tree.id    = item.DepartmentId;
                tree.text  = item.FullName;
                tree.value = item.DepartmentId;
                if (item.ParentId == "0")
                {
                    tree.parentId = item.OrganizeId;
                }
                else
                {
                    tree.parentId = item.ParentId;
                }
                tree.checkstate  = existAuthorizeData.Count(t => t.ResourceId == item.DepartmentId);
                tree.showcheck   = true;
                tree.isexpand    = true;
                tree.complete    = true;
                tree.img         = "fa fa-umbrella";
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            int authorizeType = -1;

            if (existAuthorizeData.ToList().Count > 0)
            {
                authorizeType = existAuthorizeData.ToList()[0].AuthorizeType.ToInt();
            }
            var JsonData = new
            {
                authorizeType = authorizeType,
                authorizeData = existAuthorizeData,
                treeJson      = treeList.TreeToJson(),
            };

            return(Content(JsonData.ToJson()));
        }
示例#11
0
        /// <summary>
        /// 登录判断
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public UserEntity CheckLogin(string username, string password, string sessionid)
        {
            UserEntity userEntity = service.FindEntity(t => t.F_Account == username);

            if (userEntity != null)
            {
                if (userEntity.F_EnabledMark == true)
                {
                    UserLogOnEntity userLogOnEntity = userLogOnApp.GetForm(userEntity.F_Id);
                    if (userLogOnEntity == null)
                    {
                        throw new Exception("账户未初始化设置密码,请联系管理员");
                    }
                    string dbPassword = Md5.md5(DESEncrypt.Encrypt(password.ToLower(), userLogOnEntity.F_UserSecretkey).ToLower(), 32).ToLower();
                    if (dbPassword == userLogOnEntity.F_UserPassword)
                    {
                        DateTime lastVisitTime = DateTime.Now;
                        int      LogOnCount    = (userLogOnEntity.F_LogOnCount).ToInt() + 1;
                        if (userLogOnEntity.F_LastVisitTime != null)
                        {
                            userLogOnEntity.F_PreviousVisitTime = userLogOnEntity.F_LastVisitTime.ToDate();
                        }
                        userLogOnEntity.F_LoginSession  = sessionid;
                        userLogOnEntity.F_LastVisitTime = lastVisitTime;
                        userLogOnEntity.F_LogOnCount    = LogOnCount;
                        userLogOnApp.UpdateForm(userLogOnEntity);
                        //缓存记录登录sessionId
                        CacheFactory.Cache().WriteCache(sessionid, userEntity.F_Id);
                        return(userEntity);
                    }
                    else
                    {
                        if (userEntity.F_Account != "admin")
                        {
                            userLogOnEntity.F_ErrorNum = userLogOnEntity.F_ErrorNum + 1;
                            string erornum = (5 - userLogOnEntity.F_ErrorNum).ToString();
                            if (userLogOnEntity.F_ErrorNum == 5)
                            {
                                userLogOnEntity.F_ErrorNum = 0;
                                userEntity.F_EnabledMark   = true;
                                userLogOnApp.UpdateForm(userEntity, userLogOnEntity);
                                throw new Exception("密码不正确,账户被系统锁定");
                            }
                            else
                            {
                                userLogOnApp.UpdateForm(userLogOnEntity);
                                throw new Exception("密码不正确,请重新输入,还有" + erornum + "次机会");
                            }
                        }
                        else
                        {
                            throw new Exception("密码不正确,请重新输入");
                        }
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员");
                }
            }
            else
            {
                throw new Exception("账户不存在,请重新输入");
            }
        }
示例#12
0
        private static void cacheRemove(int id)
        {
            CacheManager cache = CacheFactory.GetCacheManager();

            cache.Remove("kitTessen_Seminars_" + id.ToString());
        }
示例#13
0
        public ActionResult CacheInfo()
        {
            ICache cache = CacheFactory.Create();

            return(View(cache.Count));
        }
        public async Task <ResponseObject <StaOnlineResult> > GetStaOnline(CurrentUser currentUser)
        {
            StaOnlineResult staOnlineResult = new StaOnlineResult();

            try
            {
                var userList = await _db.Instance.Queryable <TSMUserAccountDbModel, TSMUserInfoDbModel>(
                    (t1, t2) => new object[] { JoinType.Left, t1.UserInfoId == t2.ID }
                    ).Where((t1, t2) => t1.CompanyId == currentUser.CompanyID && t1.Status == 1).Select((t1, t2) => new { acount = t1, info = t2 }).ToListAsync();

                var redis = CacheFactory.Instance(CacheType.Redis) as RedisCache;

                string thisWeek = DateUtil.GetThisWeekString();
                string strV     = string.Format(CacheKeyString.StaOnlineUser, currentUser.CompanyID, thisWeek);
                string strTimeV = string.Format(CacheKeyString.StaOnlineTimes, currentUser.CompanyID, thisWeek);

                staOnlineResult.TotalUser = userList.Count();
                staOnlineResult.TopPlace  = new List <StaOnlineModel>();

                //本周
                List <byte[]> placeList = redis.ZScan(strV, 0);

                bool isFindSelf = false;
                int  place      = 1;
                for (int i = placeList.Count - 1; i > 0; i = i - 2)
                {
                    if (staOnlineResult.TopPlace.Count() >= 5 && isFindSelf)
                    {
                        break;
                    }

                    string userID = Encoding.UTF8.GetString(placeList[i - 1]); //姓名

                    if (staOnlineResult.TopPlace.Count() < 5)
                    {
                        StaOnlineModel staOnlineModel = new StaOnlineModel();
                        staOnlineModel.TimeSpend = Convert.ToDouble(Encoding.UTF8.GetString(placeList[i]));//时长

                        var userA = userList.Where(p => p.acount.ID.ToString() == userID).FirstOrDefault();
                        if (userA != null)
                        {
                            staOnlineModel.AccountName = userA.acount?.AccountName;
                            staOnlineModel.HeadPicPath = userA.info?.HeadPicPath;
                        }


                        staOnlineModel.Place = place;

                        List <byte[]> placeOrder = redis.ZScan(strTimeV, 0, 1, userID);
                        if (placeOrder.Count() > 1)
                        {
                            staOnlineModel.Times = Convert.ToInt32(Encoding.UTF8.GetString(placeOrder[1]));//次数
                        }

                        staOnlineResult.TopPlace.Add(staOnlineModel);
                    }

                    if (!isFindSelf)
                    {
                        if (userID == currentUser.UserID.ToString())
                        {
                            isFindSelf = true;

                            StaOnlineModel staOnlineModel = new StaOnlineModel();
                            staOnlineModel.TimeSpend = Convert.ToDouble(Encoding.UTF8.GetString(placeList[i]));//时长
                            staOnlineModel.Place     = place;

                            staOnlineResult.CurentStaTW = staOnlineModel;
                        }
                    }

                    place++;
                }

                if (!isFindSelf)//如果redis没有
                {
                    StaOnlineModel staOnlineModel = new StaOnlineModel();
                    staOnlineModel.TimeSpend = 0;//时长
                    staOnlineModel.Place     = place;

                    staOnlineResult.CurentStaTW = staOnlineModel;
                }

                //上周

                string lastWeek     = DateUtil.GetLastWeekString();
                string laststrV     = string.Format(CacheKeyString.StaOnlineUser, currentUser.CompanyID, lastWeek);
                string laststrTimeV = string.Format(CacheKeyString.StaOnlineTimes, currentUser.CompanyID, lastWeek);

                long lastPlace = redis.Client.GetItemIndexInSortedSetDesc(laststrV, currentUser.UserID.ToString());

                if (lastPlace == -1)
                {
                    StaOnlineModel staOnlineModel = new StaOnlineModel();
                    staOnlineModel.TimeSpend = 0;//时长

                    staOnlineModel.Place = staOnlineResult.TotalUser;

                    staOnlineResult.CurentStaLW = staOnlineModel;
                }
                else
                {
                    StaOnlineModel staOnlineModel = new StaOnlineModel();

                    List <byte[]> placeOrder = redis.ZScan(laststrTimeV, 0, 1, currentUser.UserID.ToString());
                    if (placeOrder.Count() > 1)
                    {
                        staOnlineModel.Times = Convert.ToInt32(Encoding.UTF8.GetString(placeOrder[1]));//次数
                    }

                    staOnlineModel.Place = lastPlace + 1;

                    staOnlineResult.CurentStaLW = staOnlineModel;
                }

                return(ResponseUtil <StaOnlineResult> .SuccessResult(staOnlineResult, 1));
            }
            catch (Exception ex)
            {
                return(ResponseUtil <StaOnlineResult> .FailResult(null, ex.Message));
            }
        }
示例#15
0
        private static void cacheStore(DojoSeminar dojoSeminar)
        {
            CacheManager cache = CacheFactory.GetCacheManager();

            cache.Add("kitTessen_Seminars_" + dojoSeminar.iD.ToString(), dojoSeminar);
        }
示例#16
0
        public string MakeNo(int CompanyID)
        {
            var redis = CacheFactory.Instance(CacheType.Redis);

            string key     = string.Format(CacheKeyString.LockGeneratorIR, CompanyID);
            string datekey = string.Format(CacheKeyString.LockGeneratorIR_date, CompanyID);


            var result = redis.LockRelease(key, TimeSpan.FromSeconds(10), () =>
            {
                DateSno dateSno = null;
                if (redis.ContainsKey(datekey))
                {
                    dateSno = redis.GetValueByKey <DateSno>(datekey); //获取redis 里面存储的日期
                }

                string nowStr = DateTime.Now.ToString("yyyyMMdd"); //当前日期


                if (dateSno != null)
                {
                    if (dateSno.DateStr != nowStr) //不是当天
                    {
                        dateSno = new DateSno()
                        {
                            DateStr = nowStr, SNO = 1
                        };

                        redis.UpdateKey(datekey, dateSno, 60 * 60 * 48);
                    }
                    else //当前 流水号+1
                    {
                        dateSno.SNO = dateSno.SNO + 1;

                        redis.UpdateKey(datekey, dateSno, 60 * 60 * 48);
                    }
                }
                else
                {
                    string no = _db.Instance.Queryable <TWMProfitMainDbModel>().Where(p => p.CompanyId == CompanyID && p.WarehousingOrder.StartsWith(ProvideName)).Max(p => p.WarehousingOrder);

                    if (!string.IsNullOrEmpty(no))
                    {
                        no = no.TrimStart(ProvideName.ToArray());

                        string timeStr = no.Substring(0, 8);
                        if (timeStr == nowStr)
                        {
                            string noIndex = no.Substring(8);

                            int index = Convert.ToInt32(noIndex);

                            dateSno = new DateSno()
                            {
                                DateStr = nowStr, SNO = index + 1
                            };

                            redis.UpdateKey(datekey, dateSno, 60 * 60 * 48);
                        }
                        else
                        {
                            dateSno = new DateSno()
                            {
                                DateStr = nowStr, SNO = 1
                            };

                            redis.UpdateKey(datekey, dateSno, 60 * 60 * 48);
                        }
                    }
                    else
                    {
                        dateSno = new DateSno()
                        {
                            DateStr = nowStr, SNO = 1
                        };

                        redis.UpdateKey(datekey, dateSno, 60 * 60 * 48);
                    }
                }


                return("IR" + dateSno.DateStr + dateSno.SNO.ToString().PadLeft(4, '0'));
            });

            return(result);
        }
示例#17
0
 static HiCache()
 {
     HiCache._cache = CacheFactory.CreateInstance();
 }
 public ProductData()
 {
     cache        = CacheFactory.GetCacheManager("Loading Scenario Cache Manager");
     dataProvider = new DataProvider();
 }
示例#19
0
 private static void MostSimpleCacheManagerC()
 {
     var cache = CacheFactory.Build <string>(
         p => p.WithSystemRuntimeCacheHandle());
 }
示例#20
0
 public void Remove()
 {
     CacheFactory.Cache().RemoveCache(cacheKey);
 }
示例#21
0
        private static void AppConfigLoadInstalledCacheCfg()
        {
            var cache = CacheFactory.FromConfiguration <object>("myCache");

            cache.Add("key", "value");
        }
        /// <summary>
        /// 处理时间过滤
        /// </summary>
        /// <returns></returns>
        public bool FilterTime()
        {
            //缓存key
            string cacheKey = "FilterTime_" + OperatorProvider.Provider.Current().UserId;
            //取得用户对象关系Id
            string objectId = OperatorProvider.Provider.Current().ObjectId;
            IEnumerable <FilterTimeEntity> filterTimeList = null;
            var cacheList = CacheFactory.Cache().GetCache <IEnumerable <FilterTimeEntity> >(cacheKey);

            if (cacheList == null)
            {
                filterTimeList = this.GetList(objectId);
                CacheFactory.Cache().WriteCache(filterTimeList, cacheKey, DateTime.Now.AddMinutes(1));
            }
            else
            {
                filterTimeList = cacheList;
            }
            int    weekday = Time.GetNumberWeekDay(DateTime.Now);
            string time    = DateTime.Now.ToString("HH") + ":00";

            if (filterTimeList.Count() > 0)
            {
                foreach (var item in filterTimeList)
                {
                    string strFilterTime = "";
                    switch (weekday)
                    {
                    case 1:
                        strFilterTime = item.WeekDay1;
                        break;

                    case 2:
                        strFilterTime = item.WeekDay2;
                        break;

                    case 3:
                        strFilterTime = item.WeekDay3;
                        break;

                    case 4:
                        strFilterTime = item.WeekDay4;
                        break;

                    case 5:
                        strFilterTime = item.WeekDay5;
                        break;

                    case 6:
                        strFilterTime = item.WeekDay6;
                        break;

                    case 7:
                        strFilterTime = item.WeekDay7;
                        break;

                    default:
                        break;
                    }
                    if (!string.IsNullOrEmpty(strFilterTime))
                    {
                        //当前时段包含在限制时段中
                        if (strFilterTime.IndexOf(time) >= 0)
                        {
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
示例#23
0
 public String AppendCache(string key, object value)
 {
     return(CacheFactory.GetInstance().AppendCache(key, value));
 }
示例#24
0
        internal static async Task <Possible <CacheCoreCacheInitializer> > TryInitializeCacheInternalAsync(
            LoggingContext loggingContext,
            PathTable pathTable,
            string cacheDirectory,
            ICacheConfiguration config,
            bool enableFingerprintLookup,
            RootTranslator rootTranslator)
        {
            Contract.Requires(pathTable != null);
            Contract.Requires(pathTable.IsValid);
            Contract.Requires(config != null);
            Contract.Requires(config.CacheLogFilePath.IsValid);
            Contract.Requires(config.CacheConfigFile.IsValid);
            Contract.Requires(!string.IsNullOrWhiteSpace(cacheDirectory));

            bool              succeeded = false;
            ICacheCoreCache   cache     = null;
            ICacheCoreSession session   = null;

            try
            {
                Possible <ICacheConfigData> cacheConfigData = TryGetCacheConfigData(pathTable, cacheDirectory, config);
                if (!cacheConfigData.Succeeded)
                {
                    return(cacheConfigData.Failure);
                }

                Possible <ICacheCoreCache> maybeCache = await CacheFactory.InitializeCacheAsync(cacheConfigData.Result, loggingContext.ActivityId);

                if (!maybeCache.Succeeded)
                {
                    return(maybeCache.Failure);
                }

                // We are now responsible for shutting this down (even if something later fails).
                cache = maybeCache.Result;

                cache.SuscribeForCacheStateDegredationFailures(
                    failure => { Tracing.Logger.Log.CacheReportedRecoverableError(loggingContext, failure.DescribeIncludingInnerFailures()); });

                // Log the cache ID we got.
                Tracing.Logger.Log.CacheInitialized(loggingContext, cache.CacheId);

                Possible <ICacheCoreSession> maybeSession =
                    string.IsNullOrWhiteSpace(config.CacheSessionName)
                        ? await cache.CreateSessionAsync()
                        : await cache.CreateSessionAsync(config.CacheSessionName);

                if (!maybeSession.Succeeded)
                {
                    return(maybeSession.Failure);
                }

                session = maybeSession.Result;

                succeeded = true;
                return(new CacheCoreCacheInitializer(
                           loggingContext,
                           cache,
                           session,
                           new List <IDisposable>(),
                           enableFingerprintLookup: enableFingerprintLookup,
                           rootTranslator: rootTranslator,
                           replaceExistingFileOnMaterialization: config.ReplaceExistingFileOnMaterialization));
            }
            finally
            {
                if (!succeeded)
                {
                    // Note that we clean up in reverse order that we initialized things.
                    if (session != null)
                    {
                        Analysis.IgnoreResult(await session.CloseAsync(), justification: "Okay to ignore close");
                        Analysis.IgnoreResult(await cache.ShutdownAsync(), justification:  "Okay to ignore shutdown");
                    }
                }
            }
        }
示例#25
0
文件: Data.cs 项目: lr030/ML
        private static BulkDataOperation <T> BulkExecute(EActionType type, IEnumerable <T> models, Mutator mutator = null, bool rawMode = false)
        {
            ValidateState(type);

            var    logStep = "";
            object logObj  = null;

            if (models == null)
            {
                return(null);
            }

            var modelSet   = models.ToList();
            var modelCount = modelSet.Count;

            var silent = modelCount == 1 || Info <T> .Settings.Silent;

            var _timed = new TimeLog();

            if (modelSet.Count == 0)
            {
                return(null);
            }

            var resultPackage = new BulkDataOperation <T> {
                Type = type
            };

            // First let's obtain any ServiceTokenGuid set by the user.

            lock (_bulkSaveLock)
            {
                try
                {
                    var     successSet = new List <T>();
                    var     failureSet = new List <T>();
                    Clicker logClicker = null;

                    _timed.Start($"{type} bulk [Warm-up]", !silent);
                    if (!silent)
                    {
                        logClicker = modelSet.GetClicker(_timed.CurrentMessage, !silent);
                    }

                    resultPackage.Control = new ConcurrentDictionary <string, DataOperationControl <T> >();

                    var paralelizableClicker = logClicker;

                    if (!rawMode)
                    {
                        Parallel.ForEach(modelSet, new ParallelOptions {
                            MaxDegreeOfParallelism = 5
                        }, item =>
                        {
                            paralelizableClicker?.Click();

                            if (item.IsNew())
                            {
                                var tempKey = mutator?.KeyPrefix + item.ToJson().Sha512Hash();

                                if (resultPackage.Control.ContainsKey(tempKey))
                                {
                                    if (!silent)
                                    {
                                        Current.Log.Warn <T>(_timed.Log($"    [Warm-up] duplicated key: {tempKey}"));
                                    }
                                    failureSet.Add(item);
                                }
                                else
                                {
                                    resultPackage.Control[tempKey] = new DataOperationControl <T> {
                                        Current = item, IsNew = true, Original = null
                                    };
                                }

                                return;
                            }

                            var modelKey = mutator?.KeyPrefix + item.GetDataKey();

                            if (resultPackage.Control.ContainsKey(modelKey))
                            {
                                if (!silent)
                                {
                                    Current.Log.Warn <T>(_timed.Log($"Repeated Identifier: {modelKey}. Data: {item.ToJson()}"));
                                }
                                return;
                            }

                            resultPackage.Control[modelKey] = new DataOperationControl <T> {
                                Current = item
                            };
                        });

                        logClicker?.End();

                        _timed.Log($"{type} bulk  [Before]", false);

                        logClicker = modelSet.GetClicker(_timed.CurrentMessage);

                        logStep = "obtaining original keys";
                        var originalKeys = resultPackage.Control.Where(controlItem => !controlItem.Value.IsNew).Select(controlPair => controlPair.Key).ToList();

                        logStep = "obtaining original models";
                        var originalSet = Get(originalKeys).ToList();

                        logStep = _timed.Log("Populating Control structure");
                        var originalMap = originalSet.ToDictionary(i => i.GetDataKey(), i => i).ToList();

                        foreach (var item in originalMap)
                        {
                            resultPackage.Control[item.Key].Original = item.Value;
                        }

                        logStep = "processing Control structure";

                        foreach (var controlItem in resultPackage.Control)
                        {
                            if (!silent)
                            {
                                logClicker.Click();
                            }

                            var currentModel  = controlItem.Value.Current;
                            var originalModel = controlItem.Value.Original;

                            var canProceed = true;

                            logStep = "checking if model is new";

                            if (!controlItem.Value.IsNew)
                            {
                                logObj = currentModel;

                                originalModel = type == EActionType.Remove ? ProcBeforePipeline(EActionType.Remove, EActionScope.Model, mutator, currentModel, originalModel) : ProcBeforePipeline(controlItem.Value.IsNew ? EActionType.Insert : EActionType.Update, EActionScope.Model, mutator, currentModel, originalModel);

                                if (originalModel == null)
                                {
                                    failureSet.Add(currentModel);
                                    controlItem.Value.Success = false;
                                    controlItem.Value.Message = "Failed ProcBeforePipeline";
                                    canProceed = false;
                                }
                            }
                            else
                            {
                                if (type == EActionType.Remove) // So we're removing a New object. Just ignore.
                                {
                                    failureSet.Add(currentModel);
                                    controlItem.Value.Success = false;
                                    controlItem.Value.Message = $"Invalid {type} operation: Record is New()";
                                    canProceed = false;
                                }
                                else
                                {
                                    originalModel = currentModel;
                                }
                            }

                            if (canProceed)
                            {
                                logStep = "Adding model to process list";
                                logObj  = currentModel;

                                successSet.Add(originalModel);

                                if (type == EActionType.Remove)
                                {
                                    originalModel.BeforeRemove();
                                }
                                else
                                {
                                    if (!originalModel.IsNew())
                                    {
                                        originalModel.BeforeUpdate();
                                    }
                                    else
                                    {
                                        originalModel.BeforeInsert();
                                    }

                                    originalModel.BeforeSave();
                                }

                                controlItem.Value.Success = true;
                            }
                        }

                        if (!silent)
                        {
                            logClicker.End();
                        }

                        logStep = _timed.Log($"{type} {successSet.Count} models");

                        if (type == EActionType.Remove)
                        {
                            Info <T> .Settings.Adapter.BulkRemove(successSet);
                        }
                        else
                        {
                            Info <T> .Settings.Adapter.BulkUpsert(successSet);
                        }

                        if (!silent)
                        {
                            logClicker = modelSet.GetClicker($"{type} bulk   [After]");
                        }

                        logStep = _timed.Log("post-processing individual models");

                        Parallel.ForEach(resultPackage.Control.Where(i => i.Value.Success), new ParallelOptions {
                            MaxDegreeOfParallelism = 5
                        }, controlModel =>
                        {
                            var key = controlModel.Key;
                            if (!silent)
                            {
                                logClicker.Click();
                            }

                            if (type == EActionType.Remove)
                            {
                                controlModel.Value.Current.AfterRemove();
                                ProcAfterPipeline(EActionType.Remove, EActionScope.Model, mutator, controlModel.Value.Current, controlModel.Value.Original);
                            }
                            else
                            {
                                if (controlModel.Value.IsNew)
                                {
                                    controlModel.Value.Current.AfterInsert(key);
                                }
                                else
                                {
                                    controlModel.Value.Current.AfterUpdate(key);
                                }

                                controlModel.Value.Current.AfterSave(key);

                                ProcAfterPipeline(controlModel.Value.IsNew ? EActionType.Insert : EActionType.Update, EActionScope.Model, mutator, controlModel.Value.Current, controlModel.Value.Original);
                            }

                            CacheFactory.FlushModel <T>(key);
                        });

                        resultPackage.Success = successSet;
                        resultPackage.Failure = failureSet;

                        logStep = _timed.Log($"{type} bulk operation complete. Success: {resultPackage.Success.Count} | Failure: {resultPackage.Failure.Count}");

                        if (!silent)
                        {
                            logClicker.End();
                        }
                        _timed.End(false);
                    }
                    else //RawMode means no triggers. AT ALL.
                    {
                        if (type == EActionType.Remove)
                        {
                            Info <T> .Settings.Adapter.BulkRemove(modelSet);
                        }
                        else
                        {
                            Info <T> .Settings.Adapter.BulkUpsert(modelSet);
                        }
                    }

                    return(resultPackage);
                }
                catch (Exception e)
                {
                    if (!silent)
                    {
                        Current.Log.Add <T>(e);
                    }
                    var ex = new Exception($"{type} - Error while {logStep} {logObj?.ToJson()}: {e.Message}", e);

                    _timed.End();
                    throw ex;
                }
            }
        }
        public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
        {
            Init();
            log.Info("building session factory");

            properties          = new Dictionary <string, string>(cfg.Properties);
            interceptor         = cfg.Interceptor;
            this.settings       = settings;
            sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
            eventListeners      = listeners;
            filters             = new Dictionary <string, FilterDefinition>(cfg.FilterDefinitions);
            if (log.IsDebugEnabled)
            {
                log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
            }

            try
            {
                if (settings.IsKeywordsImportEnabled)
                {
                    SchemaMetadataUpdater.Update(this);
                }
                if (settings.IsAutoQuoteEnabled)
                {
                    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
                }
            }
            catch (NotSupportedException)
            {
                // Ignore if the Dialect does not provide DataBaseSchema
            }

            #region Caches
            settings.CacheProvider.Start(properties);
            #endregion

            #region Generators
            identifierGenerators = new Dictionary <string, IIdentifierGenerator>();
            foreach (PersistentClass model in cfg.ClassMappings)
            {
                if (!model.IsInherited)
                {
                    IIdentifierGenerator generator =
                        model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
                                                                   settings.DefaultSchemaName, (RootClass)model);

                    identifierGenerators[model.EntityName] = generator;
                }
            }
            #endregion

            #region Persisters

            Dictionary <string, ICacheConcurrencyStrategy> caches = new Dictionary <string, ICacheConcurrencyStrategy>();
            entityPersisters        = new Dictionary <string, IEntityPersister>();
            implementorToEntityName = new Dictionary <System.Type, string>();

            Dictionary <string, IClassMetadata> classMeta = new Dictionary <string, IClassMetadata>();

            foreach (PersistentClass model in cfg.ClassMappings)
            {
                model.PrepareTemporaryTables(mapping, settings.Dialect);
                string cacheRegion = model.RootClazz.CacheRegionName;
                ICacheConcurrencyStrategy cache;
                if (!caches.TryGetValue(cacheRegion, out cache))
                {
                    cache =
                        CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
                    if (cache != null)
                    {
                        caches.Add(cacheRegion, cache);
                        allCacheRegions.Add(cache.RegionName, cache.Cache);
                    }
                }
                IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
                entityPersisters[model.EntityName] = cp;
                classMeta[model.EntityName]        = cp.ClassMetadata;

                if (model.HasPocoRepresentation)
                {
                    implementorToEntityName[model.MappedClass] = model.EntityName;
                }
            }
            classMetadata = new UnmodifiableDictionary <string, IClassMetadata>(classMeta);

            Dictionary <string, ISet <string> > tmpEntityToCollectionRoleMap = new Dictionary <string, ISet <string> >();
            collectionPersisters = new Dictionary <string, ICollectionPersister>();
            foreach (Mapping.Collection model in cfg.CollectionMappings)
            {
                ICacheConcurrencyStrategy cache =
                    CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
                                             properties);
                if (cache != null)
                {
                    allCacheRegions[cache.RegionName] = cache.Cache;
                }
                ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
                collectionPersisters[model.Role] = persister;
                IType indexType = persister.IndexType;
                if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashedSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
                IType elementType = persister.ElementType;
                if (elementType.IsAssociationType && !elementType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashedSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
            }
            Dictionary <string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary <string, ICollectionMetadata>(collectionPersisters.Count);
            foreach (KeyValuePair <string, ICollectionPersister> collectionPersister in collectionPersisters)
            {
                tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
            }
            collectionMetadata = new UnmodifiableDictionary <string, ICollectionMetadata>(tmpcollectionMetadata);
            collectionRolesByEntityParticipant = new UnmodifiableDictionary <string, ISet <string> >(tmpEntityToCollectionRoleMap);
            #endregion

            #region Named Queries
            namedQueries         = new Dictionary <string, NamedQueryDefinition>(cfg.NamedQueries);
            namedSqlQueries      = new Dictionary <string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
            sqlResultSetMappings = new Dictionary <string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
            #endregion

            imports = new Dictionary <string, string>(cfg.Imports);

            #region after *all* persisters and named queries are registered
            foreach (IEntityPersister persister in entityPersisters.Values)
            {
                persister.PostInstantiate();
            }
            foreach (ICollectionPersister persister in collectionPersisters.Values)
            {
                persister.PostInstantiate();
            }
            #endregion

            #region Serialization info

            name = settings.SessionFactoryName;
            try
            {
                uuid = (string)UuidGenerator.Generate(null, null);
            }
            catch (Exception)
            {
                throw new AssertionFailure("Could not generate UUID");
            }

            SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

            #endregion

            log.Debug("Instantiated session factory");

            #region Schema management
            if (settings.IsAutoCreateSchema)
            {
                new SchemaExport(cfg).Create(false, true);
            }

            if (settings.IsAutoUpdateSchema)
            {
                new SchemaUpdate(cfg).Execute(false, true);
            }
            if (settings.IsAutoValidateSchema)
            {
                new SchemaValidator(cfg, settings).Validate();
            }
            if (settings.IsAutoDropSchema)
            {
                schemaExport = new SchemaExport(cfg);
            }
            #endregion

            #region Obtaining TransactionManager
            // not ported yet
            #endregion

            currentSessionContext = BuildCurrentSessionContext();

            if (settings.IsQueryCacheEnabled)
            {
                updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
                queryCache            = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
                queryCaches           = new ThreadSafeDictionary <string, IQueryCache>(new Dictionary <string, IQueryCache>());
            }
            else
            {
                updateTimestampsCache = null;
                queryCache            = null;
                queryCaches           = null;
            }

            #region Checking for named queries
            if (settings.IsNamedQueryStartupCheckingEnabled)
            {
                IDictionary <string, HibernateException> errors = CheckNamedQueries();
                if (errors.Count > 0)
                {
                    StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
                    foreach (KeyValuePair <string, HibernateException> pair in errors)
                    {
                        failingQueries.Append('{').Append(pair.Key).Append('}');
                        log.Error("Error in named query: " + pair.Key, pair.Value);
                    }
                    throw new HibernateException(failingQueries.ToString());
                }
            }
            #endregion

            Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

            // EntityNotFoundDelegate
            IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
            if (enfd == null)
            {
                enfd = new DefaultEntityNotFoundDelegate();
            }
            entityNotFoundDelegate = enfd;
        }
示例#27
0
        public void NearCacheListenNoneTest()
        {
            LocalNamedCache localcache = new LocalNamedCache();
            INamedCache     safecache  = CacheFactory.GetCache(CacheName);
            NearCache       nearcache  = new NearCache(localcache, safecache, CompositeCacheStrategyType.ListenNone);

            nearcache.Clear();

            nearcache.Add(1, "Ivan");
            Assert.AreEqual(1, nearcache.Count);
            Assert.AreEqual(1, nearcache.FrontCache.Count);
            Assert.AreEqual(1, nearcache.BackCache.Count);
            nearcache.Insert(2, "Goran");
            Assert.AreEqual(2, nearcache.Count);
            Assert.AreEqual(2, nearcache.FrontCache.Count);
            Assert.AreEqual(2, nearcache.BackCache.Count);
            Assert.IsTrue(nearcache.FrontCache.Contains(1));
            Assert.IsTrue(nearcache.FrontCache.Contains(2));
            Assert.IsTrue(nearcache.BackCache.Contains(1));
            Assert.IsTrue(nearcache.BackCache.Contains(2));

            object obj = nearcache[1];

            Assert.AreEqual("Ivan", obj);
            obj = nearcache[2];
            Assert.AreEqual("Goran", obj);

            nearcache.Clear();
            Assert.AreEqual(0, nearcache.Count);
            Assert.IsTrue(nearcache.IsActive);
            localcache.LocalCache = new LocalCache(Int32.MaxValue, 500);
            nearcache.Insert(1, "Ana");
            nearcache.Add(2, "Goran");
            Assert.IsTrue(nearcache.FrontCache.Contains(1));
            Assert.IsTrue(nearcache.FrontCache.Contains(2));
            Assert.IsTrue(nearcache.BackCache.Contains(1));
            Assert.IsTrue(nearcache.BackCache.Contains(2));
            Thread.Sleep(1000);
            Assert.IsNull(nearcache.FrontCache[1]);
            Assert.IsNull(nearcache.FrontCache[2]);

            nearcache.Insert(3, "Ivan");
            IDictionary dict = nearcache.GetAll(new object[] { 1, 2, 3, 4 });

            Assert.AreEqual("Ana", dict[1]);
            Assert.AreEqual("Goran", dict[2]);
            Assert.AreEqual("Ivan", dict[3]);
            Assert.AreEqual(null, dict[4]);

            localcache.LocalCache = new LocalCache();
            obj = nearcache[1];
            Assert.AreEqual(obj, "Ana");
            Assert.IsTrue(nearcache.FrontCache.Contains(1));
            Assert.IsNull(nearcache.FrontCache[2]);

            Hashtable ht = new Hashtable();

            ht.Add(2, "Goran");
            ht.Add(3, "Ivan");
            ht.Add(4, "Aleks");
            nearcache.InsertAll(ht);
            nearcache.Remove(1);
            Assert.IsNull(nearcache.FrontCache[1]);
            Assert.IsNull(nearcache[1]);

            nearcache.Clear();
            nearcache.Release();
            Assert.IsFalse(nearcache.IsActive);

            CacheFactory.Shutdown();
        }
示例#28
0
 public void TestRemoveCacheFromMeekCacheFactory()
 {
     var cacheId = Guid.NewGuid().ToString();
     var factory = new CacheFactory();
     var expected = factory.GetCache(cacheId);
     factory.RemoveCache(cacheId);
     var result = factory.GetCache(cacheId);
     Assert.IsFalse(expected == result);
 }
示例#29
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName, HangfireLauncher hangfireLauncher, string modulesPath)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion


            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                .WithUpdateMode(CacheUpdateMode.Up)
                .WithSystemRuntimeCacheHandle("memCacheHandle")
                .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance(cacheManager);
            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["AssetsConnectionString"].ConnectionString);

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }


            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:ModulesDataSources", string.Empty).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
示例#30
0
        static void Main(string[] args)
        {
            try
            {
                CacheFactory cacheFactory = CacheFactory.CreateCacheFactory();

                Console.WriteLine("Connected to the Geode Distributed System");

                // Create a Geode Cache with the "clientPdxRemoteQuery.xml" Cache XML file.
                Cache cache = cacheFactory.Set("cache-xml-file", "XMLs/clientPdxSerializer.xml").Create();

                Console.WriteLine("Created the Geode Cache");

                // Get the example Region from the Cache which is declared in the Cache XML file.
                IRegion <string, Person> region = cache.GetRegion <string, Person>("Person");

                Console.WriteLine("Obtained the Region from the Cache");

                //to map .net type tp pdx type or java type
                Serializable.SetPdxTypeMapper(new PdxTypeMapper());

                // Register inbuilt reflection based autoserializer to serialize the domain types(Person class) as pdx format
                Serializable.RegisterPdxSerializer(new AutoSerializerEx());
                Console.WriteLine("Registered Person Query Objects");

                // Populate the Region with some PortfolioPdx objects.
                Person p1 = new Person("John", 1 /*ID*/, 23 /*age*/);
                Person p2 = new Person("Jack", 2 /*ID*/, 20 /*age*/);
                Person p3 = new Person("Tony", 3 /*ID*/, 35 /*age*/);

                region["Key1"] = p1;
                region["Key2"] = p2;
                region["Key3"] = p3;

                Console.WriteLine("Populated some Person Objects");

                //find the pool
                Pool pool = PoolManager.Find("examplePool");

                // Get the QueryService from the pool
                QueryService <string, Person> qrySvc = pool.GetQueryService <string, Person>();

                Console.WriteLine("Got the QueryService from the Pool");

                // Execute a Query which returns a ResultSet.
                Query <Person>          qry     = qrySvc.NewQuery("SELECT DISTINCT * FROM /Person");
                ISelectResults <Person> results = qry.Execute();

                Console.WriteLine("ResultSet Query returned {0} rows", results.Size);

                // Execute a Query which returns a StructSet.
                QueryService <string, Struct> qrySvc1 = pool.GetQueryService <string, Struct>();
                Query <Struct>          qry1          = qrySvc1.NewQuery("SELECT name, age FROM /Person WHERE id = 1");
                ISelectResults <Struct> results1      = qry1.Execute();

                Console.WriteLine("StructSet Query returned {0} rows", results1.Size);

                // Iterate through the rows of the query result.
                int rowCount = 0;
                foreach (Struct si in results1)
                {
                    rowCount++;
                    Console.WriteLine("Row {0} Column 1 is named {1}, value is {2}", rowCount, si.Set.GetFieldName(0), si[0].ToString());
                    Console.WriteLine("Row {0} Column 2 is named {1}, value is {2}", rowCount, si.Set.GetFieldName(1), si[1].ToString());
                }


                // Close the Geode Cache.
                cache.Close();

                Console.WriteLine("Closed the Geode Cache");
            }
            // An exception should not occur
            catch (GeodeException gfex)
            {
                Console.WriteLine("PdxSerializer Geode Exception: {0}", gfex.Message);
            }
        }
示例#31
0
 public void Dispose()
 {
     Cache = null;
     CacheFactory.Dispose();
 }
示例#32
0
        private static void cacheStore(DojoRank dojoRank)
        {
            CacheManager cache = CacheFactory.GetCacheManager();

            cache.Add("kitTessen_Ranks_" + dojoRank.iD.ToString(), dojoRank);
        }
        public void Configuration(IAppBuilder app)
        {
            var config = System.Web.Http.GlobalConfiguration.Configuration;

            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling =
                Newtonsoft.Json.NullValueHandling.Ignore;
            config.CacheOutputConfiguration().RegisterCacheOutputProvider(() => new CustomCacheProvider());
            config.CacheOutputConfiguration().RegisterDefaultCacheKeyGeneratorProvider(() => new CustomCacheKeyGenerator());
            ConfigureServices(app, config);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            System.Web.Http.GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling =
                Newtonsoft.Json.NullValueHandling.Ignore;
            app.CreatePerOwinContext(MiniSessionManager.Create);
            app.CreatePerOwinContext <UserManager>(UserManager.Create);
            app.CreatePerOwinContext(() =>
            {
                var signInManager = new SignInManager <IdentityUser, string>(
                    HttpContext.Current.GetOwinContext().GetUserManager <UserManager>(),
                    HttpContext.Current.GetOwinContext().Authentication
                    );
                return(signInManager);
            });
            System.Web.Http.GlobalConfiguration.Configure(ThrottleConfig.Register);
            System.Web.Http.GlobalConfiguration.Configure(APIRegistryConfig.Register);
            int cookieValidationIntervalInSeconds = 1;

            try
            {
                cookieValidationIntervalInSeconds = int.Parse(ConfigurationManager.AppSettings["AuthenticationCookieValidationIntervalInSeconds"]);
            }
            catch (Exception e)
            {
                log4net.LogManager.GetLogger("CookieValidationInterval").Error("Could not parse Cookie Validation Interval Setting! Using default...", e);
            }
            // Retrieve Session Storage cache settings, to sync with authentication cookie
            var authenticationCookineExpirationTimeout = TimeSpan.FromMinutes(20);

            //var authenticationCookineSlidingExpiration = true;
            try
            {
                var cacheConfig        = CacheFactory.FromConfiguration <object>(CacheManager.Core.ConfigurationBuilder.LoadConfiguration("SessionStateStorage"));
                var sessionCacheHandle = cacheConfig.CacheHandles.FirstOrDefault();
                authenticationCookineExpirationTimeout = sessionCacheHandle.Configuration.ExpirationTimeout;
                //authenticationCookineSlidingExpiration = sessionCacheHandle.Configuration.ExpirationMode == ExpirationMode.Sliding;
            }
            catch (Exception e)
            {
                log4net.LogManager.GetLogger("SessionStateStorage").Error("Could not retrieve cache configuration for Session Storage!", e);
            }
            log4net.LogManager.GetLogger("AuthenticationCookie").Info($"Authentication Cookie Timeout: {authenticationCookineExpirationTimeout.Minutes} minute(s)");
            //log4net.LogManager.GetLogger("AuthenticationCookie").Info($"Authentication Cookie Sliding Expiration Enabled: {authenticationCookineSlidingExpiration}");
            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
            {
                CookieName         = ConfigurationManager.AppSettings["AuthenticationCookieName"],
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                ExpireTimeSpan     = authenticationCookineExpirationTimeout,
                //SlidingExpiration = authenticationCookineSlidingExpiration,  // Sliding expiration is always what happens despite this setting

                LoginPath = new PathString("/SignInPage/Load"),

                ReturnUrlParameter = "returnUrl",

                Provider = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = context =>
                    {
                        log4net.LogManager.GetLogger("CookieAuthenticationProvider").Error("REDIRECTING!!!");
                    },
                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(validateInterval: TimeSpan.FromSeconds(cookieValidationIntervalInSeconds)),
                    OnException        = context => log4net.LogManager.GetLogger("IdentityLogger").DebugFormat("CookieAuthenticationProvider Error for req: {0}", context.Request.Path)
                },
            });
            app.UseBasicAuthentication(new BasicAuthenticationOptions("", (id, secret) =>
            {
                try
                {
                    if (!IdentityHelper.ValidateUser(id, secret))
                    {
                        return(Task.FromResult <IEnumerable <Claim> >(null));
                    }
                    var user = IdentityHelper.GetUserManager().FindByName(id);
                    if (user == null)
                    {
                        return(Task.FromResult <IEnumerable <Claim> >(new List <Claim>()));
                    }
                    var claims = user.User.Permissions.Select(p => new Claim(ClaimTypes.Permission, p.Name)).ToList();
                    claims.Add(new Claim(System.Security.Claims.ClaimTypes.Name, user.UserName));
                    if (!string.IsNullOrWhiteSpace(user.User.Email))
                    {
                        claims.Add(new Claim(System.Security.Claims.ClaimTypes.Email, user.User.Email));
                    }
                    var userRoles = user.User.Roles.Select(r => new Claim(System.Security.Claims.ClaimTypes.Role, r.Name));
                    claims.AddRange(userRoles);
                    return(Task.FromResult <IEnumerable <Claim> >(claims));
                }
                catch (Exception e)
                {
                    log4net.LogManager.GetLogger("BasicAuthentication.CredentialValidationFunction").Error("Error validating identity!", e);
                    return(Task.FromResult <IEnumerable <Claim> >(null));
                }
            }));
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:authority"]))
            {
                var options = new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = ConfigurationManager.AppSettings["idsrv:authority"]
                };
                if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:scopes"]))
                {
                    options.RequiredScopes = ConfigurationManager.AppSettings["idsrv:scopes"].Split(' ');
                }
                if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:clientid"]) &&
                    !string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["idsrv:clientsecret"]))
                {
                    options.ClientId     = ConfigurationManager.AppSettings["idsrv:clientid"];
                    options.ClientSecret = ConfigurationManager.AppSettings["idsrv:clientsecret"];
                }
                app.UseIdentityServerBearerTokenAuthentication(options);
            }
            else
            {
                // Configure the application for OAuth based flow
                var PublicClientId = "self";
                var OAuthOptions   = new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath         = new PathString("/OAuth/Token"),
                    Provider                  = new zAppDev.DotNet.Framework.Identity.AppOAuthProvider(PublicClientId),
                    AuthorizeEndpointPath     = new PathString("/OAuth/Account/ExternalLogin"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
                    AllowInsecureHttp         = true // Don't do this in production ONLY FOR DEVELOPING: ALLOW INSECURE HTTP!
                };
                // Enable the application to use bearer tokens to authenticate users
                app.UseOAuthBearerTokens(OAuthOptions);
            }
            Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver.Register(typeof(Newtonsoft.Json.JsonSerializer), () =>
            {
                return(Newtonsoft.Json.JsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings
                {
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                    ContractResolver = new zAppDev.DotNet.Framework.Utilities.NHibernateContractResolver()
                }));
            });
            app.MapSignalR();
            zAppDev.DotNet.Framework.Identity.IdentityHelper.AllowMultipleSessionsPerUser = true;
            zAppDev.DotNet.Framework.Identity.IdentityHelper.AdminCanResetPassword        = false;
            DSS1_RetailerDriverStockOptimisation.Hubs.EventsHub.AddOrderForecastCalculationProgressUpdateListener((Username, ProgressMessage, Progress) =>
            {
                DSS1_RetailerDriverStockOptimisation.BO.EventHandlers.HandleOrderForecastCalculationProgressUpdate(Username, ProgressMessage, Progress);
                return(false);
            });
            DSS1_RetailerDriverStockOptimisation.Hubs.EventsHub.AddOrderCalculationStartedListener((orderForecastId, user) =>
            {
                DSS1_RetailerDriverStockOptimisation.BO.EventHandlers.HandleOrderCalculationStarted(orderForecastId, user);
                return(false);
            });
            DSS1_RetailerDriverStockOptimisation.DatabaseSeeder databaseSeeder = new DSS1_RetailerDriverStockOptimisation.DatabaseSeeder();
            databaseSeeder.UpdateAuthorizationTables();
            ConfigeAuditTrailManager();
            ServiceLocator.Current.GetInstance <zAppDev.DotNet.Framework.Workflow.ScheduleManager>();
            ServiceLocator.Current.GetInstance <zAppDev.DotNet.Framework.Workflow.WorkflowManager>()
            .Init(typeof(DSS1_RetailerDriverStockOptimisation.DAL.Repository).Assembly);
            DSS1_RetailerDriverStockOptimisation.Hubs.EventsHub.RaiseApplicationStart();
            zAppDev.DotNet.Framework.Mvc.FileHelper.ClearTempData();
        }
        public void ConfigureServices(IAppBuilder app, System.Web.Http.HttpConfiguration config)
        {
            var cacheConfig = CacheManager.Core.ConfigurationBuilder.LoadConfiguration("ServicesCache");
            var builder     = new ContainerBuilder();

            builder
            .RegisterInstance(RabbitMQMessagingLogger.FromConfiguration())
            .SingleInstance();
            builder
            .RegisterInstance(CacheFactory.FromConfiguration <object>(cacheConfig))
            .SingleInstance();
            builder
            .RegisterInstance(CacheFactory.FromConfiguration <object>(CacheManager.Core.ConfigurationBuilder.LoadConfiguration("AppCache")))
            .Named <ICacheManager <object> >("AppCache")
            .SingleInstance();
            builder
            .RegisterInstance(CacheFactory.FromConfiguration <object>(CacheManager.Core.ConfigurationBuilder.LoadConfiguration("SessionStateStorage")))
            .Named <ICacheManager <object> >("SessionStateStorage")
            .SingleInstance();
            builder
            .Register(c => new DSS1_RetailerDriverStockOptimisation.Hubs.EventsHub())
            .As <zAppDev.DotNet.Framework.Hubs.IApplicationHub>().SingleInstance();
            var repoBuilder = new RepositoryBuilder();

            builder
            .Register(c => repoBuilder)
            .As <zAppDev.DotNet.Framework.Data.DAL.IRepositoryBuilder>().SingleInstance();
            builder
            .Register(c => new zAppDev.DotNet.Framework.Workflow.WorkflowManager(repoBuilder))
            .As <zAppDev.DotNet.Framework.Workflow.WorkflowManager>().SingleInstance();
            builder
            .Register(c =>
            {
                var scheduleManager = new zAppDev.DotNet.Framework.Workflow.ScheduleManager(repoBuilder);
                zAppDev.DotNet.Framework.Workflow.ScheduleThread.NumberOfSessions = 0;
                zAppDev.DotNet.Framework.Workflow.ScheduleThread.Manager          = scheduleManager; // Inject Application Schedule Manager
                zAppDev.DotNet.Framework.Workflow.ScheduleThread.StartScheduleThread(HttpContext.Current);
                return(scheduleManager);
            })
            .As <zAppDev.DotNet.Framework.Workflow.ScheduleManager>().SingleInstance();
            builder
            .Register(c => new NHAuditTrailManager())
            .As <INHAuditTrailManager>().SingleInstance();
            builder
            .Register(c =>
            {
                return(new Security.Encryption.EncryptionManager());
            })
            .As <zAppDev.DotNet.Framework.Data.Encryption.Manager.EncryptionManagerBase>()
            .SingleInstance();
            builder
            .Register(c =>
            {
                PerformanceMonitorConfiguration monitorConfiguration = null;
                return(monitorConfiguration);
            })
            .SingleInstance();
            var container = builder.Build();
            var csl       = new AutofacServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => csl);
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
示例#35
0
 public static CacheFactory GetFactory()
 {
     return _instance ?? (_instance = new CacheFactory());
 }
示例#36
0
文件: Args.cs 项目: kittinap/kunnjae
        /// <summary>
        /// Runs the cache analyzer. Performs a statistical analysis and/or a
        /// consistency check and/or an input assertion list check of the cache.
        /// </summary>
        /// <returns>Status code. 0 => success, non-zero => failure</returns>
        internal int RunAnalyzer()
        {
            if (!(m_runStatisticalAnalysis || m_runConsistencyCheck || m_findInputAssertionListAnomalies || m_dumpInputAssertionLists || m_runContentBreakdown))
            {
                WriteError("You must specify to do a statistical analysis (/sa) and/or a consistency check (/cc) and/or an input assertion list check (/ic) and/or an input assertion list dump (/id) and/or a content breakdown (/cb).");
                return(1);
            }

            Console.Error.WriteLine("\nUsing the following json string: " + m_jsonString);

            Possible <ICache, Failure> possibleCache = CacheFactory.InitializeCacheAsync(m_jsonString, default(Guid)).Result;

            if (!possibleCache.Succeeded)
            {
                WriteError("Cache initialization failed: " + possibleCache.Failure.Describe());
                return(1);
            }

            m_cache = possibleCache.Result;

            int returnValue = 1;

            if (m_runStatisticalAnalysis)
            {
                returnValue = DoStatisticalAnalysis();
                if (returnValue != 0)
                {
                    return(returnValue);
                }
            }

            if (m_runConsistencyCheck)
            {
                returnValue = DoConsistencyCheck();
                if (returnValue != 0)
                {
                    return(returnValue);
                }
            }

            if (m_findInputAssertionListAnomalies)
            {
                returnValue = CheckForInputListAnomalies();
                if (returnValue != 0)
                {
                    return(returnValue);
                }
            }

            if (m_dumpInputAssertionLists)
            {
                returnValue = DumpInputAssertionLists();
                if (returnValue != 0)
                {
                    return(returnValue);
                }
            }

            if (m_runContentBreakdown)
            {
                returnValue = DoContentBreakdown();
                if (returnValue != 0)
                {
                    return(returnValue);
                }
            }

            OutputWeakFingerprintsToFile();

            return(returnValue);
        }