public void SimpleTest1() { var f = new PhysicalFile() { Sourcecode = "a\nabc\na" }; int result = f.GetLengthOfLine(1); Assert.AreEqual(3, result); }
public void GetIndexNormalSlashR() { var f = new PhysicalFile() { Sourcecode = "a\r\naXc\na" }; Position p = new Position(1, 1); int actual = f.GetIndex(p); Assert.AreEqual(4, actual); }
public void GetNewLinesAsTarget_rn_hitn() { var f = new PhysicalFile() { Sourcecode = "a\r\nabc\na" }; Position p = new Position(0, 2); int actual = f.GetIndex(p); Assert.AreEqual(2, actual); }
public void Write_Writes_Content_To_File() { // Arrange PhysicalFile file = new PhysicalFile(); // Act file.Write(this.filePath, "Some text").Wait(); var contentResult = File.ReadAllText(this.filePath); // Assert Assert.That(contentResult, Is.EqualTo("Some text")); }
internal async Task ProcessChildItemsAsync(string documentText, string filePath) { var physicalFile = await PhysicalFile.FromFileAsync(filePath); var spans = Scanner.GetSpans(documentText, true); var generator = SpansToContent.Convert(spans); await CreateSqlContentAsync(physicalFile, generator); await CreateEnumContentAsync(physicalFile, generator); }
public void Read_Reads_Content_From_File() { // Arrange PhysicalFile file = new PhysicalFile(); this.CreateDirectoryIfNotExists(); File.WriteAllText(this.filePath, "Some content"); // Act var contentResult = file.Read(this.filePath).Result; // Assert Assert.That(contentResult, Is.EqualTo("Some content")); }
public void Delete_Deletes_File() { // Arrange PhysicalFile file = new PhysicalFile(); this.CreateDirectoryIfNotExists(); File.Create(this.filePath); // Act file.Delete(this.filePath); // Assert Assert.That(File.Exists(this.filePath), Is.False); }
public static async Task SetAsChildItemAsync(this PhysicalFile file, PhysicalFile parent) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var projectItem = parent.AsProjectItem(); if (projectItem.ContainingProject.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { projectItem.ProjectItems.AddFromFile(file.FullPath); } else { await file.TrySetAttributeAsync("DependentUpon", parent.Text); } }
internal async Task <PhysicalFile> WriteFileAsync(string content, string path, Project project) { using (var sw = new StreamWriter(path)) { await sw.WriteAsync(content); } var file = await PhysicalFile.FromFileAsync(path); if (file == null) { file = (await project.AddExistingFilesAsync(path)).Single(); } return(file); }
public static void WriteFileData <T>(this Context context, string fileName, T obj, IStreamEncoder?encoder = null, Endian?endian = null) where T : BinarySerializable, new() { PhysicalFile file = encoder == null ? new LinearFile(context, fileName, endian) : new EncodedLinearFile(context, fileName, encoder, endian); context.AddFile(file); try { FileFactory.Write(context, fileName, obj); } finally { context.RemoveFile(file); } }
public Collection <Diagnostic> ConvertToLSPDiagnostics(IEnumerable <DiagnosticElement> errors) { PhysicalFile file = _fileRepository.PhysicalFile; Collection <Diagnostic> diagnostics = new Collection <Diagnostic>(); foreach (DiagnosticElement e in errors) { var mainDiagnostic = ConvertErrorToDiagnostic(file, e); diagnostics.Add(mainDiagnostic); var relateds = ExtractRelatedInformationOfAnError(file, e); foreach (var r in relateds) { diagnostics.Add(r); } } return(diagnostics); }
private void AddPosition(CounterExample ce, string stateCapturedStateName) { const string regex = @".*dfy\((\d+),(\d+)\)"; //anything, then dfy(00,00) var r = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Singleline); var m = r.Match(stateCapturedStateName); if (m.Success) { var lineStr = m.Groups[1].ToString(); int line = int.Parse(lineStr); ce.Line = line; ce.Col = PhysicalFile.GetLengthOfLine(line); } else { ce.Line = 0; ce.Col = 0; } }
internal async Task CreateEnumContentAsync(PhysicalFile physicalFile, ContentGenerator generator) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var language = physicalFile.AsProjectItem().ContainingProject.CodeModel.Language; var codePath = Path.ChangeExtension(physicalFile.FullPath, CodeModelLanguageConstants.vsCMLanguageVB == language ? ".dv.vb" : ".dv.cs" ); var codeProvider = CodeModelLanguageConstants.vsCMLanguageVB == language ? CodeDomProvider.CreateProvider("VisualBasic") : CodeDomProvider.CreateProvider("C#"); var fileNamespace = GenerateNamespace(physicalFile); var enumContent = generator.GetEnumCode(codeProvider, fileNamespace); if (string.IsNullOrWhiteSpace(enumContent)) { var vsFile = await PhysicalFile.FromFileAsync(codePath); if (vsFile != null) { await vsFile.TryRemoveAsync(); } return; } var file = await WriteFileAsync(enumContent, codePath, physicalFile.ContainingProject); if (file == null) { return; } await file.SetAsChildItemAsync(physicalFile); await physicalFile.ContainingProject.SaveAsync(); }
private void RunCompilation(string filePath, string[] args = null) { if (args == null) { args = new string[] { }; } var physFile = new PhysicalFile() { Filepath = filePath, Sourcecode = File.ReadAllText(filePath), Uri = new Uri(filePath) }; ExecutionEngine.printer = new ConsolePrinter(); var results = new DafnyTranslationUnit(physFile).Verify(); var repo = new FileRepository(physFile, results); compilerResults = new CompileProvider(repo, args).Compile(); }
internal async Task CreateSqlContentAsync(PhysicalFile physicalFile, ContentGenerator generator) { var sqlPath = Path.ChangeExtension(physicalFile.FullPath, ".dv.sql"); var solution = physicalFile.GetSolution(); var relativePath = physicalFile.FullPath.Replace(Path.GetDirectoryName(solution.FullPath), string.Empty); var sqlContent = generator.GetSqlCode(relativePath); var file = await WriteFileAsync(sqlContent, sqlPath, physicalFile.ContainingProject); if (file == null) { return; } await file.SetAsChildItemAsync(physicalFile); if (!string.IsNullOrWhiteSpace(generator.CopySql)) { var targetItem = FindSolutionItem(solution, generator.CopySql.Split('\\').ToArray()); if (targetItem is PhysicalFolder folder) { var copyPath = Path.Combine(folder.FullPath, Path.GetFileName(sqlPath)); var copyFile = await WriteFileAsync(sqlContent, copyPath, folder.ContainingProject); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); copyFile.SetProperty("BuildAction", "None"); } } await physicalFile.ContainingProject.SaveAsync(); }
public CounterExampleExtractor(PhysicalFile file, List <ILanguageSpecificModel> specificModels) { PhysicalFile = file; SpecificModels = specificModels; }
protected override void BeforeQueryStatus(EventArgs e) { base.BeforeQueryStatus(e); currentFile = null; ThreadHelper.JoinableTaskFactory.Run(CheckAvailabilityAsync); }
public PackageFile AddFile(string filePath) { if (!File.Exists(filePath)) { throw new ArgumentException("File does not exist.", "filePath"); } string newFileName = System.IO.Path.GetFileName(filePath); if (ContainsFolder(newFileName)) { PackageViewModel.UIServices.Show(Resources.FileNameConflictWithExistingDirectory, Types.MessageLevel.Error); return null; } bool showingRemovedFile = false; if (ContainsFile(newFileName)) { bool confirmed = PackageViewModel.UIServices.Confirm(Resources.ConfirmToReplaceExsitingFile, true); if (confirmed) { // check if we are currently showing the content of the file to be removed. // if we are, we'll need to show the new content after replacing the file. if (PackageViewModel.ShowContentViewer) { PackagePart part = this[newFileName]; if (PackageViewModel.CurrentFileInfo.File == part) { showingRemovedFile = true; } } // remove the existing file before adding the new one RemoveChildByName(newFileName); } else { return null; } } var physicalFile = new PhysicalFile(filePath); var newFile = new PackageFile(physicalFile, newFileName, this); Children.Add(newFile); newFile.IsSelected = true; this.IsExpanded = true; PackageViewModel.NotifyChanges(); if (showingRemovedFile) { ICommand command = PackageViewModel.ViewContentCommand; command.Execute(newFile); } return newFile; }
public int Update(PhysicalFile physicalFile) { return(PhysicalFileRepository.Update(physicalFile)); }
public int Insert(PhysicalFile physicalFile) { return(PhysicalFileRepository.Insert(physicalFile)); }
public void ProcessRequest(HttpContext context) { JavaScriptSerializer js = new JavaScriptSerializer(); try { //取得檔案放置路徑 var uploadPath = context.Request.Params["uploadPath"]; //取得上傳圖片類型尺寸 var strProfileID = context.Request.Params["strProfileID"]; PhysicalFile objPhysicalFile = new PhysicalFile(); //取得會使用到的相關資訊 //objArticleService = new ArticleService(); //Enum.TryParse(sArticleStatus, out objArticleStatus); //objArticle = objArticleService.GetArticle(sAnswerCode, objArticleStatus); //objSystemParam = new SysemParam(); //壓縮檔處理 foreach (string file in context.Request.Files) { HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile; //fileExtension:副檔名 String fileExtension = System.IO.Path.GetExtension(hpf.FileName).ToLower(); object result = new object(); string sZipFilePath = string.Empty; string sFolderPath = string.Empty; Image img = Image.FromStream(hpf.InputStream, true, true); //取得影像的格式 ImageFormat thisFormat = img.RawFormat; String PictureSize = ImageUploadHelper.GetProfileParm(strProfileID); String[] PictureSizeLimit = PictureSize.Replace(" ", "").Split('x'); //寬 & 高不得小於設定 //if (img.Width < Convert.ToInt32(PictureSizeLimit[0]) || img.Height < Convert.ToInt32(PictureSizeLimit[1])) //{ // String ErrorMsg = "請上傳尺寸大於" + PictureSize + "的檔案,謝謝!"; // result = new { status = "Failure", ErrorMsg = ErrorMsg }; // var jsonObjImg = js.Serialize(result); // context.Response.Write(jsonObjImg.ToString()); // break; //} if (hpf.ContentLength == 0) { continue; } //資料夾路徑 sFolderPath = System.Web.HttpContext.Current.Server.MapPath(uploadPath + "/"); List <MultiSizeImg> MultiSizeImgList = new List <MultiSizeImg>(); if (String.Equals(strProfileID, "Picture")) { MultiSizeImgList = ResizeImg(img, new String[] { "MiddlePicture", "SmallPicture" }, sFolderPath, fileExtension); } else { MultiSizeImgList = ResizeImg(img, new String[] { "BackgroundPicture" }, sFolderPath, fileExtension); } //要儲存的路徑 objPhysicalFile.CreateFolder(sFolderPath); foreach (var item in MultiSizeImgList) { //儲存圖片,需加入影像的格式,不然IE圖片不出現 item.ImageOut.Save(item.FilePath, thisFormat); } result = new { status = "Success", MultiSizeImgList = MultiSizeImgList, uploadPath = uploadPath, FolderPath = sFolderPath }; var jsonObj = js.Serialize(result); context.Response.Write(jsonObj.ToString()); } } catch (Exception ex) { object result = new { status = "Failure", ErrorMsg = "發生異常錯誤,請重新上傳" }; var jsonObjImg = js.Serialize(result); context.Response.Write(jsonObjImg.ToString()); } }
public DafnyTranslationUnit(PhysicalFile file) { _file = file ?? throw new ArgumentNullException(nameof(file), ExceptionMessages.DTU_no_physical_file_given); }
private Diagnostic ConvertErrorToDiagnostic(PhysicalFile file, DiagnosticElement e) { int line = e.Tok.line - 1; int col = e.Tok.col - 1; int length = file.GetLengthOfLine(line) - col; var range = this.CreateRange(line, col, length); if (e.Msg.EndsWith(".")) { e.Msg = e.Msg.Substring(0, e.Msg.Length - 1); } string msg; if (e.Tok.val == "anything so that it is nonnull" || e.Tok.val == null) { msg = e.Msg; } else if (e.Tok.val.Equals("{") && _fileRepository.SymbolTableManager != null) { ISymbolInformation wrappingSymbol = _fileRepository.SymbolTableManager.GetSymbolWrapperForCurrentScope(file.Uri, line, col); range = CreateRange(wrappingSymbol.Position.BodyStartToken, wrappingSymbol.Position.BodyEndToken); msg = e.Msg + $"\n at {wrappingSymbol.Name}"; } else { msg = e.Msg + $" \n at {e.Tok.val}\n "; } string src = file.Filepath.Split('/').Last(); DiagnosticSeverity severity; switch (e.Severity) { case ErrorLevel.Error: severity = DiagnosticSeverity.Error; break; case ErrorLevel.Warning: severity = DiagnosticSeverity.Warning; break; case ErrorLevel.Info: severity = DiagnosticSeverity.Information; break; default: severity = DiagnosticSeverity.Error; break; } Diagnostic d = new Diagnostic { Message = msg, Range = range, Severity = severity, Source = src }; return(d); }
/// <summary> /// This CTOR is for testing only. /// </summary> public FileRepository(PhysicalFile physFile, TranslationResult results) { PhysicalFile = physFile; Result = results; }
public CounterExampleProvider(PhysicalFile file) : this(file, FileAndFolderLocations.modelBVD) { }
/// <summary> /// Use this ctor to inject a custom model-file for testing. /// </summary> /// <param name="file">The Physical File that is to be evaluated</param> /// <param name="pathToModelBvd">Injected model file</param> public CounterExampleProvider(PhysicalFile file, string pathToModelBvd) { PhysicalFile = file; ModelBvd = pathToModelBvd; }
public FileRepository(PhysicalFile physicalFile) { PhysicalFile = physicalFile; }