public VFSDirectory(string repositoryUri, string lockUri) { try { fsManager = VFS.getManager(); directory = fsManager.resolveFile(repositoryUri); if (!directory.exists()) { directory.createFolder(); } locker = fsManager.resolveFile(lockUri); if (!locker.exists()) { locker.createFolder(); } } catch (System.IO.IOException ioe) { throw ioe; } catch (Exception e) { throw e; } }
static LuaObject CreateFileObject(Stream stream, bool autoflush) { FileObject fobj = new FileObject(stream); fobj.writer.AutoFlush = autoflush; LuaObject obj = LuaObject.FromObject(fobj); obj.Metatable = FileMetatable; return obj; }
public async Task <FileObject> FetchFile(string binaryObjectId) { FileObject file = new FileObject(); var binaryObject = repo.GetOne(Guid.Parse(binaryObjectId)); file.StoragePath = binaryObject.StoragePath; file.Name = binaryObject.Name; file.ContentType = binaryObject.ContentType; file.BlobStream = new FileStream(file?.StoragePath, FileMode.Open, FileAccess.Read); return(file); }
/// <inheritdoc /> public int GetHardLinkCount(AbsolutePath path) { lock (_drives) { FileObject file = FindFileObject(path); if (file == null) { throw new FileNotFoundException(); } return(file.NumberOfLinks); } }
private void Test() { DirectoryObject directory = new DirectoryObject("C:\\") .SubDirectory("Users") .SubDirectory("Jon") .SubDirectory("Desktop"); //Console.WriteLine("Search Parameters - Pattern: " + searchInfo.SearchPattern + " | " + searchInfo.MinimumDate.ToShortDateString() + " | " + "Max Size: " + searchInfo.MaximumSize); FileObject file = directory.File("TestRights.txt"); Globals.ResultType archiveResult = file.Archive(System.IO.Compression.CompressionLevel.NoCompression); }
public void Matches_File_False() { var fileSystem = new MockFileSystem(); fileSystem.RegisterFile(@"C:\file"); var rule = new AttributeRule(FileAttributes.System); var file = new FileObject(@"C:\file", fileSystem); var result = rule.Matches(file, null); Assert.AreEqual(false, result); }
/// <inheritdoc /> public ulong GetFileId(AbsolutePath path) { lock (_drives) { FileObject file = FindFileObject(path); if (file == null) { throw new FileNotFoundException(); } return((ulong)((long)file.GetHashCode() + int.MaxValue)); } }
public async Task <ActionResult> Index(string id, string nexturl) { if (!Request.IsAuthenticated) { return(RedirectToAction("SignIn", "Account")); } _factory = new ServiceClientFactory(); var sharepointClient = await _factory.CreateSharepointServicesClientWithAsync("MyFiles"); List <FileObject> returnResults = new List <FileObject>(); try { // Performs a search of the default Documents folder. // You could also specify other folders using the syntax: var filesResults = await _client.Files["folder_name"].ExecuteAsync(); // This results in a call to the service. var filesResults = await sharepointClient.Files.ExecuteAsync(); var files = filesResults.CurrentPage; foreach (IItem fileItem in files) { // The item to add to the result set. FileObject modelFile = new FileObject(fileItem); if (modelFile.DisplayName == "File") { returnResults.Add(modelFile); } } } catch (ODataErrorException) { return(null); } catch (DataServiceQueryException) { return(null); } catch (MissingMethodException e) { Debug.Write(e.Message); } ViewBag.LmsParams = Server.UrlEncode(id); ViewBag.NextUrl = Server.UrlEncode(nexturl); return(View(returnResults)); }
/// <summary> /// Secures the file object with a 3-DES algorithm /// </summary> public FileObject Process(FileObject fo) { FileObject file = new FileObject() { MetadataMD5 = fo.MetadataMD5, IsSecured = false }; try { file.DataContent = _3des.Decrypt(fo.DataContent); } catch (Exception ex) { throw new SmkException( string.Format(ErrorResources.UnsecureTransform_ProcessException, "DataContent", fo.Metadata.FullName), ex); } try { file.MetadataContent = _3des.Decrypt(fo.MetadataContent); } catch (Exception ex) { throw new SmkException( string.Format(ErrorResources.UnsecureTransform_ProcessException, "MetadataContent", fo.Metadata.FullName), ex); } // Deserialize the metadata file.Metadata = file.MetadataContent.XmlToObject <FileMetadata>(); // Be sure the metadata is authentic if (file.MetadataMD5 != MD5.CreateHash(file.Metadata.ToBytes())) { Logger.WriteLog(ErrorCodes.UnsecureTransform_InvalidMetadataSignature, string.Format(ErrorResources.UnsecureTransform_InvalidMetadataSignature, fo.Metadata.FullName), Severity.Warning, VerboseLevel.User); return(null); } // Be sure the original file is authentic if (file.Metadata.OriginalMD5 != MD5.CreateHash(file.DataContent)) { Logger.WriteLog(ErrorCodes.UnsecureTransform_InvalidMetadataSignature, string.Format(ErrorResources.UnsecureTransform_InvalidDataContentSignature, fo.Metadata.FullName), Severity.Warning, VerboseLevel.User); return(null); } return(file); }
public CallResult GetFileInfo(string virtualPath) { logger.Info("Getting FileInfo for {0}", virtualPath); if (mountErrorOccurred) { logger.Error("Mount error found"); return(new ErrorResult(RemoteErrorCode.MountError)); } if (mountErrorOccurred) { logger.Error("Mount error found"); return(new ErrorResult(RemoteErrorCode.MountError)); } try { if (!checkPermission(virtualPath)) { logger.Error("Permission denied"); return(new ErrorResult(RemoteErrorCode.NotAuthorizedError)); } var localPath = getLocalPath(virtualPath); if (localPath.IsNullOrEmpty()) { throw new FileNotFoundException(); } var file = new FileObject(); file.LocalPath = localPath; file.LoadFromDisk(); return(new ResponseResult(file)); } catch (Exception ex) { if (ex is FileNotFoundException || ex is DirectoryNotFoundException) { logger.Error("Item not found"); return(new ErrorResult(RemoteErrorCode.ItemNotFoundError)); } else { throw ex; } } }
public bool Connect() { if (_config.LogAnalyticsCreate | _config.LogAnalyticsRecreate | _config.Unique) { Authenticate(); GetCurrentWorkspace(); if (_config.LogAnalyticsRecreate) { return(RecreateWorkspace()); } if (_config.LogAnalyticsCreate) { return(CreateWorkspace()); } if (_config.Unique) { List <string> existingUploads = PostQueryList($"['{_config.LogAnalyticsName}_CL']|distinct RelativeUri_s", false).Select(x => x = Path.GetFileNameWithoutExtension(x)).ToList(); Log.Info($"listResults:", existingUploads); foreach (string existingUpload in existingUploads) { _instance.FileObjects.Add(new FileObject(existingUpload) { Status = FileStatus.existing }); } } } // send empty object to check connection FileObject fileObject = new FileObject(); fileObject.Stream.Set(Encoding.UTF8.GetBytes("{}")); Log.Info($"Checking connection to log analytics workspace {_config.LogAnalyticsId} ", ConsoleColor.Green); if (!PostData(fileObject, true)) { return(false); } if (_config.IsLogAnalyticsPurgeRequested()) { _arm.Authenticate(); Purge(); return(false); } return(true); }
private void addFilesToRTF() { if (toolStripComboBoxAttachments.Items.Count > 0) { //add file attaches to the rtf... for (int i = 0; i < toolStripComboBoxAttachments.Items.Count; i++) { FileObject fo = (FileObject)toolStripComboBoxAttachments.Items[i]; richMessage.Select(richMessage.TextLength, 0); richMessage.SelectedRtf = @"{\rtf1\ansi\deff0{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}" + @"\line\cf11[" + DateTime.Now.ToShortTimeString() + @"] \cf11" + Environment.UserName + @":\cf9 Attached File: " + fo.FileName + " }"; richMessage.ScrollToCaret(); } } }
private void rtbALF_TextChanged(object sender, EventArgs e) { if (AllGeneratingCode) { return; } if (clbCppFilesList.SelectedIndex != -1) { FileObject fo = (FileObject)clbCppFilesList.SelectedItem; string fileNameOnly = Path.GetFileNameWithoutExtension(fo.fileName); SourceFiles.First(x => x.fileName == fileNameOnly + ".cpp").alfCode = rtbALF.Text; } }
public bool FileAttributesAreSubset(AbsolutePath path, FileAttributes attributes) { lock (_drives) { FileObject fileObject = FindFileObject(path); if (fileObject == null) { throw new FileNotFoundException(); } return(attributes.HasFlag(fileObject.Attributes)); } }
/// <inheritdoc /> public FileAttributes GetFileAttributes(AbsolutePath path) { lock (_drives) { FileObject fileObject = FindFileObject(path); if (fileObject == null) { throw new FileNotFoundException(); } return(fileObject.Attributes); } }
public override IStatementObject VisitFile(SuperReadableParser.FileContext context) { var file = new FileObject(); var statements = context.GetRuleContexts <SuperReadableParser.StatementContext>(); foreach (var statement in statements) { var statementObj = Visit(statement); file.Children.Add(statementObj.Run); } return(file); }
public ActionResult ReadBook() { string file = @"C:\Work\TopicReview.pdf"; FileObject read_file = new FileObject(file); ViewerSettings viewerSettings = new ViewerSettings(); viewerSettings.VisibleFileOperationControls.Open = true; ViewResponse viewResponse = MvcApplication.starDocs.Viewer.CreateView( read_file, null, viewerSettings); //Redirect return(new RedirectResult(viewResponse.Url)); }
public void CanSetNameOfFileObject(string filePath) { //Assign DataObject file = new FileObject(); string expectedResult = "index.txt"; //Act file.Path = filePath; file.Name = filePath.Name(); string result = file.Name; //Assert Assert.Equal(expectedResult, result); }
public void ToStringTest() { FileObject fileObject = new FileObject(_fileUri) { LastModified = _lastModified }; CsvExceptionRecord csvExceptionRecord = new CsvExceptionRecord(fileObject.FileUri, fileObject); Assert.IsNotNull(csvExceptionRecord); string output = csvExceptionRecord.ToString(); Assert.IsTrue(output.StartsWith($"{_lastModified:o},{_pid},{_fileType},{_fileUri}"), $"output: {output}"); }
public static bool OpenProject(string filePath) { FileObject <PerhapsProject> proj = new FileObject <PerhapsProject>(filePath); if (proj.Load()) { CurrentProjectFile = proj; AppendRecentProject(filePath); return(true); } return(false); }
private bool PostData(FileObject fileObject, bool connectivityCheck = false) { Log.Debug("enter"); string jsonBody = Config.UseMemoryStream || connectivityCheck ? new StreamReader(fileObject.Stream.Get()).ReadToEnd() : File.ReadAllText(fileObject.FileUri); fileObject.Stream.Close(); byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonBody); string date = DateTime.UtcNow.ToString("r"); string signature = BuildSignature(date, jsonBytes); Log.Info($"signature length: {signature.Length} date: {date} json length: {jsonBytes.Length}\r\n file: {Path.GetFileName(fileObject.FileUri)}", ConsoleColor.Magenta); try { string uri = "https://" + Config.LogAnalyticsId + _logAnalyticsCustomLogSuffix; Log.Debug($"post uri:{uri}"); Dictionary <string, string> headers = new Dictionary <string, string>(); // send empty log name for connectivity check // successful connect will respond with badrequest headers.Add("Log-Type", connectivityCheck ? string.Empty : Config.LogAnalyticsName); headers.Add("Authorization", signature); headers.Add("x-ms-date", date); headers.Add("time-generated-field", _timeStampField); _httpClient.SendRequest( uri: uri, jsonBody: jsonBody, httpMethod: HttpMethod.Post, headers: headers, okStatus: connectivityCheck ? HttpStatusCode.BadRequest : HttpStatusCode.OK); Log.Info($"{_httpClient.Response?.ReasonPhrase}"); if (_httpClient.Success || (connectivityCheck && _httpClient.StatusCode == HttpStatusCode.BadRequest)) { return(true); } Log.Error("unsuccessful response:", _httpClient.Response); return(false); } catch (Exception e) { Log.Exception($"post exception:{e}"); return(false); } }
public void CanSetSizeOfFileObject(string filePath) { //Assign DataObject file = new FileObject(); file.Path = filePath; string expectedResult = "0KB"; //Act file.Size = filePath.FileSize(); string result = file.Size; //Assert Assert.Equal(expectedResult, result); }
public void CanSetLastAccessOfFileObject(string filePath) { //Assign DataObject file = new FileObject(); file.Path = filePath; string expectedResult = "2017/03/01 12:10:24.96"; //Act file.LastAccess = filePath.LastAccess(); string result = file.LastAccess; //Assert Assert.Equal(expectedResult, result); }
static void AppendRecentProject(string path) { FileObject <RecentProjectsContainer> container = new FileObject <RecentProjectsContainer>(recentProjFilePath); if (!container.Load()) { container.Object = new RecentProjectsContainer(); } container.Object.recentProjectPaths.AddFront(path); container.Object.recentProjectPaths = container.Object.recentProjectPaths.Distinct().ToDeque(); container.Save(); }
// Summary: // List mapping method // // Returns: // List of FileObject from a dictionary. private List <FileObject> _GetDataList(IDictionary <string, object> dic) { List <object> data = (List <object>)dic["data"]; List <FileObject> list = new List <FileObject>(); foreach (IDictionary <string, object> content in data) { FileObject fileObject = ConvertToFileObjectHelper.ConvertToFileObject(content); if (fileObject != null) { list.Add(fileObject); } } return(list); }
private void printFileObject(FileObject file) { if (file == null) { Program.ErrorLine(this, "FileObject NULL"); } else { Program.OutputLine(this, file.Name.FormatEscape()); //Program.OutputLine(this, "Path: {0}", file.Path); Program.OutputLine(this, "LastEdited: {0}", file.LastEdited); Program.OutputLine(this, "Created: {0}", file.Created); Program.OutputLine(this, "Hash: {0}", file.Hash); } }
public void Write_Create_ANewFile_When_Using_IncrementFileExtension_Option([Range(1, 101)] int i) { // Arrange var testFile = new FileObject($"{TestFile.FilePathOnly}incrementTest"); testFile.CreateOrTruncate(false); var newFileName = $"{testFile.FilePathOnly}{testFile.FileNameOnlyNoExtension}.{i}"; // Act testFile.Write($"File #{i}", FileOption.IncrementFileExtensionIfExist, Encoding.ASCII); // Assert Assert.That(FileExists(newFileName), Is.True); }
/// <inheritdoc /> public void AllowFileWrites(AbsolutePath path) { lock (_drives) { FileObject fileObject = FindFileObject(path); if (fileObject == null) { throw new FileNotFoundException( string.Format(CultureInfo.InvariantCulture, "Failed to set an Allow Writes ACL on {0}", path.Path), path.Path); } fileObject.DenyAllWrites = false; } }
private async Task HandleIfExistsInCloud(B2Db b2Db, string filePath, B2File existingB2File, ulong xhash, string parentPath, string b2Path) { // try find local object in db FileObject existingFileObject = b2Db.GetFileObject(filePath); if (existingFileObject != null && existingFileObject.B2Files.ContainsKey(existingB2File.FileId)) { // local object xhash diff from cloud, then mark this for upload if (existingFileObject.Xhash != xhash) { existingFileObject.Xhash = xhash; UploadList.Add(new UploadObject(existingFileObject, parentPath, b2Path)); } } // if existing file object is available but b2file object is not available else if (existingFileObject != null && !existingFileObject.B2Files.ContainsKey(existingB2File.FileId)) { // update b2file object and does not need to reupload if (existingB2File.ContentSHA1.Equals("none") || Utils.FilepathToSha1Hash(filePath).Equals(existingB2File.ContentSHA1.Replace("unverified:", ""), StringComparison.InvariantCultureIgnoreCase)) { existingFileObject.B2Files.Add(existingB2File.FileId, existingB2File); existingFileObject.DateModified = DateTime.Now; await b2Db.UpdateFileObject(existingFileObject); } else // mark this object to upload if diff sha { existingFileObject.Xhash = xhash; UploadList.Add(new UploadObject(existingFileObject, parentPath, b2Path)); } } else { // local not available, so check it's sha1hash when same add to db or mark to upload FileObject tempFileObject = new FileObject(filePath, xhash); if (existingB2File.ContentSHA1.Equals("none") || Utils.FilepathToSha1Hash(filePath).Equals(existingB2File.ContentSHA1.Replace("unverified:", ""), StringComparison.InvariantCultureIgnoreCase)) { tempFileObject.B2Files.Add(existingB2File.FileId, existingB2File); await b2Db.Add(tempFileObject); } else { UploadList.Add(new UploadObject(tempFileObject, parentPath, b2Path)); } } }
/// <inheritdoc /> public dynamic DeserializeFromFile(string fullFilePath) { var file = new FileObject(fullFilePath); if (file.Exist != true) { throw new FileNotFoundException(fullFilePath); } using (TextReader fileReader = file.GetStreamReader()) { using (var csv = new CsvReader(fileReader, Configuration)) { return(csv.GetRecord <dynamic>()); } } }
private static IRandomAccessScanner CreateRandomAccessScanner(string file) { var filePath = Path.Combine(rootDir, file); FileObject fo = new FileObject(filePath); var parserType = typeof(Parser); var nested = parserType.GetNestedType("Scanner", BindingFlags.NonPublic); Assert.IsNotNull(nested, "nested (Scanner) type is null"); var ctor = nested.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IFileObject) }, null); Assert.IsNotNull(ctor, "Scanner ctor is null"); return((IRandomAccessScanner)ctor.Invoke(new[] { fo })); }
/// <inheritdoc /> /// <summary> /// Serializes to file. /// </summary> /// <param name="obj">The obj.</param> /// <param name="file">The file.</param> /// <exception cref="T:System.ArgumentNullException">obj</exception> public void SerializeToFile(object obj, string fullFilePath, FileOption option = FileOption.DoNothingIfExist) { var file = new FileObject(fullFilePath); if (option == FileOption.DoNothingIfExist) { if (file.Exist == true) { return; } } using (Stream stream = file.GetFileStream(option)) { SerializeToStream(obj, stream); } }
private void Close(FileObject file) { if (file != null) { try { file.close(); } catch (System.IO.IOException ioe) { throw ioe; } catch (Exception e) { throw e; } } }
public VFSIndexInput(FileObject file) { try { content = file.getContent().getRandomAccessContent(); length = content.length; } catch (System.IO.IOException ioe) { throw ioe; } catch (Exception e) { throw e; } }
public VFSIndexOutput(FileObject file) { try { if (!file.exists()) file.createFile(); content = file.getContent().getRandomAccessContent(); } catch (System.IO.IOException ioe) { throw ioe; } catch (Exception e) { throw e; } }
public VFSLock(FileObject file,StringBuilder buffer) { lockFile = file; buf = buffer; }
private static Glob.FileSystemEnumerator CreateEnumerator(FileObject file) { var map = file.Visit(); Glob.FileSystemEnumerator e = (entityType, path) => { FileObject result; if (!map.TryGetValue(path, out result)) result = FileObject.Empty; IEnumerable<Tuple<string, Glob.FileSystemEntity>> items = result.Files.Select(t => t.AsTuple()); if (entityType != Glob.FileSystemEntity.FileOrDirectory) items = items.Where(t => t.Item2 == entityType); return items; }; return e; }
/// <summary> /// Creates a <see cref="Modification"/> instance for the given Amazon S3 object. /// </summary> /// <param name="workingDirectory">The current project's working directory.</param> /// <param name="fileObject">The <see cref="FileObject"/> to get a modification for.</param> /// <param name="type">The modification type.</param> /// <returns>The created <see cref="Modification"/>.</returns> private Modification CreateModification(string workingDirectory, FileObject fileObject, string type) { string path = fileObject.Key; if (!String.IsNullOrEmpty(this.Prefix)) { path = path.Substring(this.Prefix.Length); } if (path.StartsWith("/", StringComparison.Ordinal)) { path = path.Substring(1); } path = Path.Combine(workingDirectory, path.Replace('/', Path.DirectorySeparatorChar)); return new Modification() { FileName = Path.GetFileName(path), FolderName = Path.GetDirectoryName(path), ModifiedTime = fileObject.LastModified.ToLocalTime(), Type = type, Url = fileObject.Key }; }