Solved

How to incorporate a queue into a C# console application to read field values?

Posted on 2011-09-13
2
206 Views
Last Modified: 2013-12-17
I am developing a C# console application using Visual Studio 2005.

I read as input, an XML file and then I create an Error report, if any of the individual fields within each record have an invalid value.

If a particular field has an error, I display the "Check Number" for this record and the field value in error.

In the code section that follows, I display a sample record that serves as my input file.

The problem I am facing is that I want to display the Check Number field value as the identifying field for each record with an error. However, the Check Number is the 4th field to be read from the XML input file in the field sequence.

Thus, if there is an error in the 1st, 2nd, or 3rd field, I don't have the check number field value yet to display for my error report.

My code is in the code section that follows.

Do you know how this application code could be modified to create error records showing the Check Number value, when an error occurs in any field, including the first 3 fields as follows:

<csc:processing_date>
<csc:item_sequence_number>
<csc:account_number>

It was suggested that I could use a queue. Do you know how to incorporate the following queue into the existing C# console application that is in the code section?

System.Collections.Generic.Queue<string> tempQueue = new System.Collections.Generic.Queue<string>();

// field 1, if in error
tempQueue.Enqueue(field1);

// field 2, if in error
tempQueue.Enqueue(field2);

// field 3, if in error
tempQueue.Enqueue(field3);

// field 4 - "Check Number"
while (tempQueue.Count > 0)
{
    string field = tempQueue.Dequeue();
    // you should get back field1, field2, field3, in that order, so you can concatenate
    //  or whatever you would like to do with those values
}

Here is the format of the xml file:

<csc:item>
<csc:processing_date>20100702</csc:processing_date>
<csc:item_sequence_number>000002500759580</csc:item_sequence_number>
<csc:account_number>00000000000001111111</csc:account_number>
<csc:check_number>000000104216438</csc:check_number>
<csc:amount>0000002206</csc:amount>
<csc:routing_transit>007122258</csc:routing_transit>
<csc:bank_number>0088</csc:bank_number>
<csc:transaction_code></csc:transaction_code>
<csc:data1></csc:data1>
<csc:data2></csc:data2>
<csc:data3></csc:data3>
<csc:userField></csc:userField>
<csc:image_offset>0</csc:image_offset>
<csc:image_length>018218</csc:image_length>
<csc:image_side>A</csc:image_side>
</csc:item>
============================
My C# program is as follows:

using System;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;

namespace ReadXml1
{

    class Class1
    {
        static void Main(string[] args)
        {
           
            string goodFilePath = @"U:\Harris\HarrisCheck.ard.ind";
            string emptyFilePath = @"U:\Harris\HarrisCheck.ard";
            string tiffFilePath = @"U:\Harris\HarrisCheck.ard.out";
            string errorFilePath = @"U:\Harris\HarrisCheck.err.txt";

            if (File.Exists(goodFilePath))
            {
                File.Delete(goodFilePath);
            }

            if (File.Exists(emptyFilePath))
            {
                File.Delete(emptyFilePath);
            }

            if (File.Exists(tiffFilePath))
            {
                File.Delete(tiffFilePath);
            }

            if (File.Exists(errorFilePath))
            {
                File.Delete(errorFilePath);
            }

            
            DirectoryInfo parentDirectory = new DirectoryInfo(@"\\nydfs1\root\APPDATA\CashControl\HARRISBKOnDemandUtility\FTPFILES\Dev");

            
            bool hasElseBeenExecuted = false;  // <-- add this boolean line to use as a check further down

            foreach (FileInfo file in parentDirectory.GetFiles())
            {
                StreamWriter sw = null;
                try
                {
                    if (file != null && XmlFile(file.FullName))

                    //if (XmlFile(file.FullName))
                    {
                        StreamWriter sw1 = new StreamWriter(errorFilePath);
                        sw = new StreamWriter(goodFilePath);
                        ProcessFile(file.FullName, sw, sw1);
                    }
                    else if (!hasElseBeenExecuted)  // <-- change this from a regular "else" to an "else if" that specifically looks to see if the hasElseBeenExecuted variable is set to false
                    {
                        hasElseBeenExecuted = true;  // <-- set the boolean flag to true so that this else block never gets hit again
                        sw = new StreamWriter(emptyFilePath);
                        File.Copy(file.FullName, @"U:\Harris\HarrisCheck.ard.out");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (sw != null) sw.Close();
                }
            }



            if (File.Exists(errorFilePath))
            {
                if (new FileInfo(errorFilePath).Length == 0)
                {
                    if (File.Exists(errorFilePath))
                    {
                        File.Delete(errorFilePath);
                    }
                }

                else
                {
                    if (File.Exists(goodFilePath))

                        File.Delete(goodFilePath);

                    if (File.Exists(emptyFilePath))

                        File.Delete(emptyFilePath);

                    if (File.Exists(tiffFilePath))

                        File.Delete(tiffFilePath);
                }
            }


            Console.WriteLine("Processing done. Press enter to exit ... ");
            Console.ReadLine();
        }

        private static void ProcessFile(string filePath, StreamWriter sw, StreamWriter sw1)
        {
            int i = 0;
            string[,] arr1 = new string[2000, 20];
            int iCheckNumber = 0;
            String formattedString1 = null;
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader(filePath);
                while (reader.Read())
                {

                    if (reader.NodeType == XmlNodeType.Element)
                    {

                        if (reader.Name == "csc:item_sequence_number")
                        {
                            arr1[i, 11] = "GROUP_FIELD_NAME:CpcsNo";
                            String h = reader.ReadElementContentAsString();
                            String formattedString = h.Substring(7, 8);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 12] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 12] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:CpcsNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                                iCheckNumber--;
                            }
                        }
                        if (reader.Name == "csc:check_number")
                        {
                            iCheckNumber = iCheckNumber + 1;
                            arr1[i, 0] = "COMMENT: CHECK NUMBER #" + iCheckNumber;
                            arr1[i, 1] = "GROUP_FIELD_NAME:CheckNumber";
                            String e = reader.ReadElementContentAsString();
                            String formattedString = e.Substring(6, 3);
                            formattedString1 = e.Substring(9, 6);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString1, out intTest))
                                arr1[i, 2] = "GROUP_FIELD_VALUE:" + formattedString1;
                            else
                            {
                                arr1[i, 2] = "GROUP_FIELD_VALUE:" + formattedString1;
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:CheckNumber" + "," + "GROUP_FIELD_VALUE:" + formattedString1);
                            }

                            arr1[i, 15] = "GROUP_FIELD_NAME:OfficeNo";
                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 16] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 16] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:OfficeNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                            }
                        }
                        if (reader.Name == "csc:routing_transit")
                        {
                            arr1[i, 3] = "GROUP_FIELD_NAME:RoutingTransit";
                            String g = reader.ReadElementContentAsString();
                            String formattedString = g.Substring(1, 8);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 4] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 4] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:RoutingTransit" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                            }

                            arr1[i, 5] = "GROUP_FIELD_NAME:BankName";
                            arr1[i, 6] = "GROUP_FIELD_VALUE:HARRIS BANK";
                        }
                        if (reader.Name == "csc:account_number")
                        {
                            arr1[i, 7] = "GROUP_FIELD_NAME:BankAccountNo";
                            String f = reader.ReadElementContentAsString();
                            String formattedString = f.Substring(13, 7);
                            Int64 intTest = 0;

                            if (Int64.TryParse(formattedString, out intTest) && intTest > 0)
                                arr1[i, 8] = "GROUP_FIELD_VALUE:" + formattedString;
                            else
                            {
                                arr1[i, 8] = "GROUP_FIELD_VALUE:" + formattedString;
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:BankAccountNo" + "," + "GROUP_FIELD_VALUE:" + formattedString);
                                iCheckNumber--;
                            }

                        }
                        if (reader.Name == "csc:amount")
                        {
                            arr1[i, 9] = "GROUP_FIELD_NAME:CheckAmount";
                            
                            string value = reader.ReadElementContentAsString();
                            Int64 intTest = 0;

                            if (Int64.TryParse(value, out intTest) && intTest > 0)
                                arr1[i, 10] = "GROUP_FIELD_VALUE:" + value.Insert(value.Length - 2, ".");
                            else
                            {
                                arr1[i, 10] = "GROUP_FIELD_VALUE:" + value.Insert(value.Length - 2, ".");
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:CheckAmount" + "," + "GROUP_FIELD_VALUE:" + value);
                            }

                            
                        }

                        if (reader.Name == "csc:processing_date")
                        {
                            arr1[i, 13] = "GROUP_FIELD_NAME:CheckPaidDate";
                            String d = reader.ReadElementContentAsString();
                            DateTime parsedDate;
                            IFormatProvider format = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;

                            if (DateTime.TryParseExact(d, "yyyyMMdd", format, DateTimeStyles.None, out parsedDate))
                                arr1[i, 14] = "GROUP_FIELD_VALUE:" + parsedDate.ToShortDateString();
                            else
                            {
                                arr1[i, 14] = "GROUP_FIELD_VALUE:" + parsedDate.ToShortDateString();
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_FIELD_NAME:CheckPaidDate" + "," + "GROUP_FIELD_VALUE:" + d);
                                iCheckNumber--;
                            }
                        }

                        if (reader.Name == "csc:image_offset")
                        {
                            string strTemp1 = reader.ReadElementContentAsString();
                            Int64 intTest = 0;

                            if (Int64.TryParse(strTemp1, out intTest))
                                arr1[i, 17] = "GROUP_OFFSET:" + strTemp1.PadLeft(10, '0');
                            else
                            {
                                arr1[i, 17] = "GROUP_OFFSET:" + strTemp1.PadLeft(10, '0');
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_OFFSET:" + "," + "GROUP_FIELD_VALUE:" + strTemp1);
                            }
                        }

                        if (reader.Name == "csc:image_length")
                        {
                            string strTemp2 = reader.ReadElementContentAsString();
                            Int64 intTest = 0;

                            if (Int64.TryParse(strTemp2, out intTest) && intTest > 0)
                                arr1[i, 18] = "GROUP_LENGTH:" + strTemp2.PadLeft(10, '0');
                            else
                            {
                                arr1[i, 18] = "GROUP_LENGTH:" + strTemp2.PadLeft(10, '0');
                                sw1.WriteLine("GROUP_FIELD_NAME:CheckNumber:" + formattedString1 + ",GROUP_LENGTH:" + "," + "GROUP_LENGTH:" + strTemp2);
                            }

                            arr1[i, 19] = "GROUP_FILENAME:/clientdoc/HRSBK.HARRISBK.THKHARB4.THKHARB4.77.1.ard.out";
                            i++;
                        }
                    }
                }

                sw.WriteLine("COMMENT: specify code page of the index date");
                sw.WriteLine("CODEPAGE:819");
                for (int iter = 0; iter < i; iter++)
                {
                    for (int j = 0; j < 20; j++)
                    {
                        sw.WriteLine(arr1[iter, j]);
                    }
                }
            }
            finally
            {
                if (sw1 != null) sw1.Close();
                reader.Close();
            }
        }
        static bool XmlFile(string filePath)
        {
            string line;
            bool xmlFile = false;
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(filePath);
                line = sr.ReadLine();
                if (line.Equals("<?xml version=\"1.0\"?>"))
                    xmlFile = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                xmlFile = false;
            }
            finally
            {
                if (sr != null) sr.Close();
            }
            return xmlFile;
        }
    }
}

Open in new window

0
Comment
Question by:zimmer9
  • 2
2 Comments
 
LVL 15

Expert Comment

by:x77
Comment Utility
NetFramework include: System.Collections.Generic.Queue(Of T)


http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx
0
 
LVL 15

Accepted Solution

by:
x77 earned 500 total points
Comment Utility
I think you need declare a new Class for Field Type

Then create the Queue(Of Field)

Field type must contains
   Field Type
   Value
    ....

Note that you can overrides equals to take Contains valid.

Note also that you fill the Queue, Then you empty the queue.

Then a List<T> is valid option also.
When you Fill the List, you enumerate it, then clear.

List<T> has a good support for sorting.
Then you can Sort before enumerate and Group results on report.
   

0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Refresh Datagridview from another form 1 25
Chat Room 1 22
VB.NET HttpWebRequest 12 29
XML & .net 5 0
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now