/// <summary> /// Handle the request /// </summary> /// <param name="uri"></param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="context"></param> public void HandleRequest(string uri, HttpRequest request, HttpResponse response, HttpContext context) { // Split into path and filename int index = uri.LastIndexOf('/'); string path = (index < 0) ? "" : uri.Substring(0, index); string filename = (index < 0) ? uri : uri.Substring(index + 1); // Use default filename if applicable if (filename.Length == 0) filename = m_defaultFile; // Strip leading separators from URI if (path.StartsWith("/")) path = path.Substring(1); // Now look for the file IFolder folder = m_basePath.OpenChild(path); if (folder == null) throw new HttpNotFoundException(); if (!folder.FileExists(filename)) throw new HttpNotFoundException(); // Get the content type response.ResponseCode = HttpResponseCode.Ok; response.ContentType = MimeType.FromExtension(filename); using(Stream input = folder.CreateFile(filename, FileAccessMode.Read, CreationOptions.OpenIfExists)) input.CopyTo(response.Content); }
private static string CopyIconImage(Assembly resources, string assembly, string iconName) { // Get the stream for the source image Stream input = resources.GetManifestResourceStream(assembly + "." + ImagePrefix + iconName); if (input == null) { return(""); } // Copy the image to the static image directory IFolder folder = Locator.Current.GetService <IFolder>(); folder = folder.CreateChildren(ServiceManager.SiteFolder + ServiceManager.BaseImageUrl); string filename = assembly + "." + iconName; Stream output = folder.CreateFile(filename, FileAccessMode.ReadAndWrite, CreationOptions.ReplaceExisting); if (output == null) { return(""); } input.CopyTo(output); input.Dispose(); output.Dispose(); // All done return(ServiceManager.BaseImageUrl + "/" + filename); }
public static bool CopyFile(this IFileSystem fileSystem, AbsoluteFilePath sourcePath, AbsoluteFilePath targetPath, bool overwriteIfExists = false) { IFile source = fileSystem.GetFile(sourcePath); if (source == null) { return(false); } IFolder targetFolder = fileSystem.CreateFolder(targetPath.Folder); IFile file = targetFolder.GetFile(targetPath.ItemName); if (file != null && !overwriteIfExists) { return(false); } if (file == null) { file = targetFolder.CreateFile(targetPath.ItemName); } var buffer = new byte[512]; int count; using (Stream to = file.OpenToWrite()) { using (Stream from = file.OpenToRead()) { while ((count = from.Read(buffer, 0, buffer.Length)) >= 0) { if (count > 0) { to.Write(buffer, 0, count); } } } } return(true); }
public static IFile CreateFile(this IFolder folder, string name) { using (var stream = new MemoryStream()) { return(folder.CreateFile(name, stream, 0, new Progress())); } }
public static IFile CreateFile(this IFolder folder, IFile file, string name, IProgress progress) { using (var stream = file.OpenRead()) { return(folder.CreateFile(name, stream, file.Size, progress)); } }
/// <summary> /// Create and set up the web server. /// </summary> /// <param name="server"></param> /// <param name="useStaticFiles"></param> /// <param name="unpackSite"></param> public SensHubHttpServer(ISocketServer server, bool useStaticFiles, bool unpackSite) : base(server) { // Get the root of the static site directory IFolder folder = Locator.Current.GetService <IFolder>(); folder = folder.OpenFolder(ServiceManager.SiteFolder); // Unpack the site if we need to if (useStaticFiles && unpackSite) { // We want to serve content from a directory rather than from the resources and // we want to unpack our content from the embedded resources Assembly asm = Utilities.GetContainingAssembly <SensHubHttpServer>(); foreach (string resourceName in asm.GetManifestResourceNames()) { if (!resourceName.StartsWith(SitePrefix)) { continue; } // Determine the target file name // TODO: There should be a better way to do this string targetFile = resourceName.Substring(SitePrefix.Length); targetFile = targetFile.Replace('.', '/'); int index = targetFile.LastIndexOf('/'); targetFile = targetFile.Substring(0, index) + "." + targetFile.Substring(index + 1); // Get the directory string directory = ""; index = targetFile.LastIndexOf('/'); IFolder target = folder; if (index >= 0) { directory = targetFile.Substring(0, index); targetFile = targetFile.Substring(index + 1); target = target.CreateChildren(directory); } // Now copy the resource Stream output = target.CreateFile(targetFile, FileAccessMode.ReadAndWrite, CreationOptions.ReplaceExisting); Stream input = asm.GetManifestResourceStream(resourceName); input.CopyTo(output); output.Dispose(); input.Dispose(); } } // Add the appropriate default handler if (useStaticFiles) { AddHttpRequestHandler("/", new StaticHttpHandler(folder)); } else { AddHttpRequestHandler("/", new HttpResourceHandler(Utilities.GetContainingAssembly <SensHubHttpServer>(), SitePrefix, "index.html")); } // Add a static file handler for plugin provided images folder = Locator.Current.GetService <IFolder>(); folder = folder.CreateChildren(ServiceManager.SiteFolder + ServiceManager.BaseImageUrl); AddHttpRequestHandler(ServiceManager.BaseImageUrl + "/", new StaticHttpHandler(folder)); // Add the RPC request handler AddWebSocketRequestHandler("/api/", new WebSocketRpcHandler()); }
private async Task Add(IFolder folder, IEnumerable <string> files) { foreach (var file in files) { if (Status == OperationStatus.Cancel) { return; } if (Status == OperationStatus.Paused) { await _resumeEvent.WaitAsync(); if (Status == OperationStatus.Cancel) { return; } Status = OperationStatus.Work; } var di = new DirectoryInfo(file); if (di.Exists) { var subFolder = folder.Folders.FirstOrDefault(x => x.Name.Equals(di.Name, StringComparison.OrdinalIgnoreCase)) ?? folder.CreateFolder(di.Name); var subFiles = Directory.EnumerateDirectories(di.FullName, "*", SearchOption.TopDirectoryOnly) .Concat(Directory.EnumerateFiles(di.FullName, "*", SearchOption.TopDirectoryOnly)); await Add(subFolder, subFiles); continue; } var fileName = Path.GetFileName(file); var data = File.ReadAllBytes(file); var oldFile = folder.Files.FirstOrDefault(x => x.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase)); if (oldFile == null) { folder.CreateFile(fileName, data); } else { // TODO Need get window somehow - Time to use IoC? // TODO "Yes All" and "No All" would be cool var result = await Observable.Start(() => TaskDialog.Show(Program.Window, $"{oldFile.Parent.FullName + oldFile.Name} already exists. Do you want to replace it?", buttons: TaskDialogStandardButtons.Yes | TaskDialogStandardButtons.No), RxApp.MainThreadScheduler) .ToTask(); if (result == TaskDialogResult.Yes) { oldFile.SetData(data); } } ++Progress; } }
public static IFile CreateFile(this IFolder folder, string name, string contents, Encoding encoding) { using var stream = new MemoryStream(); using var writer = new StreamWriter(stream, encoding); writer.Write(contents); writer.Flush(); stream.Position = 0; return(folder.CreateFile(name, stream, stream.Length)); }
public static IFile CreateFile(this IFolder folder, AbsoluteFilePath path, byte[] contents, CollisionStrategy collisionStrategy = CollisionStrategy.FailIfExists) { var file = folder.CreateFile(path, collisionStrategy); using (var writer = file.OpenToWrite()) { writer.Write(contents, 0, contents.Length); } return(file); }
public static void CreateFile(this IFolder folder, string path, string content) { folder.ArgumentNullExceptionByNullOrEmpty("folder"); using (var stream = folder.CreateFile(path)) { using (var tw = new StreamWriter(stream)) { tw.Write(content); } } }
public static IFile CreateFile(this IFolder folder, string name, IEnumerable <string> contents, Encoding encoding) { using var stream = new MemoryStream(); using var writer = new StreamWriter(stream, encoding); foreach (var item in contents) { writer.WriteLine(item); } writer.Flush(); stream.Position = 0; return(folder.CreateFile(name, stream, stream.Length)); }
public static bool Save(ImageFolder sub_folder, string filename, byte[] data) { IFolder rootFolder = Plugin.NetStandardStorage.CrossStorage.FileSystem.LocalStorage; IFolder folder = rootFolder.CreateFolder(sub_folder.ToString(), CreationCollisionOption.OpenIfExists); IFile file = folder.CreateFile(filename, CreationCollisionOption.ReplaceExisting); using (Stream stream = file.Open(FileAccess.ReadWrite)) { stream.Write(data, 0, data.Length); } return(true); }
public async Task <IFile> CreateFileAsync(IFolder parentFolder, string filename, CreationCollisionOption creationCollisionOption) { await Semaphore.WaitAsync(); try { return(parentFolder.CreateFile(filename, creationCollisionOption)); } finally { Semaphore.Release(); } }
public async Task ProcessStagedWorkflowFiles(Workflow workflow) { _log.LogDebug("Begin Processing Staged Workflow Files"); _log.LogDebug("Workflow Name: {WorkflowName}", workflow.Name); IFolder stagingFolder = await _GetWorkflowFolder(workflow, FolderType.Staging); IFolder destinationFolder = await _GetWorkflowFolder(workflow, FolderType.Destination); IFolder archiveFolder = await _GetWorkflowFolder(workflow, FolderType.Archive); IFolder failedFolder = await _GetWorkflowFolder(workflow, FolderType.Failed); IEnumerable <IFile> stagedFiles = await stagingFolder.GetFiles(); foreach (IFile stagedFile in stagedFiles) { _log.LogDebug("Processing {SourceFileName}", stagedFile.FullName); try { IFile destinationFile = await destinationFolder.CreateFile(_GetUnstampedName(stagedFile.Name)); using (Stream sourceStream = await stagedFile.GetReadStream()) using (Stream destinationStream = await destinationFile.GetWriteStream()) { await sourceStream.CopyToAsync(destinationStream); await destinationStream.FlushAsync(); } await stagedFile.MoveTo(archiveFolder); } catch (Exception ex) { await stagedFile.MoveTo(failedFolder); _log.LogError(ex, "Failed to process {SourceFileName}!", stagedFile.FullName); } } _log.LogDebug("Finished Processing Staged Workflow Files"); }
/// <summary> /// Get the configuration for the instance /// /// This version of the method loads directly from a named file (the file must /// still be in the 'configs' folder. /// </summary> /// <param name="forInstance"></param> /// <param name="filename"></param> /// <returns></returns> public IDictionary <string, object> GetConfigurationFromFile(Guid forInstance, string filename) { IUserObject instance; IConfigurationDescription description; if (!GetObjectInformation(forInstance, out instance, out description)) { return(null); } // Load the configuration values from the file (if it exists) IDictionary <string, object> values = null; if (m_configDirectory.FileExists(filename)) { Stream json = m_configDirectory.CreateFile(filename, FileAccessMode.Read, CreationOptions.OpenIfExists); values = ObjectPacker.UnpackRaw(json); json.Dispose(); } else { values = new Dictionary <string, object>(); } return(description.Verify(values)); }
/// <param name="logPath">The path to where this log is logging to.</param> public Log(IFolder instanceRoot) { this.LogFileInstance = instanceRoot.CreateFile("Masterlog.txt", Plugin.NetStandardStorage.Abstractions.Types.CreationCollisionOption.ReplaceExisting); this.Writer = new StreamWriter(this.LogFileInstance.Open(FileAccess.ReadWrite)); }
public static IFile CreateFile(this IFolder folder, string name) { using var stream = new MemoryStream(); return(folder.CreateFile(name, stream, 0)); }
public static IFile CreateFile(this IFolder folder, IFile file, string name) { using var stream = file.OpenRead(); return(folder.CreateFile(name, stream, file.Size)); }
public static IFile CreateFileAsync(this IFolder folder, string name, Stream stream) { return(folder.CreateFile(name, stream, stream.Length)); }
/// <inheritdoc /> public IFile CreateFile(string desiredName, CreationCollisionOption option) => _folder.CreateFile(desiredName, option);
public static IFile GetOrCreateFile(this IFolder folder, string name) { return(folder.GetFile(name) ?? folder.CreateFile(name)); }