} // end of ReadAllLines() public static DateTime GetLastWriteTimeUtc(string filePath, StorageSource sources) { DateTime result = DateTime.MinValue; StorageFile file = null; // UserSpace. if ((sources & StorageSource.UserSpace) != 0) { file = GetStorageFile(UserSpaceFolder, Path.Combine(UserLocation, filePath)); } // TitleSpace. if (result != DateTime.MinValue && (sources & StorageSource.TitleSpace) != 0) { file = GetStorageFile(TitleSpaceFolder, filePath); } if (file != null) { IAsyncOperation <BasicProperties> foo = file.GetBasicPropertiesAsync(); foo.AsTask <BasicProperties>().Wait(); BasicProperties props = foo.GetResults(); result = props.DateModified.DateTime; } return(result); } // end of GetLastWriteTimeUtc()
private static async Task <bool> CreateVersionsFromFirebaseStorageAsync(string localJsonSaveFilePath = null) { Logger.WriteLine("Loading versions from Firebase Storage..."); var fileUri = await StorageSource.GetFileUrlAsync(FIREBASE_STORAGE_PATH); if (fileUri == null) { throw new FileNotFoundException("File not found.", FIREBASE_STORAGE_PATH); } using (var webClient = new WebClient()) { var json = webClient.DownloadString(fileUri); if (string.IsNullOrWhiteSpace(json)) { Logger.WriteLine("The local JSON-file is empty. Can't proceed."); return(false); } Versions = JsonConvert.DeserializeObject <SortedSet <Version> >(json); if (!string.IsNullOrEmpty(localJsonSaveFilePath)) { SaveVersionsToFileAsync(localJsonSaveFilePath); } return(true); } }
public StorageSource GetStorageSource() { _hub.UpdateRegistered <StorageSource>(); StorageSource ss = _hub.GetRegisteredInfo <StorageSource>("Default"); return(ss); }
} // end of FileExists() /// <summary> /// Checks if a directory exists. If both storage sources /// are specified, will check user space first. /// </summary> /// <param name="path"></param> /// <param name="sources"></param> /// <returns></returns> public static bool DirExists(string path, StorageSource sources) { bool result = false; try { // Test user space first. if ((sources & StorageSource.UserSpace) != 0) { string fullPath = Path.Combine(UserLocation, path); result = Directory.Exists(fullPath); } // Test title space. if (result == false && (sources & StorageSource.TitleSpace) != 0) { string fullPath = Path.Combine(TitleLocation, path); result = Directory.Exists(fullPath); } } catch (Exception e) { string str = e.Message; if (e.InnerException != null) { str += e.InnerException.Message; } Debug.Assert(false, str); } return(result); } // end of DirExists()
public static async Task <bool> LoadAsync() { if (Relations?.Count != 0) { return(true); } var fileUri = await StorageSource.GetFileUrlAsync(FirebaseStoragePath); if (fileUri == null) { return(false); } var outputFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(FileName); if (outputFile != null) { var json = File.ReadAllText(outputFile.Path); Relations = JsonConvert.DeserializeObject <List <ResourceRelation> >(json); } else { outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting); using (var webClient = new WebClient()) { var json = webClient.DownloadString(fileUri); Relations = JsonConvert.DeserializeObject <List <ResourceRelation> >(json); } } return(Relations?.Count != 0); }
public static bool CheckWorldExistsByGenre(Guid worldId, Genres genres) { string bucket = BokuGame.MyWorldsPath; if (genres != 0) { bucket = Utils.FolderNameFromFlags(genres); if (bucket == null) { return(false); } } string fullPath = BokuGame.Settings.MediaPath + bucket + worldId.ToString() + @".Xml"; StorageSource sources = StorageSource.All; if ((genres & Genres.Downloads) != 0) { sources = StorageSource.UserSpace; } return(Storage4.FileExists(fullPath, sources)); }
/// <summary> /// Find all files with given relative path and filter. Checks title space FIRST, then user. /// Local space not checked, because only Autosave lives there now. /// </summary> /// <param name="path"></param> /// <returns></returns> public static String[] GetFiles(string path, string filter, StorageSource sources) { String[] list = null; if (0 != (sources & StorageSource.TitleSpace)) { string dirpath = GetDirectoryName(path, StorageSource.TitleSpace); if (Directory.Exists(dirpath)) { list = Directory.GetFiles(dirpath, filter); Strip(list, PathBase(StorageSource.TitleSpace)); } } if (Initialized && 0 != (sources & StorageSource.UserSpace)) { string dirpath = GetDirectoryName(path, StorageSource.UserSpace); if (Directory.Exists(dirpath)) { String[] userList = Directory.GetFiles(dirpath, filter); Strip(userList, PathBase(StorageSource.UserSpace)); list = Concat(userList, list); } } return(list); }
// POST: api/Server public IHttpActionResult Post([FromBody] StorageSource ss) { if (ss == null) { return(BadRequest("传入的数据不能为空")); } NodesManager.Instance.UpdateStorageSource(ss); return(Ok("更新集中存储器地址成功。")); }
// GET: api/Server public IHttpActionResult Get() { StorageSource ss = NodesManager.Instance.GetStorageSource(); if (ss == null) { return(BadRequest("尚未设置集中存储服务器地址")); } return(Ok(ss)); }
internal static async Task SaveFirebaseFileToStorageFolder(FirebaseFile file, string firebaseFolder, StorageFolder storageFolder) { StorageFile sampleFile = await storageFolder.CreateFileAsync(file.FileName, CreationCollisionOption.GenerateUniqueName); using (var client = new WebClient()) { var url = await StorageSource.GetFileUrlAsync($"images/{file.FileName}"); client.DownloadFileAsync(url, sampleFile.Path); } }
public VideoDataSource GetStorageSource() { ClientHub?.UpdateRegistered <StorageSource>(); StorageSource ss = ClientHub?.GetRegisteredInfo <StorageSource>("Default"); return(new VideoDataSource() { SrcType = SourceType.Remote, Storage = ss, }); }
static public Stream TextureFileOpenRead(string nameNoExt, StorageSource sources, TextureFileType fileType) { string filePath = string.Format(FULL_FILE_PATH_FORMAT, nameNoExt, fileType.ToString()); if (FileExists(filePath, sources)) { return(OpenRead(filePath, sources)); } throw new FileNotFoundException(String.Format("Texture2D file not found in {0}: {1}", sources, nameNoExt)); }
} // end of CreateDirectory() /// <summary> /// If sources contains both local and user, and they are actually the same /// folder, then strip one out to avoid unnecessary file IO. /// </summary> /// <param name="sources"></param> /// <returns></returns> private static StorageSource CheckSources(StorageSource sources) { if (localEqualsUser) { StorageSource localAndUser = StorageSource.LocalSpace | StorageSource.UserSpace; if ((sources & localAndUser) == localAndUser) { sources &= ~StorageSource.LocalSpace; } } return(sources); }
public static SiteOptions Load(StorageSource sources) { XmlSerializer xml = new XmlSerializer(typeof(SiteOptions)); Stream stream = Storage4.OpenRead(MyFilename, sources); SiteOptions result = (SiteOptions)xml.Deserialize(stream); stream.Close(); return(result); }
private static async Task SaveVersionsToFirebaseStorage() { Logger.WriteLine($"Uploading versions to database at {FIREBASE_STORAGE_PATH}."); var json = JsonConvert.SerializeObject(Versions); byte[] jsonByteArray = Encoding.UTF8.GetBytes(json); using (var stream = new MemoryStream(jsonByteArray)) { var url = await StorageSource.UploadFileAsync(stream, FIREBASE_STORAGE_PATH); Logger.WriteLine($"Relations file was successfully uploaded to Firebase Storage at {url}."); } }
private async void ImageView_Loaded(object sender, RoutedEventArgs e) { if (File == null) { ImageView.Visibility = Visibility.Collapsed; return; } ImageView.Visibility = Visibility.Visible; var url = await StorageSource.GetFileUrlAsync($"images/{File.FileName}"); ImageView.Source = new BitmapImage(url); }
public static async Task <ImageSource> WebImageToCroppedImage <T>(T image) where T : FirebaseImage, ICroppableImage { // Convert start point and size to unsigned integer. uint startPointX = (uint)image.Crop.X; uint startPointY = (uint)image.Crop.Y; uint height = (uint)image.Crop.Height; uint width = (uint)image.Crop.Width; var bitmap = new BitmapImage(await StorageSource.GetFileUrlAsync($"images/{image.FileName}")); var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(bitmap.UriSource); using (var stream = await randomAccessStreamReference.OpenReadAsync()) { // Create a decoder from the stream. With the decoder, we can get the properties of the image. var decoder = await BitmapDecoder.CreateAsync(stream); // Create the bitmap bounds var bitmapBounds = new BitmapBounds { X = startPointX, Y = startPointY, Height = height, Width = width }; // Create cropping BitmapTransform. var bitmapTransform = new BitmapTransform { Bounds = bitmapBounds, ScaledWidth = width, ScaledHeight = height }; // Get the cropped pixels within the bounds of transform. PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, bitmapTransform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb); byte[] pixels = pixelDataProvider.DetachPixelData(); // Stream the bytes into a WriteableBitmap WriteableBitmap cropBmp = new WriteableBitmap((int)width, (int)height); Stream pixStream = cropBmp.PixelBuffer.AsStream(); pixStream.Write(pixels, 0, (int)(width * height * 4)); return(cropBmp); } }
static public Stream TextureFileOpenRead(string nameNoExt, StorageSource sources) { if (FileExists(nameNoExt + ".dds", sources)) { return(OpenRead(nameNoExt + ".dds", sources)); } if (FileExists(nameNoExt + ".png", sources)) { return(OpenRead(nameNoExt + ".png", sources)); } throw new FileNotFoundException(String.Format("Texture2D file not found in {0}: {1}", sources, nameNoExt)); }
/// <summary> /// Find all files with given relative path and filter. Checks title space FIRST, then user. /// NOTE This returns full path names, not relative ones. /// </summary> /// <param name="path"></param> /// <param name="pattern"></param> /// <param name="sources"></param> /// <param name="searchOption"></param> /// <returns></returns> public static String[] GetFiles(string path, string pattern, StorageSource sources, SearchOption searchOption) { String[] list = null; if ((sources & StorageSource.TitleSpace) != 0) { string fullPath = Path.Combine(TitleLocation, path); if (string.IsNullOrEmpty(pattern)) { if (Directory.Exists(fullPath)) { list = Directory.GetFiles(fullPath); } } else { if (Directory.Exists(fullPath)) { list = Directory.GetFiles(fullPath, pattern); } } } if ((sources & StorageSource.UserSpace) != 0) { string fullPath = Path.Combine(UserLocation, path); if (Directory.Exists(fullPath)) { string[] userList = null; if (string.IsNullOrEmpty(pattern)) { if (Directory.Exists(fullPath)) { userList = Directory.GetFiles(fullPath); } } else { if (Directory.Exists(fullPath)) { userList = Directory.GetFiles(fullPath, pattern); } } list = Concat(userList, list); } } return(list); }
/// <summary> /// Internal - create the writable directory if it doesn't exist. /// Note that since it's writable, it's in user space, not title space. /// </summary> /// <param name="name"></param> /// <returns></returns> public static void CreateDirectory(string name, StorageSource source) { try { Directory.CreateDirectory(GetDirectoryName(name, source)); } catch (Exception e) { // Just here for debug. if (e != null) { } // Pass on the pain. throw e; } } // end of CreateDirectory()
/// <summary> /// Delete the file. Only checks user space, since title space is read-only. /// </summary> /// <param name="name"></param> /// <returns></returns> public static bool Delete(string name) { // Only bother checking in user space, // because we can't delete out of title space anyway if (Initialized) { StorageSource source = CheckWriteSource(name); string filename = Combine(PathBase(source), name); if (File.Exists(filename)) { dirty = true; File.Delete(filename); return(true); } } return(false); }
/// <summary> /// Return title or user base path as requested. /// </summary> /// <param name="titleSpace"></param> /// <returns></returns> private static string PathBase(StorageSource source) { if (source == StorageSource.TitleSpace) { return(TitleLocation); } if (source == StorageSource.LocalSpace) { return(UserLocal); } if (source == StorageSource.UserSpace) { return(UserLocation); } throw new Exception("Invalid storage source"); }
/// <summary> /// Open file for reading. /// </summary> /// <param name="filePath">Path relative to storage source location.</param> /// <param name="sources">Which source(s) to look in. If both, will look in UserSpace first.</param> /// <returns></returns> public static Stream OpenRead(string filePath, StorageSource sources) { Stream stream = null; try { // If both StorageSource flags are set, we want to try user space first. // Try UserSpace. if ((sources & StorageSource.UserSpace) != 0) { string fullPath = Path.Combine(UserLocation, filePath); if (File.Exists(fullPath)) { stream = File.OpenRead(fullPath); } } // Try TitleSpace. if (stream == null && (sources & StorageSource.TitleSpace) != 0) { string fullPath = Path.Combine(TitleLocation, filePath); if (File.Exists(fullPath)) { stream = File.OpenRead(fullPath); } } } catch (Exception e) { string str = e.Message; if (e.InnerException != null) { str += e.InnerException.Message; } Debug.Assert(false, str); } return(stream); } // end of OpenRead()
public static async Task SaveAsync() { var rootfolder = ApplicationData.Current.LocalFolder; var jsonFile = await rootfolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting); Logger.WriteLine($"Saving relations to temporary file at {jsonFile.Path}."); using (var file = new StreamWriter(jsonFile.Path)) { var serializer = new JsonSerializer(); serializer.Serialize(file, Relations); } Logger.WriteLine($"Uploading relations file to database at {FirebaseStoragePath}."); using (var stream = await jsonFile.OpenStreamForReadAsync()) { var url = await StorageSource.UploadFileAsync(stream, FirebaseStoragePath); Logger.WriteLine($"Relations file was successfully uploaded to Firebase Storage at {url}."); } }
private void applySource(StorageSource source) { switch (source) { case StorageSource.NewStorage: tableLayoutPanelCreate.Visible = true; tableLayoutPanelOpen.Visible = false; buttonCreate.Visible = true; buttonOpen.Visible = false; break; case StorageSource.OpenStorage: tableLayoutPanelCreate.Visible = false; tableLayoutPanelOpen.Visible = true; buttonCreate.Visible = false; buttonOpen.Visible = true; break; default: throw new ArgumentOutOfRangeException(); } }
public static async Task <T> CreateNewImageAsync <T>(StorageFile storageFile, string description = "") where T : FirebaseImage, new() { Logger.WriteLine($"Creating new image file from storage file {storageFile.Path}..."); using (var stream = await storageFile.OpenStreamForReadAsync()) { var decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); var image = (T)Activator.CreateInstance(typeof(T), new object[] { (int)decoder.PixelWidth, (int)decoder.PixelHeight, storageFile.FileType }); await StorageSource.UploadFileAsync(stream, $"images/{image.FileName}"); Logger.WriteLine($"Image from file {storageFile.Path} was successfully created."); return(image); } }
/// <summary> /// Returns StorageFile associated with given path and source. /// </summary> /// <param name="path">full path of file</param> /// <param name="source"></param> /// <returns></returns> public static StorageFile GetStorageFile(string fullPath, StorageSource sources) { // Note, for GetStorageFile() calls we don't need to split the // path from the filename. // If both StorageSource flags are set, try user space first. StorageFile file = null; // Try UserSpace. if ((sources & StorageSource.UserSpace) != 0) { file = GetStorageFile(UserSpaceFolder, fullPath); } // Try TitleSpace. if (file == null && (sources & StorageSource.TitleSpace) != 0) { file = GetStorageFile(TitleSpaceFolder, fullPath); } return(file); }
public static async Task <ResourcePack> CreateNewResourcePackAsync(StorageFile file, User author, string name, string description = null) { if (file == null) { throw new ArgumentNullException(nameof(file)); } if (author == null) { throw new ArgumentNullException(nameof(author)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } Debug.WriteLine($"Creating new resource pack from file {file.Path}."); var verison = await DetectVersion(file); var resourcePack = new ResourcePack(author, name, verison, description); using (var resourceStream = await file.OpenStreamForReadAsync()) { if (await StorageSource.UploadFileAsync(await file.OpenStreamForReadAsync(), $"{RESOURCE_PACKS_FOLDER_NAME}/{resourcePack.FileName}") == null) { Debug.WriteLine($"Resource Pack file {file.Path} failed to upload."); return(null); } } if (!await RestApiService <ResourcePack> .Add(resourcePack)) { Debug.WriteLine($"Resource Pack {resourcePack.Key} failed to upload."); return(null); } return(resourcePack); }
private async Task CheckUriAndOpenDocument() { var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri); string?documentId = GetQueryParam(uri, "id"); string?pub = GetQueryParam(uri, "pub"); string?priv = GetQueryParam(uri, "priv"); string?contentSeed = GetQueryParam(uri, "c"); string?storage = GetQueryParam(uri, "s"); StorageSource storageSource = StorageSource.Skynet; Enum.TryParse <StorageSource>(storage, out storageSource); byte[]? pubKey = null; byte[]? privKey = null; if (!string.IsNullOrEmpty(pub)) { pubKey = Utils.HexStringToByteArray(pub); } if (!string.IsNullOrEmpty(priv)) { privKey = Utils.HexStringToByteArray(priv); } if (Guid.TryParse(documentId, out Guid docId) && pubKey != null && !string.IsNullOrEmpty(contentSeed)) { skyDocsService.AddDocumentSummary(docId, pubKey, privKey, contentSeed, storageSource); await OpenDocument(docId); } else { skyDocsService.CurrentDocument = null; } StateHasChanged(); }
/// <summary> /// Open file for reading. /// </summary> /// <param name="filePath">Path relative to storage source location.</param> /// <param name="sources">Which source(s) to look in. If both, will look in UserSpace first.</param> /// <returns></returns> public static Stream OpenRead(string filePath, StorageSource sources) { Stream stream = null; // If both StorageSource flags are set, try user space first. StorageFile file = null; // Try UserSpace. if ((sources & StorageSource.UserSpace) != 0) { file = GetStorageFile(UserSpaceFolder, Path.Combine(UserLocation, filePath)); } // Try TitleSpace. if (file == null && (sources & StorageSource.TitleSpace) != 0) { file = GetStorageFile(TitleSpaceFolder, filePath); } try { if (file != null) { Task <Stream> foo = file.OpenStreamForReadAsync(); foo.ConfigureAwait(false); stream = foo.Result; } } catch (Exception e) { if (e != null) { } } return(stream); } // end of OpenRead()