public void DisplayString_FileNameIsFullPath_DisplayFormatIsCorrect() { var fileElement = new FileElement(@"c:\folder1\file1.txt", 1024); var actualDisplayString = fileElement.DisplayString; Assert.AreEqual("file1.txt [1.0 KB]", actualDisplayString); }
private void MenuItem_CreateNewTextFile(object sender, RoutedEventArgs e) { if ((listView.Tag as Element) != null) { RenameWindow newDoc = new RenameWindow(); // ".txt", ElementType.File); newDoc.Owner = this; newDoc.Title = "Новый текстовый документ"; newDoc.label.Content = "Имя файла"; if ((newDoc.ShowDialog() == true) && (newDoc.textBox.Text != "")) { Stream ms = Stream.Null; Bitmap bmp = ImgConverter.GetIcon(".txt", thumbnailSize); FileElement newTextFile = null; try { newTextFile = (listView.Tag as DirElement).AddFile(ms, newDoc.textBox.Text + ".txt", false, bmp); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } bmp?.Dispose(); ShowFiles(listView.Tag as Element, newTextFile); } } }
public FrmCustomUpdateCreator() { InitializeComponent(); customUpdateElementViewer1.ElementDoubleClick += new CustomUpdateElementViewer.CustomUpdateElementViewer.ElementDoubleClickEventHandler(addElement); ExecutableElement executableElement = new ExecutableElement(); customUpdateElementViewer1.AddElement(executableElement); ScriptElement scriptElement = new ScriptElement(); customUpdateElementViewer1.AddElement(scriptElement); TextFileElement textFileElement = new TextFileElement(); customUpdateElementViewer1.AddElement(textFileElement); FileElement fileElement = new FileElement(); customUpdateElementViewer1.AddElement(fileElement); FolderElement folderElement = new FolderElement(); customUpdateElementViewer1.AddElement(folderElement); ServiceElement serviceElement = new ServiceElement(); customUpdateElementViewer1.AddElement(serviceElement); RegistryKeyElement RegKeyElement = new RegistryKeyElement(); customUpdateElementViewer1.AddElement(RegKeyElement); RegistryElement RegElement = new RegistryElement(); customUpdateElementViewer1.AddElement(RegElement); VariableElement variableElement = new VariableElement(); customUpdateElementViewer1.AddElement(variableElement); PowerManagementElement powerElement = new PowerManagementElement(); customUpdateElementViewer1.AddElement(powerElement); WaitElement waitElement = new WaitElement(); customUpdateElementViewer1.AddElement(waitElement); KillProcessElement killElement = new KillProcessElement(); customUpdateElementViewer1.AddElement(killElement); ReturnCodeElement returnCodeElement = new ReturnCodeElement(); customUpdateElementViewer1.AddElement(returnCodeElement); lnkLblHelp.Enabled = System.IO.File.Exists("Custom Updates.pdf"); }
private void EnterProcedureParsing(string name) { if (m_file != null && m_file.TypeScanIncluded) { var proc = m_file.ListElements().FirstOrDefault(e => e.ElementType == FileElementType.ProcedureDeclaration && e.Name == name); if (proc != null) { m_currentProcedure = proc as FileProcedure; m_currentFileElement = proc as FileElement; if (((m_currentProcedure.Flags & ProcedureFlags.IsFunction) == ProcedureFlags.IsFunction) != m_procedureIsFunction) { throw new Exception("Procedure from type scanning is different type (procedure/function) than in the current parsing."); } } else { throw new Exception(""); // TODO: convert to parsing error (internal error). } } else { m_currentProcedure = new FileProcedure(m_file, m_fileElementModifier, m_elementStart.Line, null, m_currentNamespace, name); } m_currentProcedure.ReturnType = m_procedureReturnType; m_currentProcedure.Flags = (m_currentProcedure.Flags & ~ProcedureFlags.IsFunction) | (m_procedureIsFunction ? ProcedureFlags.IsFunction : ProcedureFlags.None); m_currentFileElement = m_currentProcedure; m_lastProcedure = m_currentProcedure; m_procedureStack.Push(m_currentProcedure); }
public ImageViewer(List <Element> elementList, FileElement current, System.Windows.Controls.ListView ParentListView) : this() { parentListView = ParentListView; elements = elementList; currentIndex = elementList.IndexOf(current); ShowImage(); }
public FileElement(FileElement parent, int line, ScriptData.FileElementType type, string name) { this.Parent = parent; this.Line = line; this.Type = type; this.Name = name; }
public void CanCollectLogFiles() { var fileCollector = default(FileCollector); var logger = default(TestLogger); var filePath = default(string); "Given I am collecting performance counter data" .Context(() => { logger = new TestLogger(); filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFile.txt"); var fileElement = new FileElement(); fileElement.Name = filePath; var fileConfiguration = new LogFileConfiguration(); fileConfiguration.Files.Add(fileElement); fileCollector = new FileCollector(fileConfiguration); }); "When I begin collecting".Do(() => { fileCollector.Collect(logger); File.WriteAllLines(filePath, new string[] { "This is a test"}); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); File.Delete(filePath); }); "The file content will be collected".Observation(() => logger.LogItems[0].Message.Should().Be("This is a test")); }
public void DisplaySize_FileIsJustLargerThan1GB_DisplayGbFormat() { var fileElement = new FileElement("file1.text", 1024 * 1024 * 1024 + 1); var actual = fileElement.DisplaySize; Assert.AreEqual("1.0 GB", actual); }
private static FileElement AddNewFile(FolderElement folderElement, string fileName, int fileSize) { var fileElement = new FileElement(fileName, fileSize); folderElement.Add(fileElement); return(fileElement); }
public void DisplaySize_FileIs1023Bytes_Display1023bytes() { var fileElement = new FileElement("file1.text", 1023); var actual = fileElement.DisplaySize; Assert.AreEqual("1023 Byte(s)", actual); }
public void ShortName_NormalFullPath_OnlyReturnTheFileName() { var fileElement = new FileElement(@"C:\folder1\1.txt", 100); var expected = "1.txt"; var actual = fileElement.ShortName; Assert.AreEqual(expected, actual); }
public void DisplaySize_FileIs1025Bytes_DisplayKbFormat() { var fileElement = new FileElement("file1.text", 1025); var actual = fileElement.DisplaySize; Assert.AreEqual("1.0 KB", actual); }
public void DisplaySize_FileIsJustLessThan1GB_DisplayMbFormat() { var fileElement = new FileElement("file1.text", 1024 * 1024 * 1024 - 1); var actual = fileElement.DisplaySize; Assert.AreEqual("1024.0 MB", actual); }
public RazorPageTransfer(FileInfo file) : base(file) { _file = new FileElement(Source); Entity = _file.GetTypes <ClassElement>() .Where(x => x.IsDefined("Table")) .FirstOrDefault(); FileName = $"{Entity.Name}Query.cs"; }
/// <summary> /// 初始化类<see cref="ClassDataTransfer"/>。 /// </summary> /// <param name="file">文件信息实例。</param> public ClassDataTransfer(FileInfo file) : base(file) { _file = new FileElement(Source); Entities = _file.GetTypes <ClassElement>() .Where(x => x.IsDefined("Table")) .ToList(); FileName = $"{Name}DataMigration.cs"; }
/// <summary> /// 初始化类<see cref="ClassManagerTransfer"/>。 /// </summary> /// <param name="file">文件信息实例。</param> public ClassManagerTransfer(FileInfo file) : base(file) { _file = new FileElement(Source); Entities = _file.GetTypes <ClassElement>() .Where(x => x.IsDefined("Table")) .ToList(); FileName = $"{Path.GetFileNameWithoutExtension(File.Name)}Manager.cs"; }
private void OpenTextDoc(FileElement file) { TextWindow window = new TextWindow(file) { Owner = this }; window.Show(); }
private void Convert(FileElement element, List <FileElementDTO> dtos) { var dto = ConvertElement(element); dtos.Add(dto); foreach (var child in element.Children) { Convert(child, dtos); } }
public override void ExitFileVariableWithPropertyBlock([NotNull] SBP.FileVariableWithPropertyBlockContext context) { var type = this.PopType("ExitFileVariableWithPropertyBlock"); var name = m_varName; var element = new FileElement(this.TopElement, m_elementStartLine, ScriptData.FileElementType.FileVariable, m_varName); element.ReturnTypeData = type; element.Modifiers = m_modifiers; this.TopElement.Childs.Add(element); }
public void Size_IncreseElementSize_ParentSizeAlsoIncreased() { var folderElement = new FolderElement("root"); var fileElement1 = new FileElement("file1.txt", 10); var fileElement2 = new FileElement("file2.txt", 50); folderElement.Add(fileElement1); folderElement.Add(fileElement2); // change the size from 10 to 100 fileElement1.Size = 100; Assert.AreEqual(150, folderElement.Size); }
public override void ExitTestlist([NotNull] SBP.TestlistContext context) { var name = m_name; //var parameters = m_procedureParameters; var element = new FileElement(this.TopElement, m_elementStartLine, ScriptData.FileElementType.TestList, name); element.Modifiers = m_modifiers; element.PropertyFlags = m_elementPropFlags; //element.Parameters = parameters; //element.HasBody = context.Start.Type != SBP.SEMICOLON; this.TopElement.Childs.Add(element); }
private static async Task <Document> Parse(XWPFDocument docX, string name) { var doc = new DocumentModel.Document(name); FileElement currentElement = doc; await Task.Run(() => { for (int n = 0; n < docX.Paragraphs.Count; n++) { currentElement = ParseParagraph(n, docX.Paragraphs[n], currentElement); } }); return(doc); }
public override void EnterProcedureBodyOrNothing([NotNull] SBP.ProcedureBodyOrNothingContext context) { var name = m_name; var parameters = m_procedureParameters; var element = new FileElement(this.TopElement, m_elementStartLine, ScriptData.FileElementType.ProcedureDeclaration, name); element.Modifiers = m_modifiers; element.Parameters = parameters; element.ReturnTypeData = m_returnType; element.IsFunction = m_isFunction; element.HasBody = context.Start.Type != SBP.SEMICOLON; element.PropertyFlags = m_elementPropFlags; this.TopElement.Childs.Add(element); }
private void SetNamespace(string name) { if (m_namespaceSet) { throw new Exception("Namespace already set."); } var element = new FileElement(this.TopElement, -1, ScriptData.FileElementType.Namespace, name); if (m_elementStack.Count == 0) { m_firstElement = element; } m_elementStack.Clear(); m_elementStack.Push(element); }
private FileElementDTO ConvertElement(FileElement element) { var dto = new FileElementDTO() { ParagraphNumber = element.ParagraphNumber, Genres = element.ElementData.Genres, BookTitle = element.ElementData.BookTitle, Compilers = element.ElementData.Compilers, BookSearchData = element.ElementData.BookSearchTerms, ArticleTitle = element.ElementData.ArticleTitle, Authors = element.ElementData.Authors, ArticleSearchData = element.ElementData.ArticleSearchTerms }; return(dto); }
private void CreateIndexFiles(DataTable origin, Dictionary <uint, FileElement> dest) { foreach (DataRow row in origin.Rows) { bool include = false; // If there is no include... include all (.*) if (__includeFiles.Count < 1) { __includeFiles.Add(".*"); } // Check if the filename is included String fname = (string)row["SourceFileName"]; foreach (string entry in __includeFiles) { if (TestRegex(fname, entry)) { include = true; break; } } // Check if the namespace is excluded foreach (string entry in __excludeFiles) { if (TestRegex(fname, entry)) { include = false; break; } } // If the file passed all the filters, then we must // add it to the dictionary if (include) { try { FileInfo info = new FileInfo(fname); FileElement fe = new FileElement(info.Name, info.FullName); dest.Add((uint)row["SourceFileID"], fe); } catch (Exception e) { Console.WriteLine("Error reading file {0}. Message = {1}", fname, e.Message); } // <---- end } } }
private void listView_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.Enter)) { e.Handled = true; ShowPropertiesWindow(listView.SelectedItems.Cast <Element>().ToList()); return; } if (e.Key == Key.Enter) { e.Handled = true; if (listView.SelectedItem != null) { ShowFiles(listView.SelectedItem as Element, null, true); } } if (e.Key == Key.Delete) { DeleteSelected(); e.Handled = true; } if (e.Key == Key.F2) { Rename(); } if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.P)) { OpenParentDir(listView.SelectedItem as Element); } if (e.Key == Key.C && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Alt)) == (ModifierKeys.Control | ModifierKeys.Alt) && (listView.SelectedItem != null) && listView.SelectedItem is FileElement) { movedElementFrom = listView.SelectedItem as FileElement; } if (e.Key == Key.V && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Alt)) == (ModifierKeys.Control | ModifierKeys.Alt) && (listView.SelectedItem != null) && (movedElementFrom != null) && listView.SelectedItem is FileElement) { movedElementTo = listView.SelectedItem as FileElement; MoveElementWithChange(); } }
private void CreateWixComponents(Wix model, List <string> filesTree) { try { model.Fragment.ComponentGroup = new ComponentGroupElement { Id = $"{ Working.RemoveIllegalCharacters(InstallDirPath.Substring(InstallDirPath.LastIndexOf('\\') + 1)) }FileComponents" }; model.Fragment.ComponentGroup.Components = new List <ComponentElement>(); var format = Working.GetToStringFormat(filesTree.Count); var components = model.Fragment.ComponentGroup.Components; foreach (var filePath in filesTree) { var i = components.Count + 1; var count = i.ToString(format); var fileName = Path.GetFileName(filePath); var componentDirectory = Working.GetSubDirPath(InstallDirPath, filePath); componentDirectory = componentDirectory.Substring(0, componentDirectory.Length - fileName.Length - 1).Replace('\\', '_'); var component = new ComponentElement { Id = Working.RemoveIllegalCharacters($"IDC_{ fileName }_{ count }"), Directory = Working.RemoveIllegalCharacters($"IDD_{ componentDirectory }"), Guid = ShouldGenerateGuids ? Guid.NewGuid().ToString().ToUpper() : "*", Win64 = ShouldPrepareX64Components ? "yes" : "no" }; var file = new FileElement { Id = Working.RemoveIllegalCharacters($"IDF_{ fileName }_{ count }"), Name = fileName, DiskId = "1", Source = $"$(var.SolutionDir){ Working.GetSubDirPath(InstallDirPath, filePath) }", KeyPath = "yes" }; component.File = file; components.Add(component); } } catch (Exception ex) { var message = "Exception thrown in CreateWixComponents()\n"; throw new Exception(message, ex); } }
// Initialize the directories as below // - root // - root-file1.text // - root-file2.text // - sub // - sub file1.txt // - sub file2.txt private void InitTheElementsList() { var rootFolder = new FolderElement("root"); var rootFile1 = new FileElement("root-file1.text", 100); var rootFile2 = new FileElement("root-file1.text", 100); var subFolder = new FolderElement("sub"); var subFile1 = new FileElement("sub file1.txt", 300); var subFile2 = new FileElement("sub file2.txt", 400); rootFolder.Add(rootFile1); rootFolder.Add(rootFile2); rootFolder.Add(subFolder); subFolder.Add(subFile1); subFolder.Add(subFile2); _SizeCounterViewModel.ElementList.Add(rootFolder); }
internal void Initialize() { LogEngineConfigurationSection section = LogEngineConfigurationSection.GetSection(); if (section != null && section.Loggers != null) { foreach (LoggerElement loggerEl in section.Loggers) { string targetName = loggerEl.Target; FileElement fileEl = null; if (targetName != null && section.Files != null) { fileEl = section.Files[targetName]; if (fileEl == null) { continue; } } LogLevel minLevel = GetLogLevelFromConfiguration(loggerEl.MinLevel); IFileWriter fileWriter; if (!this._writers.TryGetValue(targetName, out fileWriter)) { NcfLoggerMode writeMode = GetWriteModeFromConfiguration(fileEl.Mode); if (writeMode == NcfLoggerMode.Immediate) { fileWriter = new ImmediateFileWriter(fileEl.FileName); } else { fileWriter = new OptimizedFileWriter(fileEl.FileName); } this._writers.Add(targetName, fileWriter); } NcfLogEngine logger = new NcfLogEngine(minLevel, fileWriter); this._loggers.Add(loggerEl.Name, logger); } } }
// Use a file dialog to obtain the filenames private void GetFilenames() { GeoProcDialog dialog = new MapWinGeoProc.Dialogs.GeoProcDialog(); // // File Element 1 // FileElement file1 = dialog.Add_FileElement(MapWinGeoProc.Dialogs.GeoProcDialog.ElementTypes.OpenShapefile); file1.Caption = "First input shapefile"; file1.HelpButtonVisible = false; // // File Element 2 // FileElement file2 = dialog.Add_FileElement(MapWinGeoProc.Dialogs.GeoProcDialog.ElementTypes.OpenShapefile); file2.Caption = "Second input shapefile"; file2.HelpButtonVisible = false; // // Out File Element // FileElement outFile = dialog.Add_FileElement(MapWinGeoProc.Dialogs.GeoProcDialog.ElementTypes.SaveShapefile); outFile.Caption = "Output Shapefile"; outFile.HelpButtonVisible = false; // Show a dialog to get the filenames to work with if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } _inFile1 = file1.Filename; _inFile2 = file2.Filename; _outFile = outFile.Filename; MapWinUtility.Logger.Dbg("input file 1: " + _inFile1); MapWinUtility.Logger.Dbg("input file 2: " + _inFile2); MapWinUtility.Logger.Dbg("output file: " + _outFile); }
protected void UpdateView() { var root = new RootElement(Title) { UnevenRows = true }; var section = new Section(); root.Add(section); var desc = new Gistacular.Elements.MultilinedElement("Description") { Value = _model.Description }; desc.Tapped += ChangeDescription; section.Add(desc); var fileSection = new Section(); root.Add(fileSection); foreach (var file in _model.Files.Keys) { var key = file; if (!_model.Files.ContainsKey(key) || _model.Files[file] == null || _model.Files[file].Content == null) continue; var elName = key; if (_model.Files[key].Filename != null) elName = _model.Files[key].Filename; var el = new FileElement(elName, key, _model.Files[key]); el.Tapped += () => { if (!_model.Files.ContainsKey(key)) return; var createController = new ModifyGistFileController(key, _model.Files[key].Content); createController.Save = (name, content) => { if (string.IsNullOrEmpty(name)) throw new InvalidOperationException("Please enter a name for the file"); //If different name & exists somewhere else if (!name.Equals(key)) if (IsDuplicateName(name)) throw new InvalidOperationException("A filename by that type already exists"); if (_originalGist.Files.ContainsKey(key)) _model.Files[key] = new GistEditModel.File { Content = content, Filename = name }; else { _model.Files.Remove(key); _model.Files[name] = new GistEditModel.File { Content = content }; } }; NavigationController.PushViewController(createController, true); }; fileSection.Add(el); } fileSection.Add(new StyledElement("Add New File", AddFile)); Root = root; }
/// <summary> возвращает почищенный список строк из файла, путь к которому задаётся в качестве аргумента </summary> private void FileClearing(string filePath, FileElement file) { //выясняем не тот ли это файл, в котором сдвиг во времени и устанавливаем флаг _needToFixTime = (filePath == Path + @"\#eternal-haro.2013-02-25.log"); var dayloglist = (File.ReadAllText(filePath)).Split('\n').ToList(); foreach (var line in dayloglist) { if (RegexClass.FirstRegexForPost.Match(line).Success) { //расковыриваем строку сообщения на час, минуту, ник и тело строки byte hour, minute; string nick; ushort length; UsersLineParsing(line, out hour, out minute, out nick, out length); if (string.IsNullOrEmpty(nick)) return; //формируем полное время строки var dt = new DateTime(file.Time.Year, file.Time.Month, file.Time.Day, hour, minute, 0); //добавляем список LineElement файла к общей базе строк _linesList.Add(new LineElement(dt, nick, length)); } //в случае если распознан вход/выход else if (RegexClass.FirstRegexForJoin.Match(line).Success) { string nick, ident, prov, host; //выделяем информацию из строки JoinLineParsing(line, out nick, out ident, out prov, out host); if (string.IsNullOrEmpty(nick)) return; JoinUpdate(nick, host); } //в случае если распознано переименование else if (RegexClass.FirstRegexForRename.Match(line).Success) { string nick1, nick2; //выделяем информацию из строки RenameLineParsing(line, out nick1, out nick2); if (string.IsNullOrEmpty(nick1) || string.IsNullOrEmpty(nick2)) return; //заносим ники в базу переименований RenameUpdate(nick1, nick2); } } }