public void CanGetInstance() { var connectionInstance = new Mock<DbConnection>().Object; var dbFactory = new Mock<DbProviderFactory>(); dbFactory.Setup(x => x.CreateConnection()).Returns(connectionInstance).Verifiable(); var storageFactory = new StorageFactory(dbFactory.Object); var result = storageFactory.CreateConnection(); Assert.Same(connectionInstance, result); dbFactory.VerifyAll(); }
private static bool TestClient(DataStorageType storageType) { var storageFactory = new StorageFactory<IImageSource>(new AutoFacIocContainer()); var storage = storageFactory.Resolve(storageType); var data = File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"); var imageSource = storage.Save(data, ".png", "Joshs Photos"); var sourceData = storage.Retrieve(imageSource.Source); var thumbnailData = storage.Retrieve(imageSource.Thumbnail); File.WriteAllBytes(@"C:\temp\source.jpg", sourceData); File.WriteAllBytes(@"C:\temp\thumbnail.jpg", thumbnailData); return storage.Delete(imageSource.Source); }
public void CanGetInstance() { var connectionInstance = new Mock<DbConnection>().Object; var transactionInstance = new Mock<DbTransaction>().Object; var command = new Mock<DbCommand>(); command.SetupSet(x => x.CommandText = "Test").Verifiable(); command.SetupSet(x => x.Connection = connectionInstance).Verifiable(); command.SetupSet(x => x.Transaction = transactionInstance).Verifiable(); var commandInstance = command.Object; var dbFactory = new Mock<DbProviderFactory>(); dbFactory.Setup(x => x.CreateCommand()).Returns(commandInstance).Verifiable(); var storageFactory = new StorageFactory(dbFactory.Object); var result = storageFactory.CreateCommand("Test", connectionInstance, transactionInstance); Assert.Same(commandInstance, result); command.VerifyAll(); dbFactory.VerifyAll(); }
public void ProcessRequest(HttpContext context) { if (_checkAuth && !SecurityContext.IsAuthenticated) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return; } var storage = StorageFactory.GetStorage(CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture), _module); var path = _path; var header = context.Request[Constants.QUERY_HEADER] ?? ""; var auth = context.Request[Constants.QUERY_AUTH]; var storageExpire = storage.GetExpire(_domain); if (storageExpire != TimeSpan.Zero && storageExpire != TimeSpan.MinValue && storageExpire != TimeSpan.MaxValue || !string.IsNullOrEmpty(auth)) { var expire = context.Request[Constants.QUERY_EXPIRE]; if (string.IsNullOrEmpty(expire)) { expire = storageExpire.TotalMinutes.ToString(CultureInfo.InvariantCulture); } var validateResult = EmailValidationKeyProvider.ValidateEmailKey(path + "." + header + "." + expire, auth ?? "", TimeSpan.FromMinutes(Convert.ToDouble(expire))); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return; } } if (!storage.IsFile(_domain, path)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } var headers = header.Length > 0 ? header.Split('&') : new string[] { }; const int bigSize = 5 * 1024 * 1024; if (storage.IsSupportInternalUri && bigSize < storage.GetFileSize(_domain, path)) { var uri = storage.GetInternalUri(_domain, path, TimeSpan.FromMinutes(15), headers); context.Response.Cache.SetAllowResponseInBrowserHistory(false); context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.Redirect(uri.ToString()); return; } string encoding = null; if (storage is DiscDataStore && storage.IsFile(_domain, path + ".gz")) { path += ".gz"; encoding = "gzip"; } using (var stream = storage.GetReadStream(_domain, path)) { stream.StreamCopyTo(context.Response.OutputStream); } foreach (var h in headers) { if (h.StartsWith("Content-Disposition")) { context.Response.Headers["Content-Disposition"] = h.Substring("Content-Disposition".Length + 1); } else if (h.StartsWith("Cache-Control")) { context.Response.Headers["Cache-Control"] = h.Substring("Cache-Control".Length + 1); } else if (h.StartsWith("Content-Encoding")) { context.Response.Headers["Content-Encoding"] = h.Substring("Content-Encoding".Length + 1); } else if (h.StartsWith("Content-Language")) { context.Response.Headers["Content-Language"] = h.Substring("Content-Language".Length + 1); } else if (h.StartsWith("Content-Type")) { context.Response.Headers["Content-Type"] = h.Substring("Content-Type".Length + 1); } else if (h.StartsWith("Expires")) { context.Response.Headers["Expires"] = h.Substring("Expires".Length + 1); } } context.Response.ContentType = MimeMapping.GetMimeMapping(path); if (encoding != null) { context.Response.Headers["Content-Encoding"] = encoding; } }
private static IDataStore GetDataStore() { return(StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "userPhotos")); }
private static void Main(string[] args) { IConfigFileClient <JObject, JToken> configFileLocal = new JSONConfigFileClient(); try { configFileLocal.Load(MagicStringEnumerator.DefaultLocalConfigPath); Log.Instance?.Info($"Configuration file {MagicStringEnumerator.DefaultLocalConfigPath} loaded."); } catch (Exception ex) { Log.Instance?.Error($"{MagicStringEnumerator.DefaultLocalConfigPath}: {ex.Message}"); CleanExit(); } var ip = configFileLocal.GetAddress(); var port = configFileLocal.GetPort(); Log.Instance?.Info($"Server ip: {ip}"); Log.Instance?.Info($"Server port: {port}"); AppDomain.CurrentDomain.ProcessExit += (o, e) => { CleanExit(); }; client = new HalClient(ip, port); new Thread(async() => { await client.StartAsync(); }).Start(); IPluginMaster pluginMaster = new PluginMasterBasePlugin(); /* * The plugin manager will manage and schedule plugins * * when a plugin need to be executed, PluginManager will launch what the plugin needs and output the result * where desired above. */ APluginManager pluginManager = new ScheduledPluginManager(pluginMaster); // We only want to configure all the plugins when the client has received all the informations and plugins client.OnReceiveDone += async(o, e) => { /* * Here we instanciate the configuration file * Its a JSON format file. * * All HAL's client configuration is here. */ IConfigFileClient <JObject, JToken> configFile = new JSONConfigFileClient(); try { configFile.Load(MagicStringEnumerator.DefaultConfigPath); Log.Instance?.Info($"Configuration file {MagicStringEnumerator.DefaultConfigPath} loaded."); } catch (Exception ex) { Log.Instance?.Error($"{MagicStringEnumerator.DefaultConfigPath}: {ex.Message}"); receiveError = true; CleanExit(); } foreach (var storageName in configFile.GetStorageNames()) { var storage = StorageFactory.CreateStorage(storageName); if (storage is StorageServerFile) { (storage as StorageServerFile).StreamWriter = client.StreamWriter; } else if (storage is StorageLocalFile) { (storage as StorageLocalFile).SavePath = configFile.GetSavePath(); } storages.Add(storage); Log.Instance?.Info($"Storage \"{storageName}\" added."); } await pluginManager.UnscheduleAllPluginsAsync(pluginMaster.Plugins); pluginMaster.RemoveAllPlugins(); /* * A connection string is needed if you want to access a database * * if none is specified, then it will do nothing and return null. */ var connectionStrings = configFile.GetDataBaseConnectionStrings(); var databases = storages.Where(s => s is IDatabaseStorage).ToArray(); for (var i = 0; i < connectionStrings?.Length; ++i) { var db = databases[i]; var connectionString = connectionStrings[i]; db.Init(connectionString); Log.Instance?.Info($"Database \"{db}\" with connection string \"{connectionString}\""); } /* * Here pluginMaster will receive some customs user specifications, * like new extensions or intepreter. */ configFile.SetScriptExtensionsConfiguration(pluginMaster); configFile.SetInterpreterNameConfiguration(pluginMaster); /* * All the plugins in the directory "plugins" will be loaded and added to the plugin master */ foreach (var file in Directory.GetFiles(MagicStringEnumerator.DefaultPluginPath)) { pluginMaster.AddPlugin(file); } /* * Then the configuration of all of the plugins is set. */ configFile.SetPluginsConfiguration(pluginMaster.Plugins); configFileLocal.SetPluginsConfiguration(pluginMaster.Plugins); configFileLocal.SetInterpreterNameConfiguration(pluginMaster); /* * An event is added when the plugin's execution is finished to save it where the user specified above. */ var savePath = configFile.GetSavePath(); foreach (var plugin in pluginMaster.Plugins) { plugin.OnExecutionFinished += async(o, e) => { foreach (var storage in storages) { try { var code = await storage.Save(e.Plugin, e.Result); if (code == StorageCode.Failed) { Log.Instance?.Error("Storage failed."); } } catch (Exception ex) { Log.Instance?.Error($"Storage failed: {ex.Message}"); } } } } ; /* * All the plugins are then schelduled to be launched when needed. */ pluginManager.SchedulePlugins(pluginMaster.Plugins); Log.Instance?.Info("Configuration reloaded."); }; while (!receiveError) { Thread.Sleep(100); } CleanExit(); } }
public IDataStore GetStoreTemplate() { return(StorageFactory.GetStorage(string.Empty, FileConstant.StorageTemplate)); }
/// <summary> /// Saves the editor control value. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void DataEditorControl_OnSave(EventArgs e) { string fileUrl = string.Empty; string bucketName = string.Empty; var postedFile = this.m_Control.PostedFile; if (postedFile != null) { StorageFactory factory = new StorageFactory(m_Control.Options.AccessKey, m_Control.Options.SecretKey); fileUrl = factory.CreateObject(bucketName, postedFile.InputStream, postedFile.ContentType, postedFile.FileName); } // save the value of the control depending on whether a new file is uploaded this.Data.Value = string.IsNullOrEmpty(fileUrl) ? m_Control.FileUrl : fileUrl; }
private static IDataStore GetStore() { return(StorageFactory.GetStorage("-1", "common_static")); }
public static void Rollback() { StorageFactory.GetStorage().Clear(); }
public void CanGetInstance() { var parameterInstance = new Mock<DbParameter>().Object; var dbFactory = new Mock<DbProviderFactory>(); dbFactory.Setup(x => x.CreateParameter()).Returns(parameterInstance).Verifiable(); var storageFactory = new StorageFactory(dbFactory.Object); var result = storageFactory.CreateParameter(); Assert.Same(parameterInstance, result); dbFactory.VerifyAll(); }
public void CanGetInstance() { var parameter = new Mock<DbParameter>(); parameter.SetupSet(x => x.DbType = DbType.DateTime).Verifiable(); parameter.SetupSet(x => x.ParameterName = "Test").Verifiable(); var parameterInstance = parameter.Object; var dbFactory = new Mock<DbProviderFactory>(); dbFactory.Setup(x => x.CreateParameter()).Returns(parameterInstance).Verifiable(); var storageFactory = new StorageFactory(dbFactory.Object); var result = storageFactory.CreateParameter("Test", DbType.DateTime); Assert.Same(parameterInstance, result); parameter.VerifyAll(); dbFactory.VerifyAll(); }
public CloudTableTests() { Factory = new StorageFactory(); }
public CloudBlockBlobTests() { Factory = new StorageFactory(); Container = Factory.CreateBlobContainer("UseDevelopmentStorage=true", "cloud-block-blob-tests"); Blob = Container.CreateBlockBlob(Guid.NewGuid().ToString("D") + "/" ); }
public static IDataStore GetDataStoreForCkImages(int tenant) { return(StorageFactory.GetStorage(null, tenant.ToString(CultureInfo.InvariantCulture), "fckuploaders", null)); }
protected virtual IDataStore GetDataStore() { return(StorageFactory.GetStorage(webConfigPath, _tenant.ToString(), "backup", null)); }
public void StorageFactory_returns_user_storage_instance() { var store = StorageFactory <SimpleEntity> .UserStorage("test", _cache); Assert.That(store, Is.Not.Null, "Store is null?"); }
public static void FCKEditingComplete(string domain, string itemID, string editedHtml, bool isEdit) { if (editedHtml == null) { throw new ArgumentNullException("editedHtml"); } var isExistsFolder = false; string folderID; if (isEdit) { folderID = FCKUploadsDBManager.GetFolderID(domain, itemID); if (String.IsNullOrEmpty(folderID)) { folderID = GetCurrentFolderID(domain); } else { isExistsFolder = true; } } else { folderID = GetCurrentFolderID(domain); } var store = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "fckuploaders"); var existsFileList = new List <Uri>(store.ListFiles(domain, folderID + "/", "*", false)).ConvertAll(uri => uri.ToString()); var usingUploadFiles = new List <string>(); var deleteFiles = new List <string>(); foreach (var file in new List <string>(existsFileList)) { if (editedHtml.IndexOf(file, StringComparison.InvariantCultureIgnoreCase) >= 0 || HttpUtility.UrlDecode(editedHtml).IndexOf(file, StringComparison.InvariantCultureIgnoreCase) >= 0 || HttpUtility.HtmlDecode(editedHtml).IndexOf(file, StringComparison.InvariantCultureIgnoreCase) >= 0) { usingUploadFiles.Add(file); } else { deleteFiles.Add(file); } //HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(string.Format("//*[contains(@src,'{0}')]", file.ToLowerInvariant())); //if (nodes != null) // usingUploadFiles.Add(file); //else // deleteFiles.Add(file); } foreach (var df in deleteFiles) { var fileName = Path.GetFileName(df); store.Delete(domain, folderID + "/" + fileName); } if (usingUploadFiles.Count > 0 && !isExistsFolder) { FCKUploadsDBManager.SetUploadRelations(domain, folderID, itemID); } else if (usingUploadFiles.Count == 0) { FCKUploadsDBManager.RemoveUploadRelation(domain, folderID, itemID); } FCKRemoveTempUploads(domain, folderID, isEdit); }
private static IDataStore GetStorageWithoutQuota(int tennant, string module) { return(StorageFactory.GetStorage(null, tennant.ToString(), module, null)); }
public CloudBlobContainerTests() { Factory = new StorageFactory(); Container = Factory.CreateBlobContainer("UseDevelopmentStorage=true", "cloud-block-blob-tests"); }
private void DoBackupStorage(IDataWriteOperator writer, List <IGrouping <string, BackupFileInfo> > fileGroups) { Logger.Debug("begin backup storage"); foreach (var group in fileGroups) { var filesProcessed = 0; var filesCount = group.Count(); foreach (var file in group) { var storage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), group.Key); var file1 = file; ActionInvoker.Try(state => { var f = (BackupFileInfo)state; using (var fileStream = storage.GetReadStream(f.Domain, f.Path)) { var tmp = Path.GetTempFileName(); try { using (var tmpFile = File.OpenWrite(tmp)) { fileStream.CopyTo(tmpFile); } writer.WriteEntry(file1.GetZipKey(), tmp); } finally { if (File.Exists(tmp)) { File.Delete(tmp); } } } }, file, 5, error => Logger.WarnFormat("can't backup file ({0}:{1}): {2}", file1.Module, file1.Path, error)); SetCurrentStepProgress((int)(++filesProcessed * 100 / (double)filesCount)); } } var restoreInfoXml = new XElement( "storage_restore", fileGroups .SelectMany(group => group.Select(file => (object)file.ToXElement())) .ToArray()); var tmpPath = Path.GetTempFileName(); using (var tmpFile = File.OpenWrite(tmpPath)) { restoreInfoXml.WriteTo(tmpFile); } writer.WriteEntry(KeyHelper.GetStorageRestoreInfoZipKey(), tmpPath); File.Delete(tmpPath); Logger.Debug("end backup storage"); }
private void EnsureAmazonS3Connection() { if (_factory == null) _factory = new StorageFactory(_config.AccessKey, _config.SecretKey); }
private static IDataStore GetStorage() { var tenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId; return(StorageFactory.GetStorage(tenantId.ToString(CultureInfo.InvariantCulture), "talk")); }
private static IKeyValueStorage <KeyOf <string>, ValueOf <byte[]> > GetByteArrayStorage() { var factory = new StorageFactory(); return(factory.CreateRadixTreeByteArrayStorage <string>(RadixTreeStorageSettings.Default())); }
public PartitionedRegJob(Config config, Storage storage, StorageFactory factory, CollectorHttpClient client) : base(config, storage, "partitionedreg") { _factory = factory; _client = client; }
public void InvalidStorageFactory() { StorageFactory storageFactory = new StorageFactory(); Assert.Throws <InvalidOperationException>(() => storageFactory.CreateStorage("Gagaguga", "Pesho")); }
public static IDataStore GetStore(bool currentTenant = true) { return(StorageFactory.GetStorage(currentTenant ? TenantProvider.CurrentTenantID.ToString() : string.Empty, FileConstant.StorageModule)); }
public virtual Vector3Int GetPosition() { var stockpileLoc = StorageFactory.GetStockpilePosition(Job.Owner); if (WalkingTo == StorageType.Crate) { if (!StorageFactory.CrateLocations.ContainsKey(Job.Owner)) { StorageFactory.CrateLocations.Add(Job.Owner, new Dictionary <Vector3Int, CrateInventory>()); } if (!LastCratePosition.Contains(GoalStoring.ClosestCrate) && StorageFactory.CrateLocations[Job.Owner].ContainsKey(GoalStoring.ClosestCrate)) { CurrentCratePosition = GoalStoring.ClosestCrate; } else { var locations = GetCrateSearchPosition().SortClosestPositions(StorageFactory.CrateLocations[Job.Owner].Keys.ToList()); foreach (var location in locations) { if (!LastCratePosition.Contains(location)) { CurrentCratePosition = location; break; } } // we have checked every crate, they are all full. // put items in stockpile. if (LastCratePosition.Contains(CurrentCratePosition)) { WalkingTo = StorageType.Stockpile; if (stockpileLoc.Position == Vector3Int.invalidPos || stockpileLoc.Position == default(Vector3Int)) { CurrentCratePosition = Job.Owner.Banners.FirstOrDefault().Position; } else { CurrentCratePosition = stockpileLoc.Position; } } } } if (CurrentCratePosition == Vector3Int.invalidPos || CurrentCratePosition == default(Vector3Int)) { WalkingTo = StorageType.Stockpile; if (stockpileLoc.Position == Vector3Int.invalidPos || stockpileLoc.Position == default(Vector3Int)) { CurrentCratePosition = Job.Owner.Banners.FirstOrDefault().Position; } else { CurrentCratePosition = stockpileLoc.Position; } } return(CurrentCratePosition); }
public static IDataStore GetDataStore(int id_tenant) { return(StorageFactory.GetStorage(null, id_tenant.ToString(CultureInfo.InvariantCulture), Defines.ModuleName, HttpContext.Current)); }
public static IDataStore GetDataStore(int tenant) { return(StorageFactory.GetStorage(tenant.ToString(CultureInfo.InvariantCulture), Defines.MODULE_NAME)); }
public void Setup() { this.storageFactory = new StorageFactory(); this.storageMaster = new StorageMaster(); }
public static IDataStore GetDataStoreForAttachments(int tenant) { return(StorageFactory.GetStorage(null, tenant.ToString(CultureInfo.InvariantCulture), "mailaggregator", null)); }
public override bool Save() { StorageFactory.ClearCache(); dataStoreConsumer = null; return(base.Save()); }
public static void Save() { StorageFactory.GetStorage().Commit(); }
public static ShouldIncludeRegistrationPackage GetShouldIncludeRegistrationPackage(StorageFactory semVer2StorageFactory) { // If SemVer 2.0.0 storage is disabled, put SemVer 2.0.0 registration in the legacy storage factory. In no // case should a package be completely ignored. That is, if a package is SemVer 2.0.0 but SemVer 2.0.0 // storage is not enabled, our only choice is to put SemVer 2.0.0 packages in the legacy storage. if (semVer2StorageFactory == null) { return((k, u, g) => true); } return((k, u, g) => !NuGetVersionUtility.IsGraphSemVer2(k.Version, u, g)); }
public void TestIfStorageFactortThrows() { var fac = new StorageFactory(); Assert.Throws <InvalidOperationException>(() => fac.CreateStorage("Metro", "Billa")); }
public FileEngine(String dbId, int tenantID) { projectsStore = StorageFactory.GetStorage(tenantID.ToString(CultureInfo.InvariantCulture), dbId); }
public DataStoreBackupStorage(StorageFactory storageFactory) { StorageFactory = storageFactory; }
public SynchronizersController(string path) { storageFactory = new StorageFactory(TypesLoader.Load(path)); // load links // start sync }
/// <summary> /// constructor with type /// </summary> /// <param name="type"></param> public StorageAmazon(StorageFactory.StorageType type) { StorageType = type; }
public GlobalStore(StorageFactory storageFactory, TenantManager tenantManager) { StorageFactory = storageFactory; TenantManager = tenantManager; }
/// <summary> /// constructor with type /// </summary> /// <param name="type"></param> public StorageAzure(StorageFactory.StorageType type) { StorageType = type; }
public IDataStore GetStore(bool currentTenant = true) { return(StorageFactory.GetStorage(currentTenant ? TenantManager.GetCurrentTenant().TenantId.ToString() : string.Empty, FileConstant.StorageModule)); }
/// <summary> /// default constructor /// </summary> /// <param name="type"></param> public StorageLocal(StorageFactory.StorageType type) { StorageType = type; }
public MethodPerformanceAdvisor() { GlimpsePerformanceConfiguration = new GlimpsePerformanceConfiguration(); ConversionHelper = new ConversionHelper(); StorageFactory = new StorageFactory(); }