public void Given_spaces_end_tag_when_compile_result_should_not_contains_space() { var compiler = new CollapseWhitespaceCompiler(); var content = new FileContent { Content = "<p>Oi</p> " }; compiler.Compile(content) .Content.Should().Be("<p>Oi</p>"); }
public void Given_spaces_tag_when_compile_result_should_contains_one_space() { var compiler = new CollapseWhitespaceCompiler(); var content = new FileContent { Content = " <div class='wrap'> <p> <span>Oi</span> </p> </div> " }; compiler.Compile(content) .Content.Should().Be("<div class='wrap'> <p> <span>Oi</span> </p> </div>"); }
public void Give_comments_in_end_word_when_compile_result_should_not_contains_comments() { var compiler = new RemoveHtmlCommentsCompiler(); var content = new FileContent { Content = "<p>Hi!<!-- comments --></p>" }; var result = compiler.Compile(content); result.Content.Should().Be("<p>Hi!</p>"); }
public void Given_html_template_when_compile_result_should_be_html_betwen_tag_script() { var content = new FileContent { Name = "template.tpl.html", Content = "<div>Oi!</div>" }; var compiler = new ScriptTagCompiler(); var result = compiler.Compile(content); result.Content.Should().Be("<script type=\"text/ng-template\" id=\"template.tpl.html\"><div>Oi!</div></script>"); }
public void Given_html_template_when_compile_result_should_not_be_null_or_empty() { var content = new FileContent { Name = "template.tpl.html", Content = "<div>Oi!</div>" }; var compiler = new ScriptTagCompiler(); var result = compiler.Compile(content); result.Should().NotBeNull(); result.Content.Should().NotBeNullOrEmpty(); }
public void EmptyFile() { var data = new FileContentData(new byte[0]); var file = new FileContent("file", data); Assert.AreEqual("file", file.Name); Assert.AreEqual(0, file.Data.Length); Assert.IsFalse(file.IsDead); }
public void Rewrite_BlankLine() { var cvs = new FileContent(".cvsignore", MakeContents("file1", "", "file2")); var git = CvsIgnoreFile.Rewrite(cvs); var contents = GetContents(git); Assert.AreEqual(contents.Length, 2); Assert.AreEqual(contents[0], "/file1"); Assert.AreEqual(contents[1], "/file2"); }
public IContent WritePage(ISource source, IPageData pageData, OutputData outputData) { //DataSet ds = outputData.Data as DataSet; //TkDebug.AssertArgumentNull(ds, "ds", null); //DataTable table = ds.Tables[fMetaData.Table.TableName]; byte[] midArray = NPOIWrite.ExportExcel(outputData, this); string fileName = fMetaData.Table.TableDesc + ".xls"; FileContent file = new FileContent(NetUtil.GetContentType(fileName), fileName, midArray); return new WebFileContent(file); }
public void Rewrite_SimpleFileNames() { var cvs = new FileContent(".cvsignore", MakeContents("file1", "file2")); var git = CvsIgnoreFile.Rewrite(cvs); Assert.AreEqual(git.Name, ".gitignore"); var contents = GetContents(git); Assert.AreEqual(contents.Length, 2); Assert.AreEqual(contents[0], "/file1"); Assert.AreEqual(contents[1], "/file2"); }
public void Rewrite_MultipleEntriesPerLine() { var cvs = new FileContent(".cvsignore", MakeContents("file1 file2", "file3")); var git = CvsIgnoreFile.Rewrite(cvs); Assert.AreEqual(git.Name, ".gitignore"); var contents = GetContents(git); Assert.AreEqual(contents.Length, 3); Assert.AreEqual(contents[0], "/file1"); Assert.AreEqual(contents[1], "/file2"); Assert.AreEqual(contents[2], "/file3"); }
public bool IsRoomFor(string name, FileContent fileContent) { VolumeFile existingFile = Open(name); int usedByThisFile = 0; if (existingFile != null) { usedByThisFile = existingFile.ReadAll().Size; } return INFINITE_CAPACITY == FreeSpace || FreeSpace + usedByThisFile >= fileContent.Size; }
public override VolumeFile Create(string name) { SafeHouse.Logger.Log("Creating file on harddisk " + name); if (files.ContainsKey(name)) { throw new KOSFileException("File already exists: " + name); } files[name] = new FileContent(); SafeHouse.Logger.Log("Created file on harddisk " + name); return new HarddiskFile(this, name); }
public void Give_comments_end_between_tags_multiline_when_compile_result_should_not_contains_comments() { var compiler = new RemoveHtmlCommentsCompiler(); var content = new FileContent { Content = @"<p><span>Hi!</span><!-- comments --></p>" }; var result = compiler.Compile(content); result.Content.Should().Be("<p><span>Hi!</span></p>"); }
public void IsIgnoreFile_FileInRoot() { var f = new FileContent(".cvsignore", FileContentData.Empty); Assert.IsTrue(CvsIgnoreFile.IsIgnoreFile(f)); }
private string[] GetContents(FileContent file) { var stringData = Encoding.UTF8.GetString(file.Data.Data, 0, (int)file.Data.Length); Assert.IsTrue(stringData.EndsWith(Environment.NewLine), "Has trailing newline"); // strip trailing newline so we don't return an extra line stringData = stringData.Remove(stringData.Length - 2); return stringData.Split(new[] { Environment.NewLine }, StringSplitOptions.None); }
public void Rewrite_NegatedEntry() { var cvs = new FileContent("dir1/dir2/.cvsignore", MakeContents("file1", "!file2")); var git = CvsIgnoreFile.Rewrite(cvs); var contents = GetContents(git); Assert.AreEqual(contents.Length, 2); Assert.AreEqual(contents[0], "/file1"); Assert.AreEqual(contents[1], "!/file2"); }
public void Rewrite_MultipleSpacesBetween() { var cvs = new FileContent(".cvsignore", MakeContents("file1.txt \t file2.txt")); var git = CvsIgnoreFile.Rewrite(cvs); Assert.AreEqual(git.Name, ".gitignore"); var contents = GetContents(git); Assert.AreEqual(contents.Length, 2); Assert.AreEqual(contents[0], "/file1.txt"); Assert.AreEqual(contents[1], "/file2.txt"); }
public async Task <bool> UpdateFileContent(FileContent entity) { return(await _repo.UpdateFileContent(entity)); }
public override void Execute(SharedObjects shared) { // run() is strange. It needs two levels of args - the args to itself, and the args it is meant to // pass on to the program it's invoking. First, these are the args to run itself: object volumeId = PopValueAssert(shared, true); string fileName = PopValueAssert(shared, true).ToString(); AssertArgBottomAndConsume(shared); // Now the args it is going to be passing on to the program: var progArgs = new List <object>(); int argc = CountRemainingArgs(shared); for (int i = 0; i < argc; ++i) { progArgs.Add(PopValueAssert(shared, true)); } AssertArgBottomAndConsume(shared); if (shared.VolumeMgr == null) { return; } if (shared.VolumeMgr.CurrentVolume == null) { throw new Exception("Volume not found"); } VolumeFile file = shared.VolumeMgr.CurrentVolume.Open(fileName, true); if (file == null) { throw new Exception(string.Format("File '{0}' not found", fileName)); } if (shared.ScriptHandler == null) { return; } if (volumeId != null) { Volume targetVolume = shared.VolumeMgr.GetVolume(volumeId); if (targetVolume != null) { if (shared.ProcessorMgr != null) { string filePath = string.Format("{0}/{1}", shared.VolumeMgr.GetVolumeRawIdentifier(targetVolume), fileName); var options = new CompilerOptions { LoadProgramsInSameAddressSpace = true, FuncManager = shared.FunctionManager }; List <CodePart> parts = shared.ScriptHandler.Compile(filePath, 1, file.ReadAll().String, "program", options); var builder = new ProgramBuilder(); builder.AddRange(parts); List <Opcode> program = builder.BuildProgram(); shared.ProcessorMgr.RunProgramOn(program, targetVolume); } } else { throw new KOSFileException("Volume not found"); } } else { // clear the "program" compilation context shared.Cpu.StartCompileStopwatch(); shared.ScriptHandler.ClearContext("program"); string filePath = shared.VolumeMgr.GetVolumeRawIdentifier(shared.VolumeMgr.CurrentVolume) + "/" + fileName; var options = new CompilerOptions { LoadProgramsInSameAddressSpace = true, FuncManager = shared.FunctionManager }; var programContext = ((CPU)shared.Cpu).SwitchToProgramContext(); List <CodePart> codeParts; FileContent content = file.ReadAll(); if (content.Category == FileCategory.KSM) { string prefix = programContext.Program.Count.ToString(); codeParts = content.AsParts(fileName, prefix); } else { try { codeParts = shared.ScriptHandler.Compile(filePath, 1, content.String, "program", options); } catch (Exception) { // If it died due to a compile error, then we won't really be able to switch to program context // as was implied by calling Cpu.SwitchToProgramContext() up above. The CPU needs to be // told that it's still in interpreter context, or else it fails to advance the interpreter's // instruction pointer and it will just try the "call run()" instruction again: shared.Cpu.BreakExecution(false); throw; } } programContext.AddParts(codeParts); shared.Cpu.StopCompileStopwatch(); } // Because run() returns FIRST, and THEN the CPU jumps to the new program's first instruction that it set up, // it needs to put the return stack in a weird order. Its return value needs to be buried UNDER the args to the // program it's calling: UsesAutoReturn = false; shared.Cpu.PushStack(0); // dummy return that all functions have. // Put the args for the program being called back on in the same order they were in before (so read the list backward): shared.Cpu.PushStack(new KOSArgMarkerType()); for (int i = argc - 1; i >= 0; --i) { shared.Cpu.PushStack(progArgs[i]); } }
public async Task <string> SetPersonDocument(string personId, FileContent entity, string activityId = null) { return(await _repo.CreatePersonDocument(entity, personId, activityId)); }
protected override void Seed(OnlineFileSystem.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // FileContent fileC1 = new FileContent(); fileC1.Data = new byte[] { 8, 4, 5, 5 }; FileContent fileC2 = new FileContent(); fileC2.Data = new byte[] { 8, 4, 5, 5 }; FileContent fileC3 = new FileContent(); fileC3.Data = new byte[] { 3, 4, 9, 1 }; FileContent fileC4 = new FileContent(); fileC4.Data = new byte[] { 1, 1 }; UserAccount user1 = new UserAccount(); user1.Username = "******"; user1.PasswordSalt = "nippon"; user1.Password = Utility.HashPassword("QWEqwe123", user1.PasswordSalt); user1.Email = "*****@*****.**"; user1.Role = 0; user1.Confirmationlink = "fgwergreeervevrev"; user1.DateCreated = new DateTime(2014, 10, 20); user1.DateModified = new DateTime(2014, 10, 20); user1.LastLogin = new DateTime(2015, 11, 21); UserAccount user2 = new UserAccount(); user2.Username = "******"; user2.PasswordSalt = "nihon"; user2.Password = Utility.HashPassword("123qweQWE", user2.PasswordSalt); user2.Email = "*****@*****.**"; user2.Role = 1; user2.Confirmationlink = "cerveipoviervr"; user2.DateCreated = new DateTime(2015, 10, 20); user2.DateModified = new DateTime(2015, 10, 20); user2.LastLogin = new DateTime(2015, 11, 21); Folder folder1 = new Folder(); folder1.Name = "folder1"; folder1.DateCreated = new DateTime(2015, 12, 20); folder1.DateModified = new DateTime(2016, 12, 20); folder1.OwnerUserAccount = user1; Folder folder2 = new Folder(); folder2.Name = "folder2"; folder2.DateCreated = new DateTime(2015, 12, 21); folder2.DateModified = new DateTime(2016, 12, 22); folder2.OwnerUserAccount = user2; Folder folder3 = new Folder(); folder3.Name = "folder3"; folder3.DateCreated = new DateTime(2015, 12, 23); folder3.DateModified = new DateTime(2016, 12, 24); folder3.ParentFolder = folder1; folder3.OwnerUserAccount = user1; File file1 = new File(); file1.Name = "test1.txt"; file1.Sharing = 1; file1.Link = "123214234324"; file1.FileType = "txt"; file1.Size = 3000; file1.DateCreated = new DateTime(2016, 12, 10); file1.DateModified = new DateTime(2016, 12, 10); file1.Content = fileC1; file1.ParentFolder = folder1; file1.OwnerUserAccount = file1.ParentFolder.OwnerUserAccount; File file2 = new File(); file2.Name = "test2.jpg"; file2.Sharing = 0; file2.FileType = "jpg"; file2.Size = 552384000; file2.DateCreated = new DateTime(2016, 12, 10); file2.DateModified = new DateTime(2016, 12, 11); file2.Content = fileC2; file2.ParentFolder = folder1; file2.OwnerUserAccount = file2.ParentFolder.OwnerUserAccount; File file3 = new File(); file3.Name = "test3"; file3.Sharing = 0; file3.FileType = "/"; file3.Link = "23432234"; file3.Size = 552384000; file3.DateCreated = new DateTime(2016, 12, 9); file3.DateModified = new DateTime(2016, 12, 10); file3.Content = fileC3; file3.ParentFolder = folder2; file3.OwnerUserAccount = file3.ParentFolder.OwnerUserAccount; File file4 = new File(); file4.Name = "test4"; file4.Sharing = 0; file4.FileType = "/"; file4.Link = "23432234"; file4.Size = 552384000; file4.DateCreated = new DateTime(2016, 12, 9); file4.DateModified = new DateTime(2016, 12, 10); file4.Content = fileC4; file4.OwnerUserAccount = user1; context.UserAccounts.AddOrUpdate(user1, user2); context.Folders.AddOrUpdate(folder1, folder2, folder3); context.FileContents.AddOrUpdate(fileC1, fileC2, fileC3, fileC4); context.Files.AddOrUpdate(file1, file2, file3, file4); /* * // Init of user roles * context.UserRoles.AddOrUpdate(p => p.UserRoleId, * new UserRole * { * Role = "Admin" * }, * new UserRole * { * Role = "User" * }, * new UserRole * { * Role = "Unconfirmed" * } * ); * * // init binary data * context.FileContents.AddOrUpdate(p => p.FileContentId, * new FileContent * { * Data = new byte[] { 8, 4, 5, 5 } * }, * new FileContent * { * Data = new byte[] { 8, 4, 5, 5 } * }, * new FileContent * { * Data = new byte[] { 3, 4, 9, 1 } * } * ); * * // init of sample files * context.Files.AddOrUpdate(p => p.FileId, * new File * { * Name = "test1.txt", * Sharing = 1, * Link = "123214234324", * FileType = "txt", * Size = 3000, * DateCreated = new DateTime(2016, 12, 10), * DateModified = new DateTime(2016, 12, 10), * Content = (from contents in context.FileContents where contents.FileContentId == 1 select contents).First() * }, * new File * { * Name = "test2.jpg", * Sharing = 0, * FileType = "jpg", * Size = 552384000, * DateCreated = new DateTime(2016, 12, 10), * DateModified = new DateTime(2016, 12, 11), * Content = (from contents in context.FileContents where contents.FileContentId == 2 select contents).First() * }, * new File * { * Name = "test3", * Sharing = 0, * Link = "23432234", * FileType = "/", * Size = 552384000, * DateCreated = new DateTime(2016, 12, 9), * DateModified = new DateTime(2016, 12, 10), * Content = (from contents in context.FileContents where contents.FileContentId == 3 select contents).First() * } * ); * * // init of folders * context.Folders.AddOrUpdate(p => p.FolderId, * new Folder * { * Name = "folder1", * DateCreated = new DateTime(2015, 12, 20), * DateModified = new DateTime(2016, 12, 20), * Files = (from files in context.Files where files.Name == "test1.txt" || files.Name == "test2.txt" select files).ToArray(), * Folders = (from folders in context.Folders where folders.Name == "folder3" select folders).ToArray(), * }, * new Folder * { * Name = "folder2", * DateCreated = new DateTime(2015, 12, 21), * DateModified = new DateTime(2016, 12, 22), * Files = (from files in context.Files where files.Name == "test3.txt" select files).ToArray(), * }, * new Folder * { * Name = "folder3", * DateCreated = new DateTime(2015, 12, 23), * DateModified = new DateTime(2016, 12, 24) * } * ); * * // init of users * context.UserAccounts.AddOrUpdate(p => p.UserAccountId, * new UserAccount * { * Username = "******", * Password = "******", * Email = "*****@*****.**", * Role = (from userRoles in context.UserRoles where userRoles.Role == "User" select userRoles).First(), * DateCreated = new DateTime(2014, 10, 20), * DateModified = new DateTime(2014, 10, 20), * LastLogin = new DateTime(2015, 11, 21), * Folders = (from folders in context.Folders where folders.Name == "folder1" select folders).ToArray(), * }, * new UserAccount * { * Username = "******", * Password = "******", * Email = "*****@*****.**", * Role = (from userRoles in context.UserRoles where userRoles.Role == "Unconfirmed" select userRoles).First(), * DateCreated = new DateTime(2015, 10, 20), * DateModified = new DateTime(2015, 10, 20), * LastLogin = new DateTime(2015, 11, 21), * Folders = (from folders in context.Folders where folders.Name == "folder2" select folders).ToArray(), * } * ); */ }
public new FileContent Add(FileContent fileContent) { return(EntityToData(FileContentDAL.Add(DataToEntity(fileContent)))); }
/// <summary> /// Upload Util Method for SFTP /// </summary> /// <param name="content"></param> /// <param name="folderPath"></param> /// <param name="fileName"></param> /// <param name="appendIfExist"></param> /// <param name="temporaryFolder"></param> /// <returns></returns> protected override async Task <HttpResponseMessage> UploadTransportSpecificFileAsync(FileContent content, string folderPath, string fileName, bool appendIfExist, string temporaryFolder) { if (!string.IsNullOrWhiteSpace(temporaryFolder) && appendIfExist) { throw new ArgumentException(Resources.InvalidOperationWithTemporaryFolder, "temporaryFolder"); } if (!this.ValidateController()) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest, this.validationErrors)); } string path = folderPath; string temporaryPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) + "\\"; try { Directory.CreateDirectory(temporaryPath); using (Session session = new Session()) { HttpResponseMessage response; if ((response = this.OpenSession(session)).StatusCode != HttpStatusCode.OK) { return(response); } if (string.IsNullOrWhiteSpace(temporaryFolder)) { await this.UploadToFolder(session, content.GetStream(), folderPath, fileName, temporaryPath, appendIfExist); } else { path = temporaryFolder; await this.UploadToFolder(session, content.GetStream(), temporaryFolder, fileName, temporaryPath); string tempPath = temporaryFolder + "/" + fileName; string destinationPath = folderPath + "/" + fileName; if (session.FileExists(destinationPath)) { session.RemoveFiles(destinationPath); } try { session.MoveFile(tempPath, destinationPath); } catch (SessionRemoteException ex) { Trace.TraceError("Stacktrace :" + ex.StackTrace); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format( CultureInfo.InvariantCulture, Resources.SftpAdapter_NotFound, destinationPath), ex)); } } } TC.FileInfo fileInfo = new TC.FileInfo(this.ServerAddress, folderPath, fileName); Trace.TraceInformation("UploadFile returning successfully, {0} , {1} ", folderPath, fileName); return(Request.CreateResponse(fileInfo)); } catch (SessionRemoteException ex) { return(GetErrorResponseMessage(ex, path)); } catch (PathTooLongException ex) { Trace.TraceError("Stacktrace :" + ex.StackTrace); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } catch (IOException ex) { Trace.TraceError("Stacktrace :" + ex.StackTrace); return(Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, Resources.ServiceUnavailable)); } finally { Directory.Delete(temporaryPath, true); } }
public void delete_files() { var fileContentEmpty = new FileContent(string.Empty, string.Empty); var file1 = "1\test1.json"; var file2 = "test4.json"; var fileContents = new FileContent[] { new FileContent("1\test0.json", "testData0"), new FileContent(file1, "testData1"), new FileContent("1\test2.json", "testData2"), new FileContent("2\test3.json", "testData3"), new FileContent(file2, "testData4"), }; var zipMemoryStream = new MemoryStream(); var zipStorageEngine = new ZipStorageEngine(zipMemoryStream, ZipStorageEngineMode.Write); Task.WaitAll(fileContents.Select(f => zipStorageEngine.WriteFile(f.Location, f)).ToArray()); var filesFromZipStorage = zipStorageEngine.ReadDirectory("1").Select(p => p.GetAwaiter().GetResult()).ToArray(); foreach (var file in fileContents) { file.Invoking(f => { var fileForCompare = fileContents.FirstOrDefault(p => p.Location == f.Location); fileForCompare.Should().NotBeNull(); f.Location.Should().Be(fileForCompare.Location); f.Content.Should().Be(fileForCompare.Content); }); } filesFromZipStorage.Count(p => p.Location.Contains("test3") || p.Location.Contains("test4")).Should().Be(0); filesFromZipStorage.Count().Should().Be(3); zipStorageEngine.ReadFile(file1).Should().NotBeNull(); zipStorageEngine.ReadFile(file2).Should().NotBeNull(); // delete file1 zipStorageEngine.DeleteFile(file1); filesFromZipStorage = zipStorageEngine.ReadDirectory("1").Select(p => p.GetAwaiter().GetResult()).ToArray(); foreach (var file in fileContents.Where(p => p.Location != file1)) { file.Invoking(f => { var fileForCompare = fileContents.FirstOrDefault(p => p.Location == f.Location); fileForCompare.Should().NotBeNull(); f.Location.Should().Be(fileForCompare.Location); f.Content.Should().Be(fileForCompare.Content); }); } filesFromZipStorage.SingleOrDefault(p => p.Location == file1).Should().BeNull(); filesFromZipStorage.Count(p => p.Location.Contains("test3") || p.Location.Contains("test4")).Should().Be(0); filesFromZipStorage.Count().Should().Be(2); var ff = zipStorageEngine.ReadFile(file1).GetAwaiter().GetResult(); zipStorageEngine.ReadFile(file1).GetAwaiter().GetResult().Should().Be(fileContentEmpty); zipStorageEngine.ReadFile(file2).GetAwaiter().GetResult().Should().NotBe(fileContentEmpty); // delete file1 and file2 zipStorageEngine.DeleteFile(file2); filesFromZipStorage = zipStorageEngine.ReadDirectory("1").Select(p => p.GetAwaiter().GetResult()).ToArray(); foreach (var file in fileContents.Where(p => p.Location != file1)) { file.Invoking(f => { var fileForCompare = fileContents.FirstOrDefault(p => p.Location == f.Location); fileForCompare.Should().NotBeNull(); f.Location.Should().Be(fileForCompare.Location); f.Content.Should().Be(fileForCompare.Content); }); } filesFromZipStorage.SingleOrDefault(p => p.Location == file1).Should().BeNull(); filesFromZipStorage.Count(p => p.Location.Contains("test3") || p.Location.Contains("test4")).Should().Be(0); filesFromZipStorage.Count().Should().Be(2); zipStorageEngine.ReadFile(file1).GetAwaiter().GetResult().Should().Be(fileContentEmpty); zipStorageEngine.ReadFile(file2).GetAwaiter().GetResult().Should().Be(fileContentEmpty); }
//insert PRGR public string InsertPRGRTable(FileContent content) { return(db.insertPRGR(content)); }
private void UpdateVersionNumber(FileContent fileContent) { CurrentVersionNumber++; fileContent.Version = CurrentVersionNumber; }
public override void ProcessRequest(HttpContext context) { // handle only if not already handled if (context.Response.StatusCode != -1) { return; } if (context.Request.Method == "GET") { var parts = context.Request.Path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var allParts = new string[parts.Length + 1]; allParts[0] = basedir; parts.CopyTo(allParts, 1); var fullPath = Path.GetFullPath(Path.Combine(allParts)); // check if full path is in the base directory if (!fullPath.StartsWith(basedir, StringComparison.InvariantCulture)) { context.Response.StatusCode = 403; context.Response.Content = new StringContent("Invalid file path\r\n"); return; } if (!File.Exists(fullPath) && Dir.Exists(fullPath)) { if (context.Request.Path.EndsWith("/", StringComparison.InvariantCulture)) { fullPath = Path.Combine(fullPath, "index.html"); } else { context.Response.StatusCode = 301; context.Response.Headers["location"] = context.Request.Path + "/"; context.Response.Content = new StringContent(); return; } } if (File.Exists(fullPath)) { var shortName = Path.GetFileName(fullPath); var mimetype = FileContent.MimeType(shortName); context.Response.Headers["content-type"] = mimetype; if ((mimetype == "application/font-woff") || (mimetype == "font/ttf") || (mimetype == "application/vnd.ms-fontobject")) { context.Response.StatusCode = 200; context.Response.Headers["cache-control"] = "public, max-age=" + cacheDuration; context.Response.SupportRanges = true; context.Response.Content = new FileContent(fullPath); } else { var lastModif = File.GetLastWriteTime(fullPath); string etag = "\"" + lastModif.Ticks.ToString("X") + "\""; context.Response.Headers["etag"] = etag; if (context.Request.QueryString.ContainsKey("if-none-match") && (context.Request.QueryString["if-none-match"] == etag)) { context.Response.StatusCode = 304; } else { context.Response.StatusCode = 200; context.Response.SupportRanges = true; context.Response.Content = new FileContent(fullPath); } } } } }
/// <inheritdoc /> public Task WriteFile(string subPath, FileContent content) { _contents[subPath] = content; return(Task.CompletedTask); }
/// <summary> /// Initializes a new instance of the <see cref="BlpFile"/> class. /// </summary> /// <param name="stream">A <see cref="Stream"/> that contains the BLP file.</param> public BlpFile(Stream stream) { _baseStream = stream; using (var reader = new BinaryReader(_baseStream, Encoding.ASCII, true)) { // Checking for correct Magic-Code _fileFormatVersion = reader.ReadInt32 <FileFormatVersion>(); if (_fileFormatVersion == FileFormatVersion.BLP0) { throw new NotSupportedException("Unable to open BLP0 file."); } // Reading type _formatVersion = reader.ReadInt32 <FileContent>(); if (_fileFormatVersion == FileFormatVersion.BLP2) { _isBLP2 = true; // Reading _colorEncoding, _alphaDepth, _alphaEncoding, and _hasMipMaps. _colorEncoding = reader.ReadByte(); _alphaDepth = reader.ReadByte(); _alphaEncoding = reader.ReadByte(); _hasMipMaps = reader.ReadByte(); } else { // Should be 0, 1, 4, or 8, and default to 0 if invalid. _alphaDepth = reader.ReadUInt32(); if (_formatVersion != FileContent.JPG) { _colorEncoding = 1; } } // Reading width and height _width = reader.ReadInt32(); _height = reader.ReadInt32(); if (_fileFormatVersion != FileFormatVersion.BLP2) { // http://www.wc3c.net/tools/specs/ // flag for alpha channel and team colors (usually 3, 4 or 5) // 3 and 4 means color and alpha information for paletted files // 5 means only color information, if >=5 on 'unit' textures, it won't show the team color. _extra = reader.ReadUInt32(); _hasMipMaps = reader.ReadUInt32(); } const int mipMaps = 16; _mipMapCount = 0; // Reading MipMapOffset Array _mipMapOffsets = new uint[mipMaps]; for (var i = 0; i < mipMaps; i++) { _mipMapOffsets[i] = reader.ReadUInt32(); if (_mipMapOffsets[i] != 0) { _mipMapCount++; } } // Reading MipMapSize Array _mipMapSizes = new uint[mipMaps]; for (var i = 0; i < mipMaps; i++) { _mipMapSizes[i] = reader.ReadUInt32(); } // When encoding is 1, there is no image compression and we have to read a color palette // This palette always exists when the formatVersion is set to FileContent.Direct, even when it's not used. if (_colorEncoding == 1) { const int paletteSize = 256; #if SkiaSharpColorPalette _colorPalette = new SKColor[paletteSize]; #else _colorPalette = new uint[paletteSize]; #endif // Reading palette for (var i = 0; i < paletteSize; i++) { #if SkiaSharpColorPalette _colorPalette[i] = new SKColor(reader.ReadUInt32()); #else _colorPalette[i] = reader.ReadUInt32(); #endif } } else if (_fileFormatVersion == FileFormatVersion.BLP1 && _formatVersion == FileContent.JPG) { var jpgHeaderSize = reader.ReadUInt32(); // max 624 bytes _jpgHeaderData = reader.ReadBytes((int)jpgHeaderSize); } } }
public override void Execute(SafeSharedObjects shared) { // NOTE: The built-in load() function actually ends up returning // two things on the stack: on top is a boolean for whether the program // was already loaded, and under that is an integer for where to jump to // to call it. The load() function is NOT meant to be called directly from // a user script. // (unless it's being called in compile-only mode, in which case it // returns the default dummy zero on the stack like everything else does). UsesAutoReturn = true; bool defaultOutput = false; bool justCompiling = false; // is this load() happening to compile, or to run? GlobalPath outPath = null; object topStack = PopValueAssert(shared, true); // null if there's no output file (output file means compile, not run). if (topStack != null) { justCompiling = true; string outputArg = topStack.ToString(); if (outputArg.Equals("-default-compile-out-")) { defaultOutput = true; } else { outPath = shared.VolumeMgr.GlobalPathFromObject(outputArg); } } object skipAlreadyObject = PopValueAssert(shared, false); bool skipIfAlreadyCompiled = (skipAlreadyObject is bool) ? (bool)skipAlreadyObject : false; object pathObject = PopValueAssert(shared, true); AssertArgBottomAndConsume(shared); if (pathObject == null) { throw new KOSFileException("No filename to load was given."); } GlobalPath path = shared.VolumeMgr.GlobalPathFromObject(pathObject); Volume volume = shared.VolumeMgr.GetVolumeFromPath(path); VolumeFile file = volume.Open(path, !justCompiling) as VolumeFile; // if running, look for KSM first. If compiling look for KS first. if (file == null) { throw new KOSFileException(string.Format("Can't find file '{0}'.", path)); } path = GlobalPath.FromVolumePath(file.Path, shared.VolumeMgr.GetVolumeId(volume)); if (skipIfAlreadyCompiled && !justCompiling) { var programContext = shared.Cpu.SwitchToProgramContext(); int programAddress = programContext.GetAlreadyCompiledEntryPoint(path.ToString()); if (programAddress >= 0) { // TODO - The check could also have some dependancy on whether the file content changed on // disk since last time, but that would also mean having to have a way to clear out the old // copy of the compiled file from the program context, which right now doesn't exist. (Without // that, doing something like a loop that re-wrote a file and re-ran it 100 times would leave // 100 old dead copies of the compiled opcodes in memory, only the lastmost copy being really used.) // We're done here. Skip the compile. Point the caller at the already-compiled version. shared.Cpu.PushArgumentStack(programAddress); this.ReturnValue = true; // tell caller that it already existed. return; } } FileContent fileContent = file.ReadAll(); // filename is now guaranteed to have an extension. To make default output name, replace the extension with KSM: if (defaultOutput) { outPath = path.ChangeExtension(Volume.KOS_MACHINELANGUAGE_EXTENSION); } if (path.Equals(outPath)) { throw new KOSFileException("Input and output paths must differ."); } if (shared.VolumeMgr == null) { return; } if (shared.VolumeMgr.CurrentVolume == null) { throw new KOSFileException("Volume not found"); } if (shared.ScriptHandler != null) { shared.Cpu.StartCompileStopwatch(); var options = new CompilerOptions { LoadProgramsInSameAddressSpace = true, FuncManager = shared.FunctionManager }; // add this program to the address space of the parent program, // or to a file to save: if (justCompiling) { // since we've already read the file content, use the volume from outPath instead of the source path volume = shared.VolumeMgr.GetVolumeFromPath(outPath); shared.Cpu.YieldProgram(YieldFinishedCompile.CompileScriptToFile(path, 1, fileContent.String, options, volume, outPath)); } else { var programContext = shared.Cpu.SwitchToProgramContext(); List <CodePart> parts; if (fileContent.Category == FileCategory.KSM) { try { string prefix = programContext.Program.Count.ToString(); parts = fileContent.AsParts(path, prefix); int programAddress = programContext.AddObjectParts(parts, path.ToString()); // push the entry point address of the new program onto the stack shared.Cpu.PushArgumentStack(programAddress); } catch (Exception ex) { if (ex is KOSException) { throw ex; } throw new KOSException("Error loading compiled file:\r\n{0}\r\n{1}", ex.Message, ex.StackTrace); } } else { UsesAutoReturn = false; shared.Cpu.YieldProgram(YieldFinishedCompile.LoadScript(path, 1, fileContent.String, "program", options)); } this.ReturnValue = false; // did not already exist. } shared.Cpu.StopCompileStopwatch(); } }
/// <summary> /// Factory method for creating a <see cref="TextSource"/> from <see cref="FileContent"/>. /// </summary> protected static TextSource CreateTextSource(FileContent content) { return(TextSource.FromCharArray(content.Content, content.Length)); }
public override void Execute(SafeSharedObjects shared) { // run() is strange. It needs two levels of args - the args to itself, and the args it is meant to // pass on to the program it's invoking. First, these are the args to run itself: object volumeId = PopValueAssert(shared, true); object pathObject = PopValueAssert(shared, true); AssertArgBottomAndConsume(shared); // Now the args it is going to be passing on to the program: var progArgs = new List <object>(); int argc = CountRemainingArgs(shared); for (int i = 0; i < argc; ++i) { progArgs.Add(PopValueAssert(shared, true)); } AssertArgBottomAndConsume(shared); if (shared.VolumeMgr == null) { return; } GlobalPath path = shared.VolumeMgr.GlobalPathFromObject(pathObject); Volume volume = shared.VolumeMgr.GetVolumeFromPath(path); VolumeFile volumeFile = volume.Open(path) as VolumeFile; FileContent content = volumeFile != null?volumeFile.ReadAll() : null; if (content == null) { throw new Exception(string.Format("File '{0}' not found", path)); } if (shared.ScriptHandler == null) { return; } if (volumeId != null) { throw new KOSObsoletionException("v1.0.2", "run [file] on [volume]", "None", ""); } else { // clear the "program" compilation context shared.Cpu.StartCompileStopwatch(); shared.ScriptHandler.ClearContext("program"); //string filePath = shared.VolumeMgr.GetVolumeRawIdentifier(shared.VolumeMgr.CurrentVolume) + "/" + fileName; var options = new CompilerOptions { LoadProgramsInSameAddressSpace = true, FuncManager = shared.FunctionManager }; var programContext = shared.Cpu.SwitchToProgramContext(); List <CodePart> codeParts; if (content.Category == FileCategory.KSM) { string prefix = programContext.Program.Count.ToString(); codeParts = content.AsParts(path, prefix); programContext.AddParts(codeParts); shared.Cpu.StopCompileStopwatch(); } else { shared.Cpu.YieldProgram(YieldFinishedCompile.RunScript(path, 1, content.String, "program", options)); } } // Because run() returns FIRST, and THEN the CPU jumps to the new program's first instruction that it set up, // it needs to put the return stack in a weird order. Its return value needs to be buried UNDER the args to the // program it's calling: UsesAutoReturn = false; shared.Cpu.PushArgumentStack(0); // dummy return that all functions have. // Put the args for the program being called back on in the same order they were in before (so read the list backward): shared.Cpu.PushArgumentStack(new KOSArgMarkerType()); for (int i = argc - 1; i >= 0; --i) { shared.Cpu.PushArgumentStack(progArgs[i]); } }
public static FileStreamResult GetFileStreamResult(FileContent file, bool forDownload = true) { return(GetFileStreamResult(new MemoryStream(file.Bytes), file.FileName)); }
private SourceFileParseResult ConvertSourceFile(RuntimeModelContext runtimeModelContext, AbsolutePath path, ISourceFile sourceFile) { runtimeModelContext.CancellationToken.ThrowIfCancellationRequested(); // This means that if there is any parse or binding errors conversion won't happen. if (runtimeModelContext.Logger.HasErrors) { return(new SourceFileParseResult(runtimeModelContext.Logger.ErrorCount)); } string specPath = sourceFile.Path.AbsolutePath; // If the serialized AST is available for this file, retrieve it and return instead of converting it if (sourceFile.IsPublicFacade) { var ast = ByteContent.Create(sourceFile.SerializedAst.Item1, sourceFile.SerializedAst.Item2); using (m_statistics.SpecAstDeserialization.Start(specPath)) { return(DeserializeAst(runtimeModelContext, ast)); } } Contract.Assert(!sourceFile.IsPublicFacade, "We are about to do AST conversion, so the corresponding spec file can't be a public facade, we need the real thing"); var converter = CreateAstConverter(sourceFile, runtimeModelContext, path, m_conversionConfiguration, m_workspace); SourceFileParseResult result; using (m_statistics.SpecAstConversion.Start(specPath)) { result = converter.ConvertSourceFile(); } if (runtimeModelContext.Logger.HasErrors) { // Skip serialization step if the error has occurred. return(result); } // At this point we have the computed AST, so we are in a position to generate the public surface of the file (if possible) // and serialize the AST for future reuse. var semanticModel = m_workspace.GetSemanticModel(); Contract.Assert(semanticModel != null); // Observe that here instead of using FrontEndHost.CanUseSpecPublicFacadeAndAst (that we checked for retrieving) we only require // that the associated flag is on. This is because, even though a partial reuse may not have happened, // saving is always a safe operation and the saved results may be available for future builds if (runtimeModelContext.FrontEndHost.FrontEndConfiguration.UseSpecPublicFacadeAndAstWhenAvailable()) { FileContent publicFacadeContent = CreatePublicFacadeContent(sourceFile, semanticModel); #pragma warning disable 4014 ScheduleSavePublicFacadeAndAstAsync(runtimeModelContext, path, sourceFile.Path.AbsolutePath, publicFacadeContent, result).ContinueWith( t => { runtimeModelContext.Logger.ReportFailedToPersistPublicFacadeOrEvaluationAst( runtimeModelContext.LoggingContext, #pragma warning disable SA1129 // Do not use default value type constructor new Location(), #pragma warning restore SA1129 // Do not use default value type constructor t.Exception.ToString()); }, TaskContinuationOptions.OnlyOnFaulted); #pragma warning restore 4014 } return(result); }
public void Rewrite_EscapedBackslash() { var cvs = new FileContent(".cvsignore", MakeContents(@"dir\\file.txt")); var git = CvsIgnoreFile.Rewrite(cvs); Assert.AreEqual(git.Name, ".gitignore"); var contents = GetContents(git); Assert.AreEqual(contents.Length, 1); Assert.AreEqual(contents[0], @"/dir\\file.txt"); }
public void DeleteFileContent(FileContent fileContent) { magmaGenericDbContext.Remove <FileContent>(fileContent); magmaGenericDbContext.SaveChanges(); }
public void Rewrite_FileInSubdir() { var cvs = new FileContent("dir1/dir2/.cvsignore", MakeContents("file1")); var git = CvsIgnoreFile.Rewrite(cvs); Assert.AreEqual(git.Name, "dir1/dir2/.gitignore"); }
public FileContentEditorContext(StatusControlContext statusContext, FileContent toLoad) { SetupStatusContextAndCommands(statusContext); StatusContext.RunFireAndForgetTaskWithUiToastErrorReturn(async() => await LoadData(toLoad)); }
public void Rewrite_WildcardEntry() { var cvs = new FileContent("dir1/dir2/.cvsignore", MakeContents("file*.txt")); var git = CvsIgnoreFile.Rewrite(cvs); var contents = GetContents(git); Assert.AreEqual(contents.Length, 1); Assert.AreEqual(contents[0], "/file*.txt"); }
public async Task <string> SetFileContent(FileContent entity) { return(await _repo.CreateFileContent(entity)); }
public void IsIgnoreFile_MatchesLowerCase() { var f = new FileContent("dir/.cvsignore", FileContentData.Empty); Assert.IsTrue(CvsIgnoreFile.IsIgnoreFile(f)); }
public DataPackage Checkin(ObjectIdentity objIdentity, String newContentPath) { ObjectIdentitySet objIdSet = new ObjectIdentitySet(); objIdSet.Identities.Add(objIdentity); OperationOptions operationOptions = new OperationOptions(); ContentProfile contentProfile = new ContentProfile(FormatFilter.ANY, null, PageFilter.ANY, -1, PageModifierFilter.ANY, null); operationOptions.ContentProfile = contentProfile; DataPackage checkinPackage = versionControlService.Checkout(objIdSet, operationOptions); DataObject checkinObj = checkinPackage.DataObjects[0]; checkinObj.Contents = null; FileContent newContent = new FileContent(); newContent.LocalPath = newContentPath; newContent.RenditionType = RenditionType.PRIMARY; newContent.Format = "gif"; checkinObj.Contents.Add(newContent); bool retainLock = false; List<String> labels = new List<String>(); labels.Add("test_version"); DataPackage resultDp; try { resultDp = versionControlService.Checkin(checkinPackage, VersionStrategy.NEXT_MINOR, retainLock, labels, operationOptions); } catch (Exception e) { Console.WriteLine(e.StackTrace); throw new Exception(e.Message); } return resultDp; }
public void IsIgnoreFile_MixedCase() { var f = new FileContent("dir/.CVSignore", FileContentData.Empty); Assert.IsTrue(CvsIgnoreFile.IsIgnoreFile(f)); }
public void Dispose() { _dataContext = null; _content = null; _currentPart = null; }
public void InformAutoSaveThread (Mono.TextEditor.Document content) { if (FileName == null || content == null) return; if (!autoSaveThreadRunning) StartAutoSaveThread (); IsDirty = true; lock (contentLock) { fileChanged = true; this.content = new FileContent (FileName, content); resetEvent.Set (); } }
public Task <int> Upload([FromBody][ModelBinder(BinderType = typeof(FileContentModelBinder))] FileContent downloadable) => Task.FromResult(downloadable.Content.Length);
public void Rewrite_SpaceInFilename() { var cvs = new FileContent(".cvsignore", MakeContents(@"file\ with\ spaces.txt")); var git = CvsIgnoreFile.Rewrite(cvs); Assert.AreEqual(git.Name, ".gitignore"); var contents = GetContents(git); Assert.AreEqual(contents.Length, 1); Assert.AreEqual(contents[0], @"/file\ with\ spaces.txt"); }
public override void Execute(SharedObjects shared) { object pathObject = PopValueAssert(shared, true); SerializableStructure serialized = PopValueAssert(shared, true) as SerializableStructure; AssertArgBottomAndConsume(shared); if (serialized == null) { throw new KOSException("This type is not serializable"); } string serializedString = new SerializationMgr(shared).Serialize(serialized, JsonFormatter.WriterInstance); FileContent fileContent = new FileContent(serializedString); GlobalPath path = shared.VolumeMgr.GlobalPathFromObject(pathObject); Volume volume = shared.VolumeMgr.GetVolumeFromPath(path); ReturnValue = volume.SaveFile(path, fileContent); }
public abstract VolumeFile Save(string name, FileContent content);
public async Task <string> SetPersonPhoto(string personId, FileContent entity) { return(await _repo.CreatePersonPhoto(personId, entity)); }
public FileItem(IFileOperations fileManager, string filePath) { _fileManager = fileManager; Name = Path.GetFileNameWithoutExtension(filePath); Content = new FileContent(_fileManager, filePath); }
public ActionResult <string> DeleteFileContent(FileContent fileContent) { return(genericResponseFactory.CreateGenericControllerResponse(fileContentService.DeleteFileContent(fileContent))); }
public ActionResult Upload(String FolderId) { User user = Session["User"] as User; if (user == null) { return(new RedirectResult(Url.Action("Index", "Error"))); } if (Request.Files.Count > 0) { Console.Write(Request.Files[0].GetType()); for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i] as HttpPostedFileWrapper; var sha1 = new System.Security.Cryptography.MD5CryptoServiceProvider(); var md5byte = sha1.ComputeHash(file.InputStream); String MD5 = Convert.ToBase64String(md5byte); MD5 = Hash_MD5_16(MD5); int folderId = Convert.ToInt32(FolderId); int userId = user.Id; if (folderId > 0) { userId = 1; } else { folderId = 1; } var fileContent = FileContentBLL.GetByMD5(MD5); if (fileContent != null) { var File = new File() { FileContentId = fileContent.Id, FolderId = folderId, UserId = userId, Name = file.FileName, Size = file.ContentLength.ToString(), Type = file.ContentType, UpdateTime = DateTime.Now.ToShortDateString() }; File value = FileBLL.Add(File); fileContent.Data.Close(); ResponseHelper.WriteObject(Response, new { Result = true, File = value }); } else { file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "/file/" + MD5); var content = new FileContent() { Data = file.InputStream, MD5 = MD5 }; content = FileContentBLL.Add(content); var File = new File() { FileContentId = content.Id, FolderId = folderId, UserId = userId, Name = file.FileName, Size = file.ContentLength.ToString(), Type = file.ContentType, UpdateTime = DateTime.Now.ToShortDateString() }; var value = FileBLL.Add(File); content.Data.Close(); ResponseHelper.WriteObject(Response, new { Result = true, File = value }); } } } return(null); }
public ProductImage(FileContent content) => Content = content;
public override VolumeFile SaveFile(VolumePath path, FileContent content, bool verifyFreeSpace = true) { try { if (verifyFreeSpace && !IsRoomFor(path, content)) { return null; } } catch (KOSPersistenceException) { throw new KOSPersistenceException("Can't save file over a directory: " + path); } HarddiskDirectory directory = ParentDirectoryForPath(path, true); return directory.Save(path.Name, content) as VolumeFile; }
/// <summary> /// Initializes a new instance of the WebFileContent class. /// </summary> /// <param name="content"></param> public WebFileContent(FileContent content, bool useCache) { fContent = content; fUseCache = useCache; }
/// <summary> /// Add items to FileContent ListBox /// </summary> /// <param name="fileContentArray"></param> private void PopulateFileContentList(FileContent[] fileContentArray) { this.lstFileContents.Items.Clear(); if (fileContentArray != null) { foreach (FileContent fileContent in fileContentArray) { this.lstFileContents.Items.Add(fileContent._Sequence); } this.btnSaveFile.Enabled = fileContentArray.Length > 0; this.lstFileContents.Visible = fileContentArray.Length > 0; this.lblFileContentWarning.Visible = !(fileContentArray.Length > 0); } else { this.btnSaveFile.Enabled = false; this.lstFileContents.Visible = false; this.lblFileContentWarning.Visible = true; } }
public WebFileContent(FileContent content) : this(content, false) { }
public WordIteratorFixture() { var textToAnalyse = new FileContent(@"C:\Users\tomas\Dropbox\Codecool - C#\csharp-text-analyser-T5chrono\TextAnalser.Test\TestFiles\test_simple.txt"); sutIterator = textToAnalyse.GetWordIterator(); }
private void Gutter_ScrollChanged(object sender, ScrollChangedEventArgs e) { FileContent.ScrollToVerticalOffset(e.VerticalOffset); }