private string GetScanPreviewFilePath(Scan scan) { if (!scan.ExtensionWithDot.Equals(".jpg", StringComparison.OrdinalIgnoreCase)) { return(string.Empty); } var previewsStoragePath = string.Format("{0}{1}", FileStorageProvider.GetCommonPathToScans(), "previews"); if (!Directory.Exists(previewsStoragePath)) { Directory.CreateDirectory(previewsStoragePath); } var previewPath = Path.Combine(previewsStoragePath, scan.LocalFileName); if (!System.IO.File.Exists(previewPath)) { var fileByteStream = new FileStream(Path.Combine(FileStorageProvider.GetCommonPathToScans(), scan.ClaimId.ToString(), scan.LocalFileName), FileMode.Open, FileAccess.Read); var imagesHelper = new ImagesHelper(); imagesHelper.GetFilePreview(fileByteStream, previewPath); } return(previewPath); }
/// <summary> /// Updates the photo. /// </summary> /// <param name="productId">The product id.</param> protected void UpdateProductPhotos(Guid productId) { foreach (var productPhoto in UploadedProductPhoto) { productPhoto.ProductId = productId; DataManager.ProductPhoto.Save(productPhoto); } var photos = labitecImageGallery.Photos; foreach (var photo in photos) { var productPhoto = DataManager.ProductPhoto.Select(photo.PhotoId); if (photo.IsDeleted) { FileStorageProvider.Delete(BusinessLogicLayer.Configuration.Settings.ProductImageAbsolutePath(CurrentUser.Instance.SiteID), productPhoto.Photo); FileStorageProvider.Delete(BusinessLogicLayer.Configuration.Settings.ProductImageAbsolutePath(CurrentUser.Instance.SiteID), productPhoto.Preview); DataManager.ProductPhoto.Delete(photo.PhotoId); } else { DataManager.ProductPhoto.Save(productPhoto.Id, productPhoto.ProductId, productPhoto.Photo, productPhoto.Preview, photo.Description, photo.IsMain); } } }
private void ShowResult(FileStorageProvider provider, string resultMessage, OperationsGroup operationsGroup = null) { switch (provider) { case FileStorageProvider.Local: pnlResultLocal.Visible = true; pnlErrorLocal.Visible = false; litResultsLocal.Text = resultMessage; if (operationsGroup != null) { litResultsLocal.Text += operationsGroup.ToString(); } break; case FileStorageProvider.AzureStorageBlobs: pnlResultAzure.Visible = true; pnlErrorAzure.Visible = false; litResultsAzure.Text = resultMessage; if (operationsGroup != null) { litResultsAzure.Text += operationsGroup.ToString(); } break; } }
public async Task <IdentityAccount> GetAccount() { try { ScatterSharp.Core.Api.Network network = new ScatterSharp.Core.Api.Network() { blockchain = ScatterConstants.Blockchains.EOSIO, host = "jungle3.cryptolions.io", port = 443, chainId = "2a02a0053e5a8cf73a56ba0fda11e4d92e0238a4a2aa74fccf46d5a910746840" }; var fileStorage = new FileStorageProvider(Application.persistentDataPath + "/scatterapp.dat"); using (var scatter = new Scatter(new ScatterConfigurator() { AppName = "UNITY-PC-SCATTER", Network = network, StorageProvider = fileStorage }, this)) { await scatter.Connect(); await scatter.GetIdentity(new IdentityRequiredFields() { accounts = new List <ScatterSharp.Core.Api.Network>() { network }, location = new List <LocationFields>(), personal = new List <PersonalFields>() }); var eos = new Eos(new EosSharp.Core.EosConfigurator() { ChainId = network.chainId, HttpEndpoint = network.GetHttpEndpoint(), SignProvider = new ScatterSignatureProvider(scatter) }); var account = scatter.Identity.accounts.First(); return(account); } } catch (ApiErrorException ex) { print(JsonConvert.SerializeObject(ex.error)); return(null); } catch (ApiException ex) { print(ex.Content); return(null); } catch (Exception ex) { print(JsonConvert.SerializeObject(ex)); return(null); } }
public static async Task SaveAsync() { var file = await FileStorageProvider.GetFileAsync(); var lines = Actions.OrderBy(i => i.Index).Select(i => ActionItemAdapter.ToString(i)); await FileIO.WriteLinesAsync(file, lines); }
public async void File_Stored_EqualToInputFile() { await Lock(async() => { var inputFile = new TestFile(_inputDirectoryPath, _inputFileName, 5); var outputFile = new TestFile(_outputDirectoryPath, _outputFileName, 5); IStorageProvider storage = new FileStorageProvider(); using (var source = new FileStream(inputFile.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { await storage.Store(outputFile.Dir, outputFile.Name, source); using (var destination = storage.Get(outputFile.Dir, outputFile.Name)) { source.Position = 0; destination.Position = 0; var inputData = new byte[source.Length]; var outputData = new byte[destination.Length]; source.Read(inputData, 0, (int)source.Length); destination.Read(outputData, 0, (int)destination.Length); Assert.Equal(source.Length, destination.Length); Assert.Equal(inputData, outputData); } } await storage.Remove(outputFile.Dir, outputFile.Name); }); }
private string GetEmbedCode(string path, string filename) { SiteFile file = SiteFiles.GetFile(path, filename); if (file != null) { if (!GlobalSettings.IsImage(filename)) { return(string.Format("<a href=\"{0}\">{1}</a>", FileStorageProvider.GetGenericDownloadUrl(file.File), filename)); } else { int width = 200; int height = 200; try { width = int.Parse(this.txtWidth.Text); } catch { } try { height = int.Parse(this.txtHeight.Text); } catch { } return(GlobalSettings.ResizeImageHtml(SiteUrlManager.GetResizedImageUrl(file.File, width, height), width, height, false)); } } else { return(string.Empty); } }
public async Task <IActionResult> Delete( [FromServices] DocumentsManager manager, [FromServices] FileStorageProvider fileStorageProvider, [FromForm] long key, [FromHeader] Guid personUniqueId, [FromQuery] string uniqueCode) { using (var attachmentsRep = new Repository <DocumentAttachment>(_provider)) { var documentRep = new Repository <Document>(attachmentsRep); var document = documentRep.Get(x => x.UniqueCode == uniqueCode && x.SenderPerson.UniqueId == personUniqueId).FirstOrDefault(); if (document == null) { return(Json(ApiResponse.Failed(ApiErrorCode.ValidationError, "Невозможно удалить файлы не привязанные к документу"))); } var savedAttachment = attachmentsRep.Get(x => x.Id == key && x.Document.Id == document.Id).FirstOrDefault(); if (savedAttachment == null) { return(Json(ApiResponse.Failed(ApiErrorCode.ValidationError, "Невозможно удалить файлы не привязанные к документу"))); } await attachmentsRep.DeleteAsync(savedAttachment); await _historyManager.WriteEntry(document, document.SenderPerson, $"Файл: {savedAttachment.FileName} - удален", attachmentsRep); await attachmentsRep.CommitAsync(); var bucket = fileStorageProvider.GetDocumentBucket(); await bucket.DeleteAsync(new ObjectId(savedAttachment.StorageId)); } return(Json(ApiResponse.Success(true))); }
public async Task <IActionResult> Post(IFormFile attachmentFile, [FromServices] FileStorageProvider fileStorageProvider) { var bucket = fileStorageProvider.GetDocumentBucket(); var fileStream = new MemoryStream(); await attachmentFile.CopyToAsync(fileStream); var metadata = new AttachmentFileMetadata { FileName = attachmentFile.FileName, ContentType = attachmentFile.ContentType, Size = fileStream.Length, Uploaded = DateTime.Now, ContentHash = Helper.CalculateSha1Hash(fileStream.ToArray()) }; fileStream.Position = 0; var id = await bucket.UploadFromStreamAsync(attachmentFile.FileName, fileStream, new GridFSUploadOptions() { Metadata = metadata.ToBsonDocument() }); var result = new FileAttachmentResponse() { FileName = attachmentFile.FileName, FileId = id.ToString() }; return(Json(ApiResponse.Success(result))); }
public async Task <IHttpActionResult> LoadAsync(Guid claimId) { var serverUploadFolder = string.Format("{0}{1}\\", FileStorageProvider.GetCommonPathToScans(), claimId); if (!Directory.Exists(serverUploadFolder)) { Directory.CreateDirectory(serverUploadFolder); } var streamProvider = new CustomMultipartFormDataStreamProvider(serverUploadFolder); await Request.Content.ReadAsMultipartAsync(streamProvider); var scan = new Scan() { Id = streamProvider.ScanId, ClaimId = claimId }; scan.CreateDate = DateTime.Now; scan.OriginalName = streamProvider.FileData.First().Headers.ContentDisposition.FileName.Trim('"'); _context.Scans.Add(scan); _context.SaveChanges(); return(Ok(scan.Id)); }
/// <summary> /// 获取默认图像 /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public string GetDefaultImageUrl(int width, int height) { if (width == 0 || height == 0) { if (File != null) { return(FileStorageProvider.GetGenericDownloadUrl(File)); } else { return(SiteUrlManager.GetNoPictureUrl()); } } else { if (File == null) { return(SiteUrlManager.GetNoPictureUrl(width, height)); } else { return(SiteUrlManager.GetResizedImageUrl(File, width, height)); } } }
public async Task <IActionResult> AddFileToDocument(IFormFile attachmentFile, [FromHeader] Guid personUniqueId, [FromQuery] string uniqueCode, [FromServices] FileStorageProvider fileStorageProvider, [FromServices] DocumentsManager manager) { var existAttachmentFile = await manager.CheckExistAttachmentFile(User.Identity.Name, uniqueCode, personUniqueId, attachmentFile); if (existAttachmentFile) { return(Json(ApiResponse.Success(false))); } var bucket = fileStorageProvider.GetDocumentBucket(); var fileStream = new MemoryStream(); await attachmentFile.CopyToAsync(fileStream); var metadata = new AttachmentFileMetadata { FileName = attachmentFile.FileName, ContentType = attachmentFile.ContentType, Size = fileStream.Length, Uploaded = DateTime.Now, ContentHash = Helper.CalculateSha1Hash(fileStream.ToArray()) }; fileStream.Position = 0; var id = await bucket.UploadFromStreamAsync(attachmentFile.FileName, fileStream, new GridFSUploadOptions() { Metadata = metadata.ToBsonDocument() }); var result = await manager.AddAttachmentFileToDraft(User.Identity.Name, uniqueCode, personUniqueId, new FileAttachmentResponse { FileId = id.ToString(), FileName = attachmentFile.FileName }); return(Json(ApiResponse.Success(result))); }
public override void InitFixture() { PhotoServer.App_Start.InitializeMapper.MapClasses(); ObjectMother.SetPhotoPath(); provider = new FileStorageProvider(ObjectMother.photoPath); ObjectMother.ClearDirectory(provider); ObjectMother.CopyTestFiles(provider); }
public static void Postfix(FileStorageProvider __instance, string name) { string fullMod = SaveHandler.GetModdedPath(__instance, name); if (File.Exists(fullMod)) { File.Delete(fullMod); } }
private static Dictionary <string, string> GetEntityMapper(string entityName, ILogger log) { if (string.IsNullOrEmpty(azureWebJobsStorage)) { return(null); } var storageParams = azureWebJobsStorage.Split(';'); string storageAccountKey = "", storageAccountName = "", blobServiceUri = ""; foreach (var p in storageParams) { if (p.StartsWith("AccountName")) { storageAccountName = p.Substring(p.IndexOf('=') + 1); } if (p.StartsWith("AccountKey")) { storageAccountKey = p.Substring(p.IndexOf('=') + 1); } if (p.StartsWith("AccountUri")) { storageAccountKey = p.Substring(p.IndexOf('=') + 1); } } if (string.IsNullOrEmpty(storageAccountKey) || string.IsNullOrEmpty(storageAccountName) || string.IsNullOrEmpty(blobServiceUri)) { log.LogInformation($"Storgae account Key or Name hasn't been set!"); return(null); } if (string.IsNullOrEmpty(shareName) || string.IsNullOrEmpty(fileName)) { log.LogInformation($"ShareName or File Name hasn't been set!"); return(null); } var fileStorageProvider = new FileStorageProvider(storageAccountName, storageAccountKey, blobServiceUri); var encoded = fileStorageProvider.ReadFromFile(shareName, fileName); var decodedMessage = JsonConvert.DeserializeObject <Dictionary <string, Dictionary <string, string> > >(encoded); if (decodedMessage != null && decodedMessage.ContainsKey(entityName)) { return(decodedMessage[entityName]); } else { return(null); } }
public ScatterUnitTests(MonoBehaviour scriptInstance) { var fileStorage = new FileStorageProvider(Application.persistentDataPath + "/scatterapp.dat"); var scatter = new Scatter(new ScatterConfigurator() { AppName = "UNITY-WEBGL-SCATTER-SHARP", Network = network, StorageProvider = fileStorage }, scriptInstance); ScatterUnitTestCases = new ScatterUnitTestCases(scatter, network); }
public void FileStorage_CreateRetrieve_Test() { var plainText = "Some test data to save to a file, single item."; ITokenStorageProvider fileProvider = new FileStorageProvider(); var token = fileProvider.Create(plainText); Assert.IsNotNull(token); var decrypted = fileProvider.Read(token); Assert.AreEqual(plainText, decrypted); }
public ActionResult Get(Guid id) { var scan = _context.Scans.Find(id); if (scan == null) { return(HttpNotFound()); } var path = Path.Combine(FileStorageProvider.GetCommonPathToScans(), scan.ClaimId.ToString(), scan.LocalFileName); Response.AppendHeader("Content-Disposition", "inline; filename=" + scan.OriginalName); return(File(path, MimeHelper.GetContentType(scan.ExtensionWithDot))); }
public async void File_Removed_DoesntExist() { await Lock(async() => { var inputFile = new TestFile(_inputDirectoryPath, _inputFileName, 4); var outputFile = new TestFile(_outputDirectoryPath, _outputFileName, 4); IStorageProvider storage = new FileStorageProvider(); await storage.Store(outputFile.Dir, outputFile.Name, inputFile.Path); await storage.Remove(outputFile.Dir, outputFile.Name); Assert.False(File.Exists(outputFile.Path)); }); }
/// <summary> /// 添加产品图片 /// </summary> /// <param name="picture"></param> /// <param name="stream"></param> /// <returns></returns> public static DataActionStatus Create(ProductPicture picture, Stream stream) { DataActionStatus status; picture = ShopDataProvider.Instance.CreateUpdatePicture(picture, DataProviderAction.Create, out status); if (status == DataActionStatus.Success) { FileStorageProvider fs = new FileStorageProvider(FileStoreKey); fs.AddUpdateFile(MakePath(picture.ProductID), picture.PictureFile, stream); HHCache.Instance.Remove(CacheKeyManager.GetPictureKey(picture.PictureID)); HHCache.Instance.Remove(CacheKeyManager.GetPictureKeyByProductID(picture.ProductID)); } return(status); }
private void ResetForm(FileStorageProvider provider) { switch (provider) { case FileStorageProvider.Local: pnlResultLocal.Visible = false; pnlErrorLocal.Visible = false; break; case FileStorageProvider.AzureStorageBlobs: pnlResultAzure.Visible = false; pnlErrorAzure.Visible = false; break; } }
/// <summary> /// 更新行业信息 /// </summary> /// <param name="industry"></param> /// <param name="contentStream"></param> public static DataActionStatus Update(ProductIndustry industry, Stream contentStream) { DataActionStatus status; ShopDataProvider.Instance.CreateUpdateIndustry(industry, DataProviderAction.Update, out status); if (status == DataActionStatus.Success) { if (contentStream != null && contentStream.Length > 0) { FileStorageProvider fs = new FileStorageProvider(FileStoreKey); fs.AddUpdateFile(MakePath(industry.IndustryID), industry.IndustryLogo, contentStream); } HHCache.Instance.RemoveByPattern(CacheKeyManager.ProductIndustryXpath); OnUpdated(industry.IndustryID); } return(status); }
String PerformStorageAction(String schema) { InvokeResultDescriptor result = new InvokeResultDescriptor(); String res = String.Empty; try { StorageActionArgs args = XmlSerializationUtility.XmlStr2Obj <StorageActionArgs>(schema); if (args != null) { FileStorageProvider storageProvider = new FileStorageProvider(); switch (args.ActionType) { case StorageActionTypes.Save: args.FileDescription.ContentFileName = args.FileDescription.Description.Name + ".content." + FileStorageProvider.GetFilteExtension(args.ContentType); storageProvider.Save(HttpContext.Current.User, args.FileDescription.Description.Name + "." + FileStorageProvider.GetFilteExtension(args.ContentType), XmlSerializationUtility.Obj2XmlStr(args.FileDescription)); storageProvider.Save(HttpContext.Current.User, args.FileDescription.ContentFileName, args.Content); break; case StorageActionTypes.Load: res = storageProvider.Load(HttpContext.Current.User, args.FileDescription.ContentFileName); break; case StorageActionTypes.GetList: res = XmlSerializationUtility.Obj2XmlStr(storageProvider.GetList(HttpContext.Current.User, "*." + FileStorageProvider.GetFilteExtension(args.ContentType)), Common.Namespace); break; case StorageActionTypes.Clear: res = XmlSerializationUtility.Obj2XmlStr(storageProvider.Clear(HttpContext.Current.User, "*." + FileStorageProvider.GetFilteExtension(args.ContentType))); break; case StorageActionTypes.Delete: storageProvider.Delete(HttpContext.Current.User, args.FileDescription.Description.Name + "." + FileStorageProvider.GetFilteExtension(args.ContentType)); storageProvider.Delete(HttpContext.Current.User, args.FileDescription.ContentFileName); res = XmlSerializationUtility.Obj2XmlStr(storageProvider.GetList(HttpContext.Current.User, "*." + FileStorageProvider.GetFilteExtension(args.ContentType)), Common.Namespace); break; } } result.Content = res; } catch (Exception) { throw; } return(InvokeResultDescriptor.Serialize(result)); }
private void ShowError(FileStorageProvider provider, string errorMessage) { switch (provider) { case FileStorageProvider.Local: pnlResultLocal.Visible = false; pnlErrorLocal.Visible = true; litErrorLocal.Text = errorMessage; break; case FileStorageProvider.AzureStorageBlobs: pnlResultAzure.Visible = false; pnlErrorAzure.Visible = true; litErrorAzure.Text = errorMessage; break; } }
public IStorageFile GetResizedFileUrl(string fileStoreKey, string path, string fileName, int width, int height) { string resizedFileName = fileName + "-" + width.ToString() + "x" + height.ToString() + "."; string resizedPath = Path.Combine(path, "ResizeImages"); System.Drawing.Imaging.ImageFormat format; string extension = GlobalSettings.GetExtension(fileName).ToLower(); if (extension == "png" || extension == "gif") { format = System.Drawing.Imaging.ImageFormat.Png; resizedFileName += "png"; } else { format = System.Drawing.Imaging.ImageFormat.Jpeg; resizedFileName += "jpg"; } FileStorageProvider fileProvider = new FileStorageProvider(fileStoreKey); IStorageFile file = fileProvider.GetFile(resizedPath, resizedFileName); if (file == null) { IStorageFile originalFile = null; if (fileProvider != null) { originalFile = fileProvider.GetFile(path, fileName); } if (originalFile != null) { using (Stream sourceStream = originalFile.OpenReadStream()) { using (Stream imageStream = GlobalSettings.ResizeImage(sourceStream, height, width, format)) { file = fileProvider.AddUpdateFile(resizedPath, resizedFileName, imageStream); imageStream.Close(); } sourceStream.Close(); } } } return(file); }
public async void FileAsStream_Stored_Exists() { await Lock(async() => { var inputFile = new TestFile(_inputDirectoryPath, _inputFileName, 1); var outputFile = new TestFile(_outputDirectoryPath, _outputFileName, 1); IStorageProvider storage = new FileStorageProvider(); using (var source = new FileStream(inputFile.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { await storage.Store(outputFile.Dir, outputFile.Name, source); Assert.True(File.Exists(outputFile.Path)); } await storage.Remove(outputFile.Dir, outputFile.Name); }); }
/// <summary> /// 添加品牌信息 /// </summary> /// <param name="brand"></param> /// <param name="contentStream"></param> public static DataActionStatus Create(ProductBrand brand, Stream contentStream) { DataActionStatus status; brand = ShopDataProvider.Instance.CreateUpdateBrand(brand, DataProviderAction.Create, out status); if (status == DataActionStatus.Success) { if (contentStream != null && contentStream.Length > 0) { FileStorageProvider fs = new FileStorageProvider(FileStoreKey); fs.AddUpdateFile(MakePath(brand.BrandID), brand.BrandLogo, contentStream); } HHCache.Instance.RemoveByPattern(CacheKeyManager.ProductBrandXpath); OnUpdated(brand.BrandID); //HHCache.Instance.Remove(CacheKeyManager.ProductBrandKey); } return(status); }
public RemoteService(HttpPilotClient client) { _client = client; _client.SetConnectionLostListener(this); _serverCallback = new ServerCallback(); _fileArchiveApi = client.GetFileArchiveApi(); var searchFactory = new SearchServiceFactory(_serverCallback); var localArchiveRootFolder = DirectoryProvider.GetTempPath(); var fileStorageProvider = new FileStorageProvider(localArchiveRootFolder); var changsetUploader = new ChangesetUploader(_fileArchiveApi, fileStorageProvider, null); var messageApi = client.GetMessagesApi(new NullableMessagesCallback()); var serverApi = client.GetServerApi(_serverCallback); var dbInfo = serverApi.OpenDatabase(); var backend = new Backend(serverApi, dbInfo, messageApi, changsetUploader); _serverApi = new ServerApiService(serverApi, dbInfo, searchFactory, backend); _serverCallback.RegisterCallbackListener((IRemoteServiceListener)_serverApi); IsActive = true; }
public override bool Save(IHtmlContent htmldoc) { var docprovider = DocumentStorageProvider.GetInstance(this.DBType, this.ConnectionString); CnblogsNewsAdapter adpt = new CnblogsNewsAdapter(htmldoc, this.Url); IDocument doc = adpt.GetDocument(); IFileStorage fs = FileStorageProvider.GetInstance(this.DBType, this.ConnectionString); foreach (string url in doc.Attachments) { if (!fs.Exists(url)) { logger.InfoFormat("Downloading document: {0}", url); var webStream = WebRequestHelper.SendGetRequestAndAutoDetectContentType(url, null, null); fs.Add(url, webStream); } } doc.LastUpdatedDate = DateTime.Now; return(docprovider.SaveDocument(doc, true)); }
public void FileStorage_CreateRetrieveMultipleRecords_Test() { var plainText1 = "Another bit of data to save"; var plainText2 = "Another bit of data to save, the second one to save"; ITokenStorageProvider fileProvider = new FileStorageProvider(); var token1 = fileProvider.Create(plainText1); Assert.IsNotNull(token1); var token2 = fileProvider.Create(plainText2); Assert.IsNotNull(token1); var decrypted = fileProvider.Read(token1); Assert.AreEqual(plainText1, decrypted); var decrypted2 = fileProvider.Read(token2); Assert.AreEqual(plainText2, decrypted2); }