Click here to Skip to main content
15,919,500 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a dll to monitor a folder, pick up xml files and upload the contents into a database. If there is an error or exception the xml file is moved to an error folder, otherwise it is deleted. I am lost unit testing it. Could somebody help me with this please?

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TryUnitTesting
{
    [XmlRootAttribute("HouseCouncilTaxDetails")]
    public class HouseCouncilTaxDetails
    {
        [XmlElement(typeof(HouseDetails), ElementName = "House"),
         XmlElement(typeof(CouncilTaxDetails), ElementName = "CouncilTax")]
        public System.Collections.ArrayList HouseCouncilTaxList;
        HouseCouncilTaxDetails()
        {
        }
    }

    public class HouseDetails
    {
        [XmlAttribute()]
        public String HOUSENAME;
        [XmlAttribute()]
        public String POSTCODE;
    }


    public class CouncilTaxDetails
    {
        [XmlAttribute()]
        public String PAYMENTDATE;
        [XmlAttribute()]
        public String AMOUNT;
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Collections;
using Logging;

namespace TryUnitTesting
{
    public class FileManager
    {
        //private string _logFileName = "";
        private string _xmlFileDirectory = "";
        private string _errorFileDirectory = "";
        private string _file = "";
        private ArrayList _errorStr;
        private int _iNoOfRecordsExported = 0;
        private int _iTotalNoOfRecords = 0;
        private string _connectionString = "";
        private Logging.Log _logger;

        public FileManager(Logging.Log logger)
        {
            _logger = logger;
        }

        #region "(Public) ProcessFiles Procedure"

        public void ProcessFiles(string strDirectory,  string strxmlFileDirectory, string strErrorFileDirectory, string strConnectionString)
        {
            // process all files in the directory
            System.IO.DirectoryInfo diDirInfo;


            try
            {
                _logger.RecordMessage("ProcessFiles: Getting list of files", Log.MessageType.Info);
                diDirInfo = new System.IO.DirectoryInfo(strDirectory);
                System.IO.FileInfo[] fiArray = diDirInfo.GetFiles("*.xml");
                if (fiArray != null && fiArray.Length > 0)
                {
                    _logger.RecordMessage("ProcessFiles: " + fiArray.Length.ToString() + " files retrieved", Log.MessageType.Info);

                    foreach (System.IO.FileInfo fi in fiArray)
                    {
                        _logger.RecordMessage("ProcessFiles: File" + fi.FullName, Log.MessageType.Info);
                        if (System.IO.File.Exists(fi.FullName))
                        {
                            _logger.RecordMessage("ProcessFiles: File exists : " + fi.FullName, Log.MessageType.Info);
                            if (!ProcessIndividualFile(fi.FullName,  strxmlFileDirectory, strErrorFileDirectory, strConnectionString))
                            {
                                _logger.RecordMessage("ProcessFiles: Failed to process individual file. Exiting", Log.MessageType.Failure);
                                //Exit For
                            }
                        }
                        else
                        {
                            _logger.RecordMessage("ProcessFiles: File doesn't exist: " + fi.FullName, Log.MessageType.Error);
                        }
                    }
                }

            }
            catch (Exception ex)
            {

                _logger.RecordMessage(ex, Log.MessageType.Error);
            }

            finally
            {
                _logger.RecordMessage(" ProcessingFiles exiting", Log.MessageType.Info);
            }
        }
        #endregion


        public bool ProcessIndividualFile(string strFile,  string strWebTISFileDirectory, string strErrorFileDirectory, string strConnectionString)
        {
            _file = strFile;
            //_logFileName = strLogFileName;
            _xmlFileDirectory = strWebTISFileDirectory;
            _errorFileDirectory = strErrorFileDirectory;
            _errorStr = new ArrayList();
            _iNoOfRecordsExported = 0;
            _connectionString = strConnectionString;

            _logger.RecordMessage("", Log.MessageType.Info);
            _logger.RecordMessage(" processing " + _file, Log.MessageType.Info);
            _logger.RecordMessage("", Log.MessageType.Info);

            try
            {
                //' deserialize the xml file
                HouseCouncilTaxDetails cData;

                using (System.IO.FileStream fs = new System.IO.FileStream(_file, System.IO.FileMode.Open))
                {
                    System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(typeof(HouseCouncilTaxDetails));
                    cData = (HouseCouncilTaxDetails)xsSerializer.Deserialize(fs);
                }

                ProcessHouseCouncilTaxDetails(cData);

                HandleErrors();

                return true;
            }
            catch (Exception ex)
            {
                //Util.LogMessage(_logFileName, " exception " + ex.InnerException + ex.StackTrace);
                _logger.RecordMessage(ex, Log.MessageType.Info);

                return false;

            }

        }


        private void ProcessHouseCouncilTaxDetails(HouseCouncilTaxDetails cSTD)
        {
            string sSQL = "";
            _iNoOfRecordsExported = 0;
            _iTotalNoOfRecords = cSTD.HouseCouncilTaxList.Count;

            for (int i = 0; i <= _iTotalNoOfRecords - 2; i = i + 2)
            {
                HouseDetails house = (HouseDetails)cSTD.HouseCouncilTaxList[i];
                CouncilTaxDetails councilTax = (CouncilTaxDetails)cSTD.HouseCouncilTaxList[i + 1];

                _logger.RecordMessage("", Log.MessageType.Info);
                _logger.RecordMessage("House - " + house.HOUSENAME + " ; CouncilTax - " + councilTax.PAYMENTDATE, Log.MessageType.Info);
                _logger.RecordMessage("", Log.MessageType.Info);


                try
                {
                    sSQL = CreateSQLQuery(house, councilTax);
                    bool result = UpdateDatabase(sSQL);
                    if (result)
                    {
                        _iNoOfRecordsExported = _iNoOfRecordsExported + 2;

                    }
                    else
                    {
                        _errorStr.Add("Unable to export. House : " + house.HOUSENAME + " " + house.POSTCODE + "Council Tax : " + councilTax.PAYMENTDATE);
                    }

                }
                catch (Exception ex)
                {
                    _errorStr.Add(ex.Message + " House : " + house.HOUSENAME + " " + house.POSTCODE + "(" + councilTax.PAYMENTDATE + " )Council Tax amount : " + councilTax.AMOUNT);
                }
            }
        }

        private void HandleErrors()
        {
            if ((_errorStr != null))
            {
                if (_errorStr.Count > 0)
                {
                    string fileName = MoveFileToDirectory(_file, _errorFileDirectory, "Unable to upload " + (_iTotalNoOfRecords - _iNoOfRecordsExported) + " records.");

                    foreach (string str in _errorStr)
                    {
                        try
                        {
                            AddErrorNode(_errorFileDirectory + "\\" + fileName, str);
                        }
                        catch (Exception ex)
                        {
                            _logger.RecordMessage(ex, Log.MessageType.Error);
                            //return false;

                        }

                    }
                }
                else
                {
                    System.IO.File.Delete(_file);
                }

            }

        }

        private string CreateSQLQuery(HouseDetails house, CouncilTaxDetails councilTax)
        {
            string sSQL = "execute UpdateCouncilTax ";


            sSQL += "@HouseName='" + house.HOUSENAME + "',@PostCode='" + house.POSTCODE
                + "'" ;

            return sSQL;
        }

        #region "UpdateDatabase - updates the database with the customer and seasons records."

        private bool UpdateDatabase(string queryString)
        {

            _logger.RecordMessage(queryString, Log.MessageType.Info);

            using (SqlConnection connection = new SqlConnection(
                       _connectionString))
            {
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Connection.Open();
                int records = 0;
                try
                {
                    records = command.ExecuteNonQuery();

                }
                catch (Exception ex)
                {

                    _logger.RecordMessage(ex, Log.MessageType.Info);
                }
                if (records > 0)
                {
                    // successful so move them to uploaded directory
                    //Log("Data export ran successfully. , Logging.LoggingLevel.Info)
                    //MoveFileToDirectory(sFile, UploadedFilesFolder, "")
                    //DeleteFile(sFile)
                    Thread.Sleep(500);
                    return true;
                }
                else
                {
                    //Log("Data export failed - Records = " + records.ToString(), Logging.LoggingLevel.Warning);
                    //sProcessingStatus = "Data export failed - Records = " + records.ToString();
                    _logger.RecordMessage("4----------------------", Log.MessageType.Info);

                    return false;
                }

            }
        }

        #endregion

         #region "MoveFileToErrorsDirectory Procedure"

        private string MoveFileToDirectory(string sFile, string sDir, string errorDetails)
        {
            // move the file passed in to the Errors directory
            System.IO.FileInfo fI = null;

            try
            {
                if (Util.CreateDirectory(sDir) == true)
                {
                    fI = new System.IO.FileInfo(sFile);
                    _logger.RecordMessage("MoveFileToDirectory: " + fI.Name, Log.MessageType.Info);
                    string fileName = String.Format("{0:yyyy-MM-dd(HH mm ss)}", DateTime.Now) + " " + fI.Name;
                    System.IO.File.Move(sFile, sDir + "\\" + fileName);
                    //AddErrorNode(sDir & "\" & fI.Name(), errorDetails)
                    //sProcessingStatus = "Moved file " & sFile & " to " & sDir & "(" & errorDetails & ")"
                    return fileName;
                }
                else
                {
                    return "";
                }

            }
            catch (Exception ex)
            {
                _logger.RecordMessage(ex, Log.MessageType.Info);
                throw ex;

            }

        }
        #endregion

        private void AddErrorNode(string sFile, string errorDetails)
        {
            System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
            try
            {
                xmldoc.Load(sFile);
                //If Not errorDetails.Equals("") AndAlso xmldoc.SelectSingleNode("Error") Is Nothing Then
                if (!errorDetails.Equals(""))
                {
                    System.Xml.XmlNode SectionName = xmldoc.CreateNode(System.Xml.XmlNodeType.Element, "Error", "");
                    SectionName.InnerText = errorDetails;
                    xmldoc.SelectSingleNode("/*").AppendChild(SectionName);
                }
                xmldoc.Save(sFile);
            }
            catch (Exception ex)
            {
                _logger.RecordMessage(ex, Log.MessageType.Info);
                //cLogging.Log(ex, Logging.LoggingLevel.Exception, "AddErrorNode");
            }

        }

    }
}


Sample xml file

XML
<HouseCouncilTaxDetails>
<House HOUSENAME="a" POSTCODE="ABCDEF">
</House>
<CouncilTax PAYMENTDATE="SDF" AMOUNT="343">
</CouncilTax>
</HouseCouncilTaxDetails

>
Posted

1 solution

HI Visual Studio.Net 2008 and 2010 comes with inbuilt automatic unit testcase generation and run the test application to test search

In Viusual studio.Net 2008/ 2010 IDE click on Test menu --> New Test --> Select Unit Test --> enter test project name

More information search from google for automatic unit testing with Visual Studio.Net 2008/ 2010
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900