////////////////////////////////////////////// //初始化 文件树函数 和 播放列表函数 private void initDefaultSettings() { TreeDB_FileName = "TreeDB.txt"; //如果文件树文件存在, 则根据文件树文件建立树。 如果不存在,那么新建文件树文件。 if (File.Exists(TreeDB_FileName)) { initTreeView(); } else { File.Create(TreeDB_FileName); } //如果 存储文件类型文件存在, 则读取信息。 如果 不存在, 则新建文件类型文件。 FileTypes_FileName = "FileTypes.txt"; if (File.Exists(FileTypes_FileName)) { //将FileTypes_File.txt内文件类型数据存入变量_fileTypes内,并且显示在窗口的TextBox内。 FileTypes = File.ReadAllText(FileTypes_FileName); TextBox_MusicFileTypesInput.Text = FileTypes; //文件后缀名列表 //List<string> fileTypes = new List<string>(); //userInput = new InputFileTypes(FileTypes); //fileTypes = userInput.FileTypesList; List <string> fileTypesList = new InputFileTypes(FileTypes).FileTypesList;//这里可以吧InputFileTypes改成工具类 // // initDataGrid(); } else { File.Create(FileTypes_FileName); } }
/// <summary> /// Creates a new <see cref="RasterImage"/> from the specified stream. /// </summary> /// <param name="imageAddress">A pointer to the address where the image data is contained.</param> /// <param name="imageLength">The length in bytes of the image data.</param> /// <param name="fileType">The type of the image contained in the stream.</param> /// <param name="pageNumber">The number of the page in the file from which the image should be created, starting at 0. Only useful for multi-page formats, such as PDF.</param> /// <param name="scale">The scale factor at which to render the image.</param> /// <param name="alpha">A boolean value indicating whether transparency (alpha) data from the image should be preserved or not.</param> /// <param name="interpolate">A boolean value indicating whether the image should be interpolated when it is resized or not.</param> public RasterImageStream(IntPtr imageAddress, long imageLength, InputFileTypes fileType, int pageNumber = 0, double scale = 1, bool alpha = true, bool interpolate = true) { using (MuPDFContext context = new MuPDFContext()) { using (MuPDFDocument document = new MuPDFDocument(context, imageAddress, imageLength, fileType)) { RoundedRectangle roundedBounds = document.Pages[pageNumber].Bounds.Round(scale); this.Width = roundedBounds.Width; this.Height = roundedBounds.Height; this.HasAlpha = alpha; this.Interpolate = interpolate; this.Id = Guid.NewGuid().ToString(); int imageSize = document.GetRenderedSize(pageNumber, scale, alpha ? MuPDFCore.PixelFormats.RGBA : MuPDFCore.PixelFormats.RGB); this.ImageDataAddress = Marshal.AllocHGlobal(imageSize); this.DataHolder = new DisposableIntPtr(this.ImageDataAddress); GC.AddMemoryPressure(imageSize); document.Render(pageNumber, scale, alpha ? MuPDFCore.PixelFormats.RGBA : MuPDFCore.PixelFormats.RGB, this.ImageDataAddress); } } }
/// <summary> /// Creates a new <see cref="RasterImage"/> from the specified stream. /// </summary> /// <param name="imageStream">The stream containing the image data.</param> /// <param name="fileType">The type of the image contained in the stream.</param> /// <param name="pageNumber">The number of the page in the file from which the image should be created, starting at 0. Only useful for multi-page formats, such as PDF.</param> /// <param name="scale">The scale factor at which to render the image.</param> /// <param name="alpha">A boolean value indicating whether transparency (alpha) data from the image should be preserved or not.</param> /// <param name="interpolate">A boolean value indicating whether the image should be interpolated when it is resized or not.</param> public RasterImageStream(Stream imageStream, InputFileTypes fileType, int pageNumber = 0, double scale = 1, bool alpha = true, bool interpolate = true) { using (MuPDFContext context = new MuPDFContext()) { IntPtr originalImageAddress; long originalImageLength; IDisposable toBeDisposed = null; GCHandle handleToFree; if (imageStream is MemoryStream ms) { int origin = (int)ms.Seek(0, SeekOrigin.Begin); originalImageLength = ms.Length; handleToFree = GCHandle.Alloc(ms.GetBuffer(), GCHandleType.Pinned); originalImageAddress = handleToFree.AddrOfPinnedObject(); } else { MemoryStream mem = new MemoryStream((int)imageStream.Length); imageStream.CopyTo(mem); toBeDisposed = mem; int origin = (int)mem.Seek(0, SeekOrigin.Begin); originalImageLength = mem.Length; handleToFree = GCHandle.Alloc(mem.GetBuffer(), GCHandleType.Pinned); originalImageAddress = handleToFree.AddrOfPinnedObject(); } using (MuPDFDocument document = new MuPDFDocument(context, originalImageAddress, originalImageLength, fileType)) { RoundedRectangle roundedBounds = document.Pages[pageNumber].Bounds.Round(scale); this.Width = roundedBounds.Width; this.Height = roundedBounds.Height; this.HasAlpha = alpha; this.Interpolate = interpolate; this.Id = Guid.NewGuid().ToString(); int imageSize = document.GetRenderedSize(pageNumber, scale, alpha ? MuPDFCore.PixelFormats.RGBA : MuPDFCore.PixelFormats.RGB); this.ImageDataAddress = Marshal.AllocHGlobal(imageSize); this.DataHolder = new DisposableIntPtr(this.ImageDataAddress); GC.AddMemoryPressure(imageSize); document.Render(pageNumber, scale, alpha ? MuPDFCore.PixelFormats.RGBA : MuPDFCore.PixelFormats.RGB, this.ImageDataAddress); } handleToFree.Free(); toBeDisposed?.Dispose(); } }
/// <summary> /// /// </summary> void TextBox_MusicFileTypesInput_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { string text = TextBox_MusicFileTypesInput.Text; userInput = new InputFileTypes(TextBox_MusicFileTypesInput.Text); File.WriteAllText(_fileTypes_FileName, text); } //throw new NotImplementedException(); }
/// <summary> /// Create a new <see cref="MuPDFDocument"/> from an array of bytes. /// </summary> /// <param name="context">The context that will own this document.</param> /// <param name="data">An array containing the data bytes that make up the document. This must not be altered until after the <see cref="MuPDFDocument"/> has been disposed! /// The address of the array will be pinned, which may cause degradation in the Garbage Collector's performance, and is thus only advised for short-lived documents. To avoid this issue, marshal the bytes to unmanaged memory and use one of the <see cref="IntPtr"/> constructors.</param> /// <param name="fileType">The type of the document to read.</param> public MuPDFDocument(MuPDFContext context, byte[] data, InputFileTypes fileType) { bool isImage = fileType == InputFileTypes.BMP || fileType == InputFileTypes.GIF || fileType == InputFileTypes.JPEG || fileType == InputFileTypes.PAM || fileType == InputFileTypes.PNG || fileType == InputFileTypes.PNM || fileType == InputFileTypes.TIFF; this.OwnerContext = context; DataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataAddress = DataHandle.Value.AddrOfPinnedObject(); ulong dataLength = (ulong)data.Length; float xRes = 0; float yRes = 0; ExitCodes result = (ExitCodes)NativeMethods.CreateDocumentFromStream(context.NativeContext, dataAddress, dataLength, FileTypeMagics[(int)fileType], isImage ? 1 : 0, ref NativeDocument, ref NativeStream, ref PageCount, ref xRes, ref yRes); if (xRes > 72) { this.ImageXRes = xRes; } else { this.ImageXRes = 72; } if (yRes > 72) { this.ImageYRes = yRes; } else { this.ImageYRes = 72; } switch (result) { case ExitCodes.EXIT_SUCCESS: break; case ExitCodes.ERR_CANNOT_OPEN_STREAM: throw new MuPDFException("Cannot open data stream", result); case ExitCodes.ERR_CANNOT_OPEN_FILE: throw new MuPDFException("Cannot open document", result); case ExitCodes.ERR_CANNOT_COUNT_PAGES: throw new MuPDFException("Cannot count pages", result); default: throw new MuPDFException("Unknown error", result); } Pages = new MuPDFPageCollection(context, this, PageCount); DisplayLists = new MuPDFDisplayList[PageCount]; }
static void Main(string[] args) { //测试SubfolderClass List <string> temp = new List <string>(); temp.Add(@"F:\music\Mozart\Mozart - Violin Concertos"); temp.Add(@"F:\music\Mozart-Requiem-Bernstein (APE)"); SubfoldersClass ftc = new SubfoldersClass(temp); ftc.test(); //假设这是返回的被选择的文件夹路径List ftc.TargetFolderPaths = temp; //得到一个装着需要的文件格式的List<string> string fileTypeInput = "mp3, cue, ape"; InputFileTypes ift = new InputFileTypes(fileTypeInput); //用来装 被筛选过的文件信息 List <FileTypeFilter> ftfList = new List <FileTypeFilter>(); for (int i = 0; i < ftc.TargetFolderPaths.Count; i++) { FileTypeFilter ftf = new FileTypeFilter(ift.FileTypesList, ftc.TargetFolderPaths[i]); ftfList.Add(ftf); } //test for (int i = 0; i < ftc.TargetFolderPaths.Count; i++) { for (int j = 0; j < ftfList[i].Count; j++) { Console.WriteLine(ftfList[i].FileNames[j]); Console.WriteLine(ftfList[i].FilePaths[j]); Console.WriteLine(); } } string filePath = @"F:\music\Bach\Bach.-.[Goldberg.Variations(Walcha.EMI.Angle)].专辑.(Flac)\033 Aria.mp3"; Tools.MusicFile musicFileTest = new MusicFile(filePath); musicFileTest.test(); Console.WriteLine(musicFileTest.MusicDuration); }
internal ClustalFileParser(ref StreamReader newFileReader, InputFileTypes newFileType) { fileReader = newFileReader; fileType = newFileType; }
public override void Evaluate(NBMessageAssembly inputAssembly) { NBOutputTerminal outTerminal = OutputTerminal("Out"); NBMessage inputMessage = inputAssembly.Message; // Create a new message from a copy of the inboundMessage, ensuring it is disposed of after use using (NBMessage outputMessage = new NBMessage(inputMessage)) { isError = false; NBMessageAssembly outAssembly = new NBMessageAssembly(inputAssembly, outputMessage); NBElement inputRoot = inputMessage.RootElement; NBElement outputRoot = outputMessage.RootElement; #region UserCode try { // check if we need to just do a test if (inputRoot["JSON"]["Data"]["headTest"] == null) { requestId = inputRoot["JSON"]["Data"]["requestId"].ValueAsString; if (inputRoot["JSON"]["Data"]["asyncRequest"] != null) { String uploadFileName = ""; if (inputRoot["JSON"]["Data"]["templateDetails"]["templates"].FirstChild["isZipUpload"].ValueAsString == "FALSE") { uploadFileName = inputRoot["JSON"]["Data"]["templateDetails"]["templates"].FirstChild["generatedName"].ValueAsString; uploadFileName = ReplaceDateTimeReferences(uploadFileName); } getUploadFileLocation(outputRoot, uploadFileName, inputRoot, requestId); } else { outputRoot["JSON"]["Data"].DeleteAllChildren(); applyLicense(outputRoot); if (isError == false) { var pdfStreams = new List <PDFStream>(); var nonZipPDFStreams = new List <PDFStream>(); foreach (NBElement template in inputRoot["JSON"]["Data"]["templateDetails"]["templates"]) { String patentDataItem = template["parentDataItem"].ValueAsString; String csvCollatedFile = ""; String isZipUpload = template["isZipUpload"].ValueAsString; String inputFileExtension = Path.GetExtension(template["templateName"].ValueAsString.ToUpper()); String outputFileExtension = Path.GetExtension(template["generatedName"].ValueAsString.ToUpper()); InputFileTypes inputFileType = (InputFileTypes)Enum.Parse(typeof(InputFileTypes), inputFileExtension.Replace(".", ""), true); OutputFileTypes outputFileType = (OutputFileTypes)Enum.Parse(typeof(OutputFileTypes), outputFileExtension.Replace(".", ""), true); String templateContent = ""; if (inputFileType != InputFileTypes.CSV) { templateContent = System.IO.File.ReadAllText(template["templateLocation"].ValueAsString); } NBElement envIn = inputRoot["JSON"]["Data"]; String documentIdentifierField = ""; if (envIn["documentIdentifierField"] != null) { documentIdentifierField = envIn["documentIdentifierField"].ValueAsString; } Boolean elementFound = true; foreach (String elementName in patentDataItem.Split('.')) { if (envIn[elementName] != null) { envIn = envIn[elementName]; } else { elementFound = false; break; } } if (elementFound == true && envIn.Children().Count() > 0) { List <NBElement> elementsToProcess = new List <NBElement>(); if (envIn.FirstChild.Name == "Item" && envIn.LastChild.Name == "Item") { elementsToProcess = envIn.ToList(); } else { elementsToProcess.Add(envIn); } String outputFileName = template["generatedName"].ValueAsString; if (outputFileType != OutputFileTypes.CSV) { Parallel.ForEach(elementsToProcess, docData => { String documentContent = templateContent; String templateName = outputFileName; String identifier = ""; if (documentIdentifierField != "") { identifier = ReplaceAllFields(docData, "[[" + documentIdentifierField + "]]"); isZipUpload = "FALSE"; } documentContent = ReplaceAllFields(docData, documentContent); templateName = ReplaceAllFields(docData, templateName); //Example of IF field - [[IFdepositAccount!=""|Deposit Account|]] Regex ifregex = new Regex(string.Format("\\[IF.*?\\]]")); foreach (Match m in ifregex.Matches(documentContent)) { String fieldContent = getFieldContent(docData, m.Value.Replace("[", "").Replace("]", "")); documentContent = documentContent.Replace("[" + m.Value, fieldContent); } //Example of IF field - [[FORMATrenewalDate|dd-MM-yyyy]] Regex formatregex = new Regex(string.Format("\\[FORMAT.*?\\]]")); foreach (Match m in formatregex.Matches(documentContent)) { String fieldName = m.Value.Replace("[", "").Replace("]", ""); if (fieldName.IndexOf('|') > -1) { String fieldFormat = fieldName.Split('|')[1]; fieldName = fieldName.Split('|')[0].Replace("FORMAT", ""); String fieldContent = ReplaceAllFields(docData, "[[" + fieldName + "]]"); if (fieldContent != "") { switch (fieldFormat.ToLower()) { case "caps": fieldContent = fieldContent.First().ToString().ToUpper() + fieldContent.Substring(1); break; case "camelcase": fieldContent = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fieldContent); break; case "lower": fieldContent = fieldContent.ToLower(); break; case "upper": fieldContent = fieldContent.ToUpper(); break; default: try { DateTime parsedDate; String pattern = "yyyy-MM-dd"; if (DateTime.TryParseExact(fieldContent, pattern, null, System.Globalization.DateTimeStyles.None, out parsedDate)) { fieldContent = String.Format("{0:" + fieldFormat + "}", parsedDate); } else { fieldContent = String.Format("{0:" + fieldFormat + "}", fieldContent); } } catch { } break; } } documentContent = documentContent.Replace("[" + m.Value, fieldContent); } } List <string> tables = new List <string>(); String docTable = documentContent; while (docTable.IndexOf("[[##TABLE") > 0) { int start = docTable.IndexOf("[[##TABLE"); int end = docTable.IndexOf("TABLE##]]"); if (end <= 0) { break; } tables.Add(docTable.Substring(start + 9, end - start - 10)); docTable = docTable.Substring(end + 1); } var rtfBuilder = new RTFBuilder(); List <String> tableNames = new List <string>(); // replace any table definitions foreach (String table in tables) { // Get Column Definitions String groupDataItem = ""; String tableName = ""; List <CommonDefinitions.ColumnDefinition> colDefs = new List <CommonDefinitions.ColumnDefinition>(); List <CommonDefinitions.TotalColumns> totalCols = new List <CommonDefinitions.TotalColumns>(); foreach (String sColDef in table.Split('|')) { if (sColDef == table.Split('|')[0]) { tableName = sColDef.Split(':')[0]; groupDataItem = sColDef.Split(':')[1]; } else { if (sColDef.Split(':').Count() == 2) { colDefs.Add(new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1])); } if (sColDef.Split(':').Count() == 3) { CommonDefinitions.ColumnDefinition colDef = new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1], sColDef.Split(':')[2]); colDefs.Add(colDef); if (colDef.isTotalColumn == true) { totalCols.Add(new CommonDefinitions.TotalColumns(tableName, (totalCols.Count + 1), colDef.fieldName)); } } if (sColDef.Split(':').Count() == 4) { CommonDefinitions.ColumnDefinition colDef = new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1], sColDef.Split(':')[2], sColDef.Split(':')[3]); colDefs.Add(colDef); if (colDef.isTotalColumn == true) { totalCols.Add(new CommonDefinitions.TotalColumns(tableName, (totalCols.Count + 1), colDef.fieldName)); } } } } tableNames.Add(tableName); byte[] tableByteArray = Encoding.ASCII.GetBytes(documentContent); MemoryStream tableStream = new MemoryStream(tableByteArray); //Document tableDoc = new Document(tableStream); Document tableDoc = new Document(); DocumentBuilder builder = new DocumentBuilder(tableDoc); builder.Write("##" + tableName + "START##"); builder.Writeln(); Aspose.Words.Tables.Table tbl = builder.StartTable(); builder.CellFormat.Borders.Top.LineStyle = LineStyle.None; builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Right.LineStyle = LineStyle.None; builder.CellFormat.Borders.Left.LineStyle = LineStyle.None; builder.CellFormat.TopPadding = 4; builder.CellFormat.BottomPadding = 4; builder.CellFormat.LeftPadding = 0; ParagraphFormat paragraphFormat = builder.ParagraphFormat; paragraphFormat.Alignment = ParagraphAlignment.Left; paragraphFormat.LeftIndent = 0; builder.Font.Name = "Arial"; builder.Font.Size = 10; builder.Font.Bold = true; builder.Font.Bold = false; Color headerFont = new Color(); headerFont = Color.FromArgb(39, 55, 96); builder.Font.Color = headerFont; foreach (CommonDefinitions.ColumnDefinition colDef in colDefs) { builder.InsertCell(); if (colDef == colDefs.First()) { builder.StartBookmark(tableName + "START"); builder.EndBookmark(tableName + "START"); } tbl.LeftIndent = -42; tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth); builder.Write(colDef.columnName); } builder.EndRow(); NBElement rowItems = docData; foreach (String elementName in groupDataItem.Split('.')) { rowItems = rowItems[elementName]; } builder.Font.Bold = false; Color contentFont = new Color(); contentFont = Color.FromArgb(128, 128, 128); builder.Font.Color = contentFont; int rowId = 1; //foreach (NBElement row in rowItems) //{ foreach (ColumnDefinition colDef in colDefs) { builder.InsertCell(); tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth); builder.Write("[[" + colDef.fieldName + "]]"); } rowId++; builder.EndRow(); foreach (ColumnDefinition colDef in colDefs) { builder.InsertCell(); tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth); builder.Write("[[" + colDef.fieldName + "Last]]"); } rowId++; builder.EndRow(); builder.EndTable(); builder.Writeln(); builder.Write("##" + tableName + "END##"); MemoryStream rtfTableStream = new MemoryStream(); tableDoc.Save(rtfTableStream, SaveFormat.Rtf); Byte[] rtfByteArray = rtfTableStream.ToArray(); String rtfDocString = Encoding.ASCII.GetString(rtfByteArray); String tableRowString = rtfDocString.Substring(rtfDocString.IndexOf("}\\trowd\\irow1\\") + 1, rtfDocString.IndexOf("}\\trowd\\irow2\\") - rtfDocString.IndexOf("}\\trowd\\irow1\\")); int insertIndex = rtfDocString.IndexOf(tableRowString) + tableRowString.Length; //String tableContents = ""; StringBuilder tableContents = new StringBuilder(rtfDocString.Substring(0, insertIndex)); int rowCount = 2; foreach (NBElement row in rowItems) { String rowString = tableRowString; foreach (ColumnDefinition colDef in colDefs) { String sData = ""; if (colDef.fieldName != "lineNo") { if (row[colDef.fieldName] != null) { sData = row[colDef.fieldName].ValueAsString; if (sData.ToUpper() == "NULL") { sData = ""; } } else { sData = colDef.defaultValue; } } else { sData = (rowCount - 1).ToString(); } if (rowCount < rowItems.Count() + 1) { rowString = rowString.Replace("[[" + colDef.fieldName + "]]", sData); } else { rtfDocString = rtfDocString.Replace("[[" + colDef.fieldName + "Last]]", sData); } } if (rowCount < rowItems.Count() + 1) { rowString = rowString.Replace("irow1", "irow" + rowCount.ToString()); tableContents.Append(rowString); } rowCount++; } tableContents.Replace(tableRowString, ""); tableContents.Append(rtfDocString.Substring(insertIndex)); String tableOnly = tableContents.ToString(); //tableOnly = tableOnly.Substring(tableOnly.IndexOf(@"\trowd", tableOnly.Length - tableOnly.IndexOf(@"{\*\latentstyles"))); int startIndex = tableOnly.IndexOf("##" + tableName + "START##") + ("##" + tableName + "START##").Length; int endIndex = tableOnly.IndexOf("##" + tableName + "END##"); tableOnly = tableOnly.Substring(startIndex, endIndex - startIndex); documentContent = documentContent.Replace("[[##TABLE" + table + "|TABLE##]]", tableOnly); } // replace any items not found in the dataset Regex regex = new Regex(string.Format("\\[.*?\\]]")); documentContent = regex.Replace(documentContent, ""); templateName = ReplaceDateTimeReferences(templateName); byte[] byteArray = Encoding.ASCII.GetBytes(documentContent); MemoryStream stream = new MemoryStream(byteArray); Document doc = new Document(stream); stream.Dispose(); //String tempFileName = @"c:\temp\FileTest\" + Guid.NewGuid().ToString(); //File.WriteAllText(tempFileName, documentContent); //Document doc = new Document(tempFileName); //File.Delete(tempFileName); foreach (String tableName in tableNames) { Bookmark bm = doc.Range.Bookmarks[tableName + "START"]; Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)bm.BookmarkStart.GetAncestor(NodeType.Table); foreach (Aspose.Words.Tables.Cell c in t.GetChildNodes(NodeType.Cell, true)) { foreach (Run run in c.GetChildNodes(NodeType.Run, true)) { Aspose.Words.Font font = run.Font; Color contentFont = new Color(); contentFont = Color.FromArgb(128, 128, 128); font.Color = contentFont; font.Name = "Arial"; } } foreach (Aspose.Words.Tables.Cell c in t.FirstRow.Cells) { foreach (Run run in c.GetChildNodes(NodeType.Run, true)) { Aspose.Words.Font font = run.Font; Color contentFont = new Color(); contentFont = Color.FromArgb(39, 55, 96); font.Color = contentFont; font.Name = "Arial"; font.Bold = true; } } } MemoryStream pdfStream = new MemoryStream(); doc.Save(pdfStream, SaveFormat.Pdf); PDFStream pdfs = new PDFStream(pdfStream.ToArray(), templateName, identifier); pdfStream.Close(); if (isZipUpload == "TRUE") { pdfStreams.Add(pdfs); } else { nonZipPDFStreams.Add(pdfs); } //} }); } if (outputFileType == OutputFileTypes.CSV) { foreach (NBElement docData in elementsToProcess) { csvCollatedFile = docData["headerRow"].ValueAsString; csvCollatedFile += Environment.NewLine; Boolean isFirstRow = true; foreach (NBElement row in docData["rows"]) { if (isFirstRow == true) { isFirstRow = false; } else { csvCollatedFile += Environment.NewLine; } csvCollatedFile += row.ValueAsString; } } byte[] byteArray = Encoding.ASCII.GetBytes(csvCollatedFile); outputFileName = ReplaceDateTimeReferences(outputFileName); outputFileName = getUploadFileName(outputFileName, inputRoot); if (isZipUpload == "TRUE") { pdfStreams.Add(new PDFStream(byteArray, outputFileName)); } else { nonZipPDFStreams.Add(new PDFStream(byteArray, outputFileName)); } } } } if (pdfStreams.Count() > 0) { byte[] zipContent = writeContentToZip(pdfStreams, outputRoot); writeFileToBlobStore(outputRoot, zipContent, inputRoot, requestId); } if (nonZipPDFStreams.Count() > 0) { writeMultiFilesToBlobStore(outputRoot, nonZipPDFStreams, inputRoot, requestId); outputRoot["JSON"]["Data"].CreateFirstChild("requestId").SetValue(requestId); } } } } else { outputRoot["JSON"]["Data"].DeleteAllChildren(); checkBlobStore(inputRoot, outputRoot); } } catch (Exception e) { handleError("PDF10000", e, outputRoot, "General Error in PDF Generation Process"); } #endregion UserCode // Change the following if not propagating message to the 'Out' terminal outTerminal.Propagate(outAssembly); } }
/// <summary> /// Create a new <see cref="MuPDFDocument"/> from data bytes accessible through the specified pointer. /// </summary> /// <param name="context">The context that will own this document.</param> /// <param name="dataAddress">A pointer to the data bytes that make up the document.</param> /// <param name="dataLength">The number of bytes to read from the specified address.</param> /// <param name="fileType">The type of the document to read.</param> public MuPDFDocument(MuPDFContext context, IntPtr dataAddress, long dataLength, InputFileTypes fileType) : this(context, dataAddress, dataLength, fileType, ref NullDataHolder) { }
public static SequenceFileParser DetermineFileType(ref StreamReader fileReader) // Read the first lines of a file to determine what type it is so that the appropriate parser can be assigned. { string lineIn = ""; SequenceFileParser fileParser; InputFileTypes fileType = InputFileTypes.None; // To be removed once Clustal method is replicated. // Find the first non-whitespace line while (!fileReader.EndOfStream) { lineIn = fileReader.ReadLine(); if (!String.IsNullOrWhiteSpace(lineIn)) { break; } } // Trim trailing whitespace. lineIn.TrimEnd(); // Evaluate the first line to determine the file type. if (lineIn.StartsWith("CLUSTAL", StringComparison.OrdinalIgnoreCase)) { // Should go first because it will be one of the most frequent files opened. fileParser = new ClustalFileParser(ref fileReader, InputFileTypes.Clustal); } else if (lineIn.StartsWith(">", StringComparison.Ordinal)) { // FASTA/Pearson is probably the next-most common type. Also indicates PIR. if (lineIn.Length >= 3 && lineIn[3] == ';') { fileType = InputFileTypes.PIR; } else { fileType = InputFileTypes.FASTAPearson; } throw new NotImplementedException(); } else if (lineIn.StartsWith("ID", StringComparison.OrdinalIgnoreCase)) { fileType = InputFileTypes.EMBLSwissProt; throw new NotImplementedException(); } else if (lineIn.StartsWith("LOCUS", StringComparison.OrdinalIgnoreCase)) { fileType = InputFileTypes.GenBank; throw new NotImplementedException(); } else if (lineIn.StartsWith("!!AA_MULTIPLE_ALIGNMENT", StringComparison.OrdinalIgnoreCase) || lineIn.StartsWith("!!NA_MULTIPLE_ALIGNMENT", StringComparison.OrdinalIgnoreCase) || lineIn.StartsWith("MSF", StringComparison.OrdinalIgnoreCase) || lineIn.StartsWith("PILEUP", StringComparison.OrdinalIgnoreCase)) { fileType = InputFileTypes.MSF; throw new NotImplementedException(); } else if (lineIn.StartsWith("!!RICH_SEQUENCE", StringComparison.OrdinalIgnoreCase)) { fileType = InputFileTypes.RSF; throw new NotImplementedException(); } else if (lineIn.StartsWith("\"", StringComparison.Ordinal) || lineIn.StartsWith("%", StringComparison.Ordinal) || lineIn.StartsWith("#", StringComparison.Ordinal)) { fileType = InputFileTypes.GDE; throw new NotImplementedException(); // Note: % = Protein, # = DNA } else if (lineIn.StartsWith("#NEXUS", StringComparison.OrdinalIgnoreCase)) { fileType = InputFileTypes.NEXUS; throw new NotImplementedException(); } else { fileType = InputFileTypes.None; throw new NotImplementedException(); } // Rewind the FileReader fileReader.DiscardBufferedData(); fileReader.BaseStream.Position = 0; return(fileParser); }