public static EventState Create(IStoreProvider storeProvider, ISettings settings) { var savedEvents = new ConcurrentDictionary<string, FixtureState>(); SetFilePath(settings); try { _logger.InfoFormat("Attempting to load file from filePath {0}", PathFileName); var savedEventStates = storeProvider.Read(PathFileName); if (savedEventStates == null) { savedEvents = new ConcurrentDictionary<string, FixtureState>(); } else { savedEvents = (ConcurrentDictionary<string, FixtureState>) JsonConvert.DeserializeObject(savedEventStates, typeof(ConcurrentDictionary<string, FixtureState>)); } } catch (FileNotFoundException) { savedEvents = new ConcurrentDictionary<string, FixtureState>(); } catch (JsonSerializationException jse) { _logger.ErrorFormat("Error during state deserialization {0}. The state file will be removed!", jse); DeleteState(); } var eventState = new EventState(storeProvider) { Events = savedEvents }; return eventState; }
/// <summary> /// 获取直连URL /// </summary> /// <param name="user">用户</param> /// <param name="avatarSizeType"><see cref="AvatarSizeType"/></param> /// <returns></returns> public static string GetAvatarDirectlyUrl(this IUserService userService, IUser user, AvatarSizeType avatarSizeType, bool enableClientCaching = false) { string url = string.Empty; IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); string directlyRootUrl = storeProvider.DirectlyRootUrl; if (!string.IsNullOrEmpty(storeProvider.DirectlyRootUrl)) { url += storeProvider.DirectlyRootUrl; } else { url += WebUtility.ResolveUrl("~/Uploads"); //本机存储时仅允许用~/Uploads/ } if (user == null) { url += "/" + AvatarDirectory + "/avatar_anonymous"; } else { if (avatarSizeType == AvatarSizeType.Original) { if (!user.HasAvatar) { url += "/" + AvatarDirectory + "/" + user.Avatar; } else { url += "/" + GetAvatarRelativePath(user.UserId).Replace(Path.DirectorySeparatorChar, '/') + "/" + user.UserId; } } else { url += "/" + AvatarDirectory + "/" + user.Avatar; } } switch (avatarSizeType) { case AvatarSizeType.Original: url += "_original." + AvatarFileExtension; break; case AvatarSizeType.Big: case AvatarSizeType.Medium: url += "_big." + AvatarFileExtension; break; case AvatarSizeType.Small: case AvatarSizeType.Micro: url += "." + AvatarFileExtension; break; default: url = string.Empty; break; } if (user != null && !enableClientCaching) { url += "?lq=" + DateTime.UtcNow.Ticks; } return(url); }
private EventState(IStoreProvider storeProvider) { _storeProvider = storeProvider; Events = new ConcurrentDictionary<string, FixtureState>(); }
/// <summary> /// Get the provider Instance /// </summary> public static IStoreProvider GetStateProvider(IReliableStateManager manager) { Assert.IsNotNull(manager); return(provider ?? (provider = new PersistentStoreProvider(manager))); }
public GetAggregateModelHandler(IStoreProvider storeProvider) { _storeProvider = storeProvider; }
public ActionResult Create(string spaceKey, string microblogBody, string tenantTypeId = null, long ownerId = 0, string imageUrl = null) { if (string.IsNullOrEmpty(microblogBody)) { return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "内容不能为空!" })); } if (!ValidateContentLength(microblogBody)) { return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "内容不能超过140个字!" })); } //当前用户登录 IUser currentUser = UserContext.CurrentUser; bool isBanned = ModelState.HasBannedWord(); MicroblogEntity entity = MicroblogEntity.New(); entity.Author = currentUser.DisplayName; entity.Body = microblogBody; entity.PostWay = PostWay.Web; entity.TenantTypeId = !string.IsNullOrEmpty(tenantTypeId) ? tenantTypeId : TenantTypeIds.Instance().User(); entity.UserId = currentUser.UserId; entity.OwnerId = ownerId > 0 ? ownerId : currentUser.UserId; if (!authorizer.Microblog_Create(entity.TenantTypeId, entity.OwnerId)) { return(HttpNotFound()); } //判断是否当前有,图片附件 HttpCookie cookie = Request.Cookies["microblog_PhotoExists"]; if (cookie != null && cookie.Value.Trim().ToLower().Equals("true")) { entity.HasPhoto = true; cookie.Value = ""; Response.Cookies.Set(cookie); } if (!string.IsNullOrEmpty(imageUrl)) { //by zhaoyx:获取到的图片地址如果带有“-”字符的话,会被ModelBinder屏蔽掉,导致图片无法加载 imageUrl = Request["imageUrl"]; entity.HasPhoto = true; } bool isSuccess = false; if (!isBanned) { isSuccess = microblogService.Create(entity) > 0; } //by zhengw: if (isSuccess) { //处理imageUrl if (!string.IsNullOrEmpty(imageUrl)) { DownloadRemoteImage(imageUrl, entity.MicroblogId); } //同步微博 var accountBindingService = new AccountBindingService(); foreach (var accountType in accountBindingService.GetAccountTypes(true, true)) { bool isSync = Request.Form.GetBool("sync_" + accountType.AccountTypeKey, false); if (isSync) { var account = accountBindingService.GetAccountBinding(currentUser.UserId, accountType.AccountTypeKey); if (account != null) { var thirdAccountGetter = ThirdAccountGetterFactory.GetThirdAccountGetter(accountType.AccountTypeKey); if (entity.HasPhoto) { byte[] bytes = null; var attachments = attachmentService.GetsByAssociateId(entity.MicroblogId); string fileName = null; if (attachments.Count() > 0) { var attachment = attachments.First(); IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); IStoreFile storeFile = storeProvider.GetResizedImage(attachment.GetRelativePath(), attachment.FileName, new Size(405, 600), Tunynet.Imaging.ResizeMethod.KeepAspectRatio); using (Stream stream = storeFile.OpenReadStream()) { bytes = StreamToBytes(stream); stream.Dispose(); stream.Close(); } fileName = attachment.FriendlyFileName; } thirdAccountGetter.CreatePhotoMicroBlog(account.AccessToken, microblogBody, bytes, fileName, account.Identification); } else { thirdAccountGetter.CreateMicroBlog(account.AccessToken, microblogBody, account.Identification); } } } } if ((int)entity.AuditStatus > (int)(new AuditService().GetPubliclyAuditStatus(MicroblogConfig.Instance().ApplicationId))) { return(Json(new { MessageType = StatusMessageType.Success, MessageContent = "发布成功", id = entity.MicroblogId })); } else { return(Json(new { MessageType = StatusMessageType.Hint, MessageContent = "尚未通过审核,请耐心等待", id = entity.MicroblogId })); } } if (isBanned) { return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "内容中有非法词语!" })); } else { return(Json(new { MessageType = StatusMessageType.Error, MessageContent = "创建失败请联系管理员!" })); } }
public DefaultManager(IDecisionProvider decisionProvider, ISessionProvider sessionProvider, IStoreProvider storeProvider) { _decisionProvider = decisionProvider; _sessionProvider = sessionProvider; _iStoreProvider = storeProvider; }
/// <summary> /// 构造器 /// </summary> /// <param name="attachmentRepository"></param> /// <param name="tenantAttachmentSettings"></param> /// <param name="storeProvider"></param> public AttachmentService(IAttachmentRepository <Attachment> attachmentRepository, TenantAttachmentSettings tenantAttachmentSettings, IStoreProvider storeProvider) : base(attachmentRepository, tenantAttachmentSettings, storeProvider) { }
/// <inheritdoc /> public Store(IStoreProvider storeProvider) { inner = storeProvider.Get <T>(); }
public MetricsStorage(IStoreProvider storeProvider) { Preconditions.CheckNotNull(storeProvider, nameof(storeProvider)); this.dataStore = Preconditions.CheckNotNull(storeProvider.GetEntityStore <Guid, IEnumerable <Metric> >("Metrics"), "dataStore"); }
public BlockProducer(ForkChoice forkChoice, IStoreProvider storeProvider) { _forkChoice = forkChoice; _storeProvider = storeProvider; }
public static ulong GetNextSequenceValueViaCASWithRetries(IStoreProvider provider, string key, int increment, int tryCount) { return(getNextSequenceValueViaCASRet(provider, key, increment, tryCount)); }
/// <summary> /// Expose the only instance of runtime /// </summary> public static IInsightRuntime GetInstance(ILogProvider logProvider, IStoreProvider storeProvider, Config config, IPerformanceSessionManager perfSessionMgr, ITaskRunner runner, CancellationToken token, bool isTest = false) { return(new DefaultInsightRuntime(logProvider, storeProvider, config, perfSessionMgr, runner, isTest, token)); }
public DataController(IStoreProvider provider) { Provider = provider; }
public SequentialStoreTest(TestRocksDbStoreProvider rocksDbStoreProvider) { this.storeProvider = new StoreProvider(rocksDbStoreProvider); }
public static void SetCurrentProvider(IStoreProvider storeProvider) { Current = storeProvider; }
/// <summary> /// 可设置repository的构造函数(主要用于测试用例) /// </summary> /// <param name="attachmentRepository">附件仓储</param> /// <param name="tenantAttachmentSettings">租户附件设置</param> /// <param name="storeProvider">文件存储Provider</param> public AttachmentService(IAttachmentRepository <T> attachmentRepository, TenantAttachmentSettings tenantAttachmentSettings, IStoreProvider storeProvider) { this.attachmentRepository = attachmentRepository; this.TenantAttachmentSettings = tenantAttachmentSettings; this.StoreProvider = storeProvider; }
public Repository(IStoreProvider storeProvider) { _storeProvider = storeProvider; }
public SequentialStoreTest() { this.storeProvider = new StoreProvider(new InMemoryDbStoreProvider()); }
public EntityStoreTest() { this.storeProvider = new StoreProvider(new InMemoryDbStoreProvider()); }
/// <summary> /// 获取背景图 /// </summary> /// <param name="ownerId">拥有者Id</param> /// <param name="presentAreaKey">呈现区域标识</param> /// <returns></returns> public IStoreFile GetBackgroundImage(string presentAreaKey, long ownerId) { IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); return(storeProvider.GetFile(GetBackgroundImageRelativePath(presentAreaKey, ownerId), GetBackgroundImageFileName(ownerId))); }
protected override void Load(ContainerBuilder builder) { // ISerde<ModuleSet> builder.Register( c => new ModuleSetSerde( new Dictionary <string, Type> { { DockerType, typeof(DockerModule) } })) .As <ISerde <ModuleSet> >() .SingleInstance(); // ISerde<DeploymentConfig> builder.Register( c => { ISerde <DeploymentConfig> serde = new TypeSpecificSerDe <DeploymentConfig>(DeploymentConfigTypeMapping); return(serde); }) .As <ISerde <DeploymentConfig> >() .SingleInstance(); // ISerde<DeploymentConfigInfo> builder.Register( c => { ISerde <DeploymentConfigInfo> serde = new TypeSpecificSerDe <DeploymentConfigInfo>(DeploymentConfigTypeMapping); return(serde); }) .As <ISerde <DeploymentConfigInfo> >() .SingleInstance(); // Detect system environment builder.Register(c => new SystemEnvironment()) .As <ISystemEnvironment>() .SingleInstance(); // IRocksDbOptionsProvider // For EdgeAgent, we don't need high performance from RocksDb, so always turn off optimizeForPerformance builder .Register(c => new RocksDbOptionsProvider( c.Resolve <ISystemEnvironment>(), false, this.storageTotalMaxWalSize, this.storageMaxManifestFileSize, this.storageMaxOpenFiles, this.storageLogLevel)) .As <IRocksDbOptionsProvider>() .SingleInstance(); if (!this.usePersistentStorage && this.useBackupAndRestore) { // Backup and restore serialization builder.Register(c => new ProtoBufDataBackupRestore()) .As <IDataBackupRestore>() .SingleInstance(); } // IDbStoreProvider builder.Register( async c => { var loggerFactory = c.Resolve <ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(typeof(AgentModule)); if (this.usePersistentStorage) { // Create partition for mma var partitionsList = new List <string> { "moduleState", "deploymentConfig" }; try { IDbStoreProvider dbStoreprovider = DbStoreProvider.Create( c.Resolve <IRocksDbOptionsProvider>(), this.storagePath, partitionsList); logger.LogInformation($"Created persistent store at {this.storagePath}"); return(dbStoreprovider); } catch (Exception ex) when(!ExceptionEx.IsFatal(ex)) { logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store."); IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c); return(dbStoreProvider); } } else { logger.LogInformation($"Using in-memory store"); IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c); return(dbStoreProvider); } }) .As <Task <IDbStoreProvider> >() .SingleInstance(); // Task<IStoreProvider> builder.Register(async c => { var dbStoreProvider = await c.Resolve <Task <IDbStoreProvider> >(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); return(storeProvider); }) .As <Task <IStoreProvider> >() .SingleInstance(); // IEntityStore<string, ModuleState> builder.Register(async c => { IStoreProvider storeProvider = await c.Resolve <Task <IStoreProvider> >(); return(storeProvider.GetEntityStore <string, ModuleState>("moduleState")); }) .As <Task <IEntityStore <string, ModuleState> > >() .SingleInstance(); // IEntityStore<string, DeploymentConfigInfo> builder.Register(async c => { IStoreProvider storeProvider = await c.Resolve <Task <IStoreProvider> >(); return(storeProvider.GetEntityStore <string, string>("deploymentConfig")); }) .As <Task <IEntityStore <string, string> > >() .SingleInstance(); // IRestartManager builder.Register(c => new RestartPolicyManager(this.maxRestartCount, this.coolOffTimeUnitInSeconds)) .As <IRestartPolicyManager>() .SingleInstance(); // IPlanner builder.Register( async c => { var commandFactory = c.Resolve <Task <ICommandFactory> >(); var entityStore = c.Resolve <Task <IEntityStore <string, ModuleState> > >(); var policyManager = c.Resolve <IRestartPolicyManager>(); return(new HealthRestartPlanner(await commandFactory, await entityStore, this.intensiveCareTime, policyManager) as IPlanner); }) .As <Task <IPlanner> >() .SingleInstance(); // IPlanRunner builder.Register(c => new OrderedRetryPlanRunner(this.maxRestartCount, this.coolOffTimeUnitInSeconds, SystemTime.Instance)) .As <IPlanRunner>() .SingleInstance(); // IEncryptionDecryptionProvider builder.Register( async c => { IEncryptionProvider provider = await this.workloadUri.Map( async uri => { IEncryptionProvider encryptionProvider = await EncryptionProvider.CreateAsync( this.storagePath, uri, this.workloadApiVersion.Expect(() => new InvalidOperationException("Missing workload API version")), Constants.EdgeletClientApiVersion, this.moduleId, this.moduleGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Constants.EdgeletInitializationVectorFileName); return(encryptionProvider); }).GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance)); return(provider); }) .As <Task <IEncryptionProvider> >() .SingleInstance(); // IAvailabilityMetric builder.Register(c => new DeploymentMetrics(c.Resolve <IMetricsProvider>(), this.storagePath)) .As <IDeploymentMetrics>() .SingleInstance(); // Task<Agent> builder.Register( async c => { var configSource = c.Resolve <Task <IConfigSource> >(); var environmentProvider = c.Resolve <Task <IEnvironmentProvider> >(); var planner = c.Resolve <Task <IPlanner> >(); var planRunner = c.Resolve <IPlanRunner>(); var reporter = c.Resolve <IReporter>(); var moduleIdentityLifecycleManager = c.Resolve <IModuleIdentityLifecycleManager>(); var deploymentConfigInfoSerde = c.Resolve <ISerde <DeploymentConfigInfo> >(); var deploymentConfigInfoStore = await c.Resolve <Task <IEntityStore <string, string> > >(); var encryptionProvider = c.Resolve <Task <IEncryptionProvider> >(); var availabilityMetric = c.Resolve <IDeploymentMetrics>(); return(await Agent.Create( await configSource, await planner, planRunner, reporter, moduleIdentityLifecycleManager, await environmentProvider, deploymentConfigInfoStore, deploymentConfigInfoSerde, await encryptionProvider, availabilityMetric)); }) .As <Task <Agent> >() .SingleInstance(); base.Load(builder); }
public EntityStoreTest(TestRocksDbStoreProvider rocksDbStoreProvider) { this.storeProvider = new StoreProvider(rocksDbStoreProvider); }
public RoleStore(IdentityErrorDescriber describer, IStoreProvider connectionProvider) : base(describer, connectionProvider) { }
private EventState(IStoreProvider storeProvider) { _storeProvider = storeProvider; Events = new ConcurrentDictionary <string, FixtureState>(); }
/// <summary> /// 获取用户头像 /// </summary> /// <param name="userId">用户Id</param> /// <param name="avatarSizeType">头像尺寸类型</param> /// <returns></returns> public static IStoreFile GetAvatar(this IUserService userService, long userId, AvatarSizeType avatarSizeType) { IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); return(storeProvider.GetFile(GetAvatarRelativePath(userId), GetAvatarFileName(userId, avatarSizeType))); }
/// <summary> /// 重置缩略图 /// </summary> /// <param name="path"></param> /// <param name="settings"></param> private void ResetThumbnails(string path, TenantAttachmentSettings settings) { if (settings.ImageSizeTypes == null || settings.ImageSizeTypes.Count == 0) { return; } if (!Directory.Exists(path)) { return; } List <string> files = Directory.GetFiles(path).ToList(); IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); List <string> originalList = new List <string>(); List <string> fileList = new List <string>(); foreach (var file in files) { string suffix = "gif,jpg,png,bmp,jpeg"; bool isContinue = true; foreach (var item in suffix.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (file.ToLower().EndsWith(item)) { isContinue = false; break; } } if (isContinue) { continue; } string fileName = GetUploadFileName(file); if (originalList.Contains(fileName)) { continue; } originalList.Add(fileName); foreach (var item in settings.ImageSizeTypes) { string name = Path.Combine(path, storeProvider.GetSizeImageName(fileName, item.Size, item.ResizeMethod)); if (!fileList.Contains(name)) { fileList.Add(name); } if (files.Contains(name)) { continue; } try { storeProvider.GetResizedImage(path, fileName, item.Size, item.ResizeMethod); } catch (Exception) { } } } //删除无用数据 foreach (var file in files) { string name = GetFileNameWistOutPath(file); if (!fileList.Contains(file) && GetUploadFileName(file) != name && GetOriginalFileName(file) != name) { System.IO.File.Delete(file); } } string[] paths = Directory.GetDirectories(path); foreach (var item in paths) { ResetThumbnails(item, settings); } }
/// <summary> /// 根据配置重置Logo /// </summary> /// <param name="path"></param> /// <param name="settings"></param> private void ResetLogos(string path, TenantLogoSettings settings) { if (!Directory.Exists(path)) { return; } if (settings == null || settings.ImageSizeTypes == null || settings.ImageSizeTypes.Count == 0) { return; } IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); string[] files = Directory.GetFiles(path); List <string> originalList = new List <string>(); List <string> fileList = new List <string>(); foreach (var file in files) { if (file.EndsWith(".db")) { continue; } string fileName = GetUploadFileName(file); if (originalList.Contains(fileName)) { continue; } originalList.Add(fileName); foreach (var type in settings.ImageSizeTypes.Values) { string name = storeProvider.GetSizeImageName(GetFileNameWistOutPath(file), type.Key, type.Value); string filePath = Path.Combine(path, name); if (!fileList.Contains(filePath)) { fileList.Add(filePath); } if (files.Contains(filePath)) { continue; } try { storeProvider.GetResizedImage(path, GetUploadFileName(filePath), type.Key, type.Value); } catch (Exception) { } } } //删除无用数据 foreach (var file in files) { string name = GetFileNameWistOutPath(file); if (!fileList.Contains(file) && GetUploadFileName(file) != name && GetOriginalFileName(file) != name) { System.IO.File.Delete(file); } } string[] paths = Directory.GetDirectories(path); foreach (var item in paths) { ResetLogos(item, settings); } }
public ArticleController(IArticleProvider articleProvider, IStoreProvider storeProvider) { _articleProvider = articleProvider; _storeProvider = storeProvider; }