none
Need help with capture string on next line

    Question

  • How can I capture the highlighted string:

    	--------------------------- Message Text ---------------------------	
            20: Sender's Reference
                34985-61283
           23B: xxxxxx xxxxxx xxx

    Using the below code:

                    foreach (var item in contents)
                    {
                        if (item.Contains("20:"))
                        {
                                string filename = item.Substring(item.LastIndexOf(':') + 1);
                                if (filename.Contains(@"/"))
                                {
                                    filename = filename.Replace(@"/", "");
                                    //Create a new instance of PDFWriter Class for output file 
                                    {
                                        GetInstance(destPath + filename + "_" + getDate + ".pdf");
                                    }
                                }
                                else
                                    GetInstance(destPath + filename + "_" + getDate + ".pdf");
                            }
                           
                         }

    Wednesday, March 29, 2017 11:59 AM

Answers

All replies

  • It really depends upon how unique this string is in the file you're parsing. If there is only 1 20: then your if statement should find it. The rest of the code inside there is looking at the filename so I'm not sure what it is trying to do. Once you've found the line you can then parse the reset of the lines knowing the layout of the file.

    For example, if you are confident line 20: contains the sender's reference and the reference is on the next line then you can simply go to the next line in the file and read the value out. (Note: This code has not been tested).

    string GetSenderReference ( IEnumerable<string> lines )
    {
       //Find the line with 20:
       var messageText = lines.SkipWhile(l => !l.Contains("20:");
    
       //Now read the next line which contains the sender reference
       return messageText.Skip(1).FirstOrDefault();
    }

    Note that you'll likely want to break this up into multiple methods so it is easier to understand and maintain (eg. FindMessageText, GetSenderReference, etc).

    Michael Taylor
    http://www.michaeltaylorp3.net

    Wednesday, March 29, 2017 2:11 PM
    Moderator
  • thank you,

    I tried to get it to work, but I am not sure to how.. Can you please help?

    Complete code:

    /*
       Microsoft SQL Server Integration Services Script Task
       Write scripts using Microsoft Visual C# 2008.
       The ScriptMain is the entry point class of the script.
    */
    
    using System;
    using System.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    using System.IO;
    using iTextSharp;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using iTextSharp.text.pdf.draw;
    
    namespace ST_2de9c3837a8046bb9f016a4a3552f948.csproj
    {
        [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
        public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
        {
    
            #region VSTA generated code
            enum ScriptResults
            {
                Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
                Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
            };
            #endregion
    
            /*
    		The execution engine calls this method when the task executes.
    		To access the object model, use the Dts property. Connections, variables, events,
    		and logging features are available as members of the Dts property as shown in the following examples.
    
    		To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
    		To post a log entry, call Dts.Log("This is my log text", 999, null);
    		To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
    
    		To use the connections collection use something like the following:
    		ConnectionManager cm = Dts.Connections.Add("OLEDB");
    		cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
    
    		Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
    		
    		To open Help, press F1.
    	*/
    
            public void Main()
            {
                // TODO: Add your code here
    
                CreatePDFs("", "");
    
                Dts.TaskResult = (int)ScriptResults.Success;
            }
            Document doc;  //Create a New instance on Document Class
    
            void GetInstance(String str)
            {
    
                //Create a New instance of PDFWriter Class for Output File
                PdfWriter.GetInstance(doc, new FileStream(str, FileMode.Create));
    
            }
    
            void GetSenderReference(IEnumerable<string> lines)
            {
                //Find the line with 20:
                var messageText = lines.SkipWhile(l => !l.Contains("20:"));
    
                //Now read the next line which contains the sender reference
                return messageText.Skip(1).FirstOrDefault();
            }
    
            private void CreatePDFs(String sourecePath, String destPath)
            {
                string getDate = DateTime.Now.ToString("ddMMyyyy");
    
                sourecePath = (@"\\hqofc\ack_current$\");
    
                destPath = (@"\\hqofc\ack_current$\");
    
                //Create a Output Directory for storing individual PDF files
                Directory.CreateDirectory(destPath);
                DirectoryInfo dir = new DirectoryInfo(sourecePath);
                FileInfo[] files = dir.GetFiles("*.prt"); //filter the files....
    
                foreach (FileInfo f in files) //iternate throguh the file infos
                {
                    
                    //Create a New instance on Document Class
                    doc = new Document();
                    String var = f.FullName; //get the name of the file..... 
    
                    //to get the file content name
    
                    String[] contents = File.ReadAllLines(var);
                    foreach (var item in contents)
                    {
                        if (item.Contains("20:"))
                        {
                            //string filename = GetSenderReference(item.);
                            string filename = item.Substring(item.LastIndexOf(':'));
                                if (filename.Contains(@"/"))
                                {
                                    filename = filename.Replace(@"/", "");
                                    //Create a new instance of PDFWriter Class for output file 
                                    {
                                        GetInstance(destPath + filename + "_" + getDate + ".pdf");
                                    }
                                }
                                else
                                    GetInstance(destPath + filename + "_" + getDate + ".pdf");
                            }
                           
                         }
    
                    using (StreamReader rdr = new StreamReader(var))
                    {
                        //Set document layout to landscape
                        doc.SetPageSize(PageSize.A4.Rotate());
    
                        //Open the Document
                        doc.Open();
    
                        //Set font type and size
                        BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                        Font times = new Font(bfTimes, 8, Font.NORMAL);
    
                        //Add the content of Text File to PDF File
                        doc.Add(new Paragraph(rdr.ReadToEnd().ToString(), times));
    
                        //Close the Document
                        doc.Close();
                       
                    }
                    //Clear the text files
                    f.Delete();
                }
            }
        }
    }

    Thursday, March 30, 2017 6:19 AM
  • Inside of CreatePDFs where you have the foreach loop that says foreach (var item in contents), replace that with the method I posted. Since this is evidently what you're going to use for the filename the remainder of the code around the filename stays.

    //to get the file content name
    var contents = File.ReadAllLines(var);
    var senderReference = GetSenderReference(contents);
    if (!String.IsNullOrEmpty(senderReference))
    {
       //I don't understand why you're doing this because it doesn't line up with what you asked for in your post
       //This line would get everything after 20: which is simply Sender's Reference
       //I'm assuming that you wanted the next line because that
       //is the sender's reference (34985-...) and that should be the name
       //of the file...
       //string filename = item.Substring(item.LastIndexOf(':'));
       var filename = senderReference;
    
       //Do you really need to deal with sender reference
       //#s that have a slash in them?   
    
       //Get rid of slashes
       filename = filename.Replace(@"/", "");
       
       //Create a new instance of PDFWriter Class for output file 
       GetInstance(destPath + filename + "_" + getDate + ".pdf");
    }  

    • Marked as answer by Matt_90 Thursday, March 30, 2017 4:51 PM
    • Unmarked as answer by Matt_90 Sunday, April 2, 2017 6:41 AM
    Thursday, March 30, 2017 1:43 PM
    Moderator
  • Hi,

    I appreciate your help.. 

    I will try to include the "Sender's Reference" with sender's reference numbers..  I know it sounds like a loop.

    Thank you,

    Thursday, March 30, 2017 4:51 PM
  • Hi,

    I tried to get it to work..

    I am not sure how to resolve the below errors..

    Error 1 The best overloaded method match for 'ST_2de9c3837a8046bb9f016a4a3552f948.csproj.ScriptMain.GetSenderReference(IEnumerable<string>)' has some invalid arguments C:\Users\mat\AppData\Local\Temp\6\SSIS\89bb71089d364dd0966c7b34904533fe\ScriptMain.cs 105 39 st_2de9c3837a8046bb9f016a4a3552f948

    Error 2 Argument '1': cannot convert from 'string[]' to 'IEnumerable<string>' C:\Users\mat\AppData\Local\Temp\6\SSIS\89bb71089d364dd0966c7b34904533fe\ScriptMain.cs 105 58 st_2de9c3837a8046bb9f016a4a3552f948

    Will try to figure it out..

    Thanks anyway

    Sunday, April 2, 2017 6:41 AM
  • Issue resolved using for loop and index.

    • Marked as answer by Matt_90 Sunday, April 2, 2017 6:17 PM
    Sunday, April 2, 2017 6:17 PM