• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 698
  • Last Modified:

Using FileSystemWatcher and Threads

I have a windows service that I want to monitor a directory and once a file is detected or changed I want it to append to another file in another diectory and delete from the current directory. Once the file's contents are moved to the new directory I need the data to be read and manipulated. I need to make sure that the reading of the file (parseFile) is complete before I copy over new data. I presume I need to use a Thread ... This is what I have so far:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.IO;
using Iteba.Solprint.DAO;

namespace Iteba.Solprint.CP2000Worker
{
      public class CP2000Worker : System.ServiceProcess.ServiceBase
      {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.IO.FileSystemWatcher FSWatcher;
            private System.ComponentModel.Container components = null;
            public System.Threading.Thread FileDetectionThread;
            public System.Threading.Thread MainWorkerThread;
            protected ISolprintDAO dao;
            private string file;

            public CP2000Worker()
            {
                  // This call is required by the Windows.Forms Component Designer.
                  InitializeComponent();
                  StartMainThread();
            }

            // The main entry point for the process
            static void Main()
            {
                  System.ServiceProcess.ServiceBase[] ServicesToRun;

                  // create an instance of the CP2000Worker
                  CP2000Worker cp = new CP2000Worker();
                  // create a CP2000Worker service
                  ServicesToRun = new System.ServiceProcess.ServiceBase[] { cp };
                  // start the service
                  System.ServiceProcess.ServiceBase.Run(ServicesToRun);

            }

            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  components = new System.ComponentModel.Container();
                  this.ServiceName = "CP2000Worker";
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            /// <summary>
            /// Set things in motion so your service can do its work.
            /// </summary>
            protected override void OnStart(string[] args)
            {

            }
      
            /// <summary>
            /// Stop this service.
            /// </summary>
            protected override void OnStop()
            {
                  // TODO: Add code here to perform any tear-down necessary to stop your service.
                  // stop the threads
                  KillThreads();
            }

            // look for the presence of a new file to read
            public void FileDetection()
            {
                  string[] file, file2, file3, destfile, destfile2;
                  file = new String[10];
                  file3 = new string[3];
                  destfile = new String[10];
                  destfile2 = new String[10];
                  string filename = "";
                  string sLine = "";
                  string logDir = "", tempFilename = "";
                  char[] sep = {'\\'};
                  char[] sep2 = {'.'};
                  long destFileLength = 0;
                  ArrayList arrText = new ArrayList();

                  // get the data access object
                  dao = SolprintDAOFactory.GetSolprintDAO();

                  // get the directory on the Management Gate where we will be getting the file from
                  string srcDirectory = dao.GetMGDirecectory();
                                    
                  // get the log directory from the database
                  logDir = dao.GetLogDirecectory();

                  // where are we copying the file to
                  string destDirectory = dao.GetSRCDirecectory();


                  //FSWatcher.Path = srcDirectory;
                  FileSystemWatcher watcher = new FileSystemWatcher();
                  watcher.Path= srcDirectory;
                  watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Attributes | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;

                  watcher.Changed += new FileSystemEventHandler(OnChanged);
                  watcher.Created += new FileSystemEventHandler(OnChanged);

            }

            public static void OnChanged(object source, FileSystemEventArgs e)
            {
                  //Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType.ToString("G"));

                  TextWriter tw = new StreamWriter("C:\\log2.log");

                  // write to the file
                  tw.WriteLine("e.FullPath");

                  tw.Close();
                  
                  // copy file over and append to a file in another directory and
                  // and then call ParseFile to read the new file

                  
                  ParseFile(string fileToRead)
                  
                  

            }


            public void ParseFile(string fileToRead)
            {
                  this.file = fileToRead;
            }

            // use this as the WaitCallback delegate to queue in the thread pool
            public void ParseFile(object file)
            {
                  ParseFile ((string) file);

                  string sLine="", timeStamp = "", jobDate = "", operatorStartDate = "", operatorEndDate = "";
                  string activity = "", empCode = "", new_flag = "", activity_desc = "", process = "";
                  string jdf_activity_desc = "", currentActivity = "", halt_currentActivity = "", jobSumID = "", personnel = "";
                  string useCount = "", previous_empCode = "", previous_jobSumID = "", logDir = "";
                  string Line = "", halt_empCode = "", jdfCC = "", orderedJobNo = "";
                  int halt_job_number = 0, halt_job_part = 0, halt_job_section = 0, halt_activity = 0;
                  int halt_solprintCC_Code = 0, halt_qty_produced = 0, halt_qty_to_add = 0, halt_activity_code = 0;
                  string destFile = "", srcFile = "", tempCopy = "", src_temp = "", destFile2 = "";
                  string fault = "", halt = "", halt_date = "";
                  string[] valueArray, jobDetailsArray, descArray, paramArray, paramArray2, infoArray;
                  string[] jobNumber = new string[3];
                  ArrayList arrText = new ArrayList();
                  ArrayList arrayText = new ArrayList();
                  ArrayList arrJobDetails = new ArrayList();
                  valueArray = new String[11];
                  infoArray = new String[15];
                  paramArray = new String[12];
                  paramArray2 = new String[12];
                  jobDetailsArray = new String[3];
                  descArray = new String[3];
                  char[] sep = {'\t'};
                  char[] sep1 = {'_'};
                  char[] sep2 = {'\\'};
                  char[] sep3 = {' '};
                  char[] sep4 = {'-'};
                  int ccCode = 0, solprintCC_Code = 0, previous_solprintCC_Code = 0, job_number = 0;
                  int previous_job_number = 0, job_part = 0, previous_part = 0, job_section = 0;
                  int activity_code = 0, qty_produced = 0, previous_qty_produced = 0, bcodedet = 0;
                  int previous_bcodedet = 0, previous_ccCode = 0, previous_activity_code = 0, halt_previous_activity_code = 0;
                  int count = 0, dummyJobNumber = 0, qty_to_add = 0, previous_job_section = 0;
                  decimal jobTime = 0, operatorStartTime = 0, operatorEndTime = 0, start_time = 0;
                  decimal end_time = 0, previous_end_time = 0, previous_start_time = 0;
                  decimal previous_time = 0, operator_number = 0, halt_end_time = 0, halt_start_time = 0;
                  
                  // get the data access object
                  ISolprintDAO dao = SolprintDAOFactory.GetSolprintDAO();

                  // get the log directory from the database
                  logDir = dao.GetLogDirecectory();

                  destFile = file.ToString();
                  destFile2 = destFile;

                  string destDirectory = dao.GetSRCDirecectory();

                  paramArray = destFile.Split(sep1);

                  srcFile = paramArray[0] + ".bde";

                  src_temp = paramArray[0] + ".temp";

                  jdfCC = paramArray[0];

                  paramArray = jdfCC.Split(sep2);

                  jdfCC = paramArray[paramArray.Length - 1];

                  paramArray2 = destFile2.Split(sep2);

                  tempCopy = logDir + paramArray2[paramArray2.Length - 1];

                  // read the last info log file to get the
                  // last record read from the previous poll

                  if (File.Exists(logDir + "lastInfo_" + jdfCC + ".log"))    
                  {

                        // create a log file
                        string logfile = logDir + "readfile_log.log";
                  
                        // create a writer and open the file
                        TextWriter tw = new StreamWriter(logfile);

                        //create a new reader object
                        StreamReader Info_objReader = new StreamReader(logDir + "lastInfo_" + jdfCC + ".log");

                        // read in the file
                        while (Line != null)
                        {
                              Line = Info_objReader.ReadLine();
                              if (Line != null)
                              {
                                    infoArray = Line.Split(sep);
                              }
                        }
                        // close the reader object
                        Info_objReader.Close();
               
                        // set the variables with the information from the lastInfo log file
                        // this is the data read from the previous record
                        previous_bcodedet = System.Convert.ToInt32(infoArray[0]);
                        previous_empCode = infoArray[1];
                        previous_jobSumID = infoArray[2];
                        previous_ccCode = System.Convert.ToInt32(infoArray[3]);
                        previous_solprintCC_Code = System.Convert.ToInt32(infoArray[4]);
                        previous_job_number = System.Convert.ToInt32(infoArray[5]);
                        previous_part = System.Convert.ToInt32(infoArray[6]);
                        previous_job_section = System.Convert.ToInt32(infoArray[7]);
                        previous_qty_produced = System.Convert.ToInt32(infoArray[8]);
                        previous_time = System.Convert.ToDecimal(infoArray[9]);
                        previous_start_time =  System.Convert.ToDecimal(infoArray[10]);
                        previous_end_time = System.Convert.ToDecimal(infoArray[11]);
                        previous_activity_code = System.Convert.ToInt32(infoArray[12]);
                        qty_to_add = System.Convert.ToInt32(infoArray[13]);

                        // write to the log file
                        tw.WriteLine(previous_bcodedet + " " + previous_empCode + " " + previous_jobSumID + " " + previous_ccCode + " " + previous_solprintCC_Code + " " + previous_job_number + " " + previous_part + " " + previous_job_section + " " + previous_qty_produced + " " + previous_time + " " + previous_start_time + " " + previous_end_time + " " + previous_activity_code);

                        tw.Close();
                  }

                  // create a log file
                  string logfile_paramArray = logDir + "readfile_paramArray.log";
                  
                  // create a writer and open the file
                  TextWriter twp = new StreamWriter(logfile_paramArray);

                  // write to the log file
                  twp.WriteLine(" jdfCC " + jdfCC + "destFile = " + destFile + " srcFile - " + srcFile + " src_temp - " + src_temp + " tempCopy - " + tempCopy);

                  twp.Close();

                  // get the position of the previous version of this file
                  FileInfo fileInfo = new FileInfo(destFile);

                  src_temp = srcFile;

                  // create a log file
                  string logfile_info = logDir + "readfile_fileinfo.log";
                  
                  // create a writer and open the file
                  TextWriter twl = new StreamWriter(logfile_info);

                  // write to the log file
                  twl.WriteLine(" destFile = " + destFile + " srcFile - " + srcFile);

                  twl.Close();

                  // get the dummy job number, which will be used when there is
                  // no job number on the record currently being read
                  dummyJobNumber = dao.GetDummyJobNo();

                  //create a new reader object
                  StreamReader objReader = new StreamReader(destFile);

                  // read in the file
                  while (sLine != null)
                  {
                        sLine = objReader.ReadLine();
                        if (sLine != null)
                        {
                              arrText.Add(sLine);
                        }
                  }
                  // close the reader object
                  objReader.Close();

                  // how many records are in the file currently being read
                  int lastRecord = arrText.Count;

                  // get the record indentifier codes
                  personnel = dao.GetRecIDCodes("Personnel");
                  process = dao.GetRecIDCodes("Process");

                  // get the information needed
                  // reading file onle line at a time
                  foreach (string sOutput in arrText)
                  {
                        count++;
                        
                        // get the bcodedet recnum
                        bcodedet = dao.GetBcodedetRecnum(job_number,job_part,job_section,solprintCC_Code);

                        if (bcodedet != 0) previous_bcodedet = bcodedet;
                        if (empCode != "") previous_empCode = empCode;
                        if (jobSumID != "") previous_jobSumID = jobSumID;
                        if (ccCode != 0) previous_ccCode = ccCode;
                        if (solprintCC_Code != 0) previous_solprintCC_Code = solprintCC_Code;
                        

                        if (job_number != dummyJobNumber)
                        {
                              previous_job_number = job_number;
                        }

                        if (job_part != dummyJobNumber)
                        {
                              previous_part = job_part;
                        }

                        if (job_section != dummyJobNumber)
                        {
                              previous_job_section = job_section;
                        }

                        if (qty_produced != 0)
                        {
                              previous_qty_produced = qty_produced;
                        }

                        // the information in the file is separated by tabs
                        // split the information up into an array
                        valueArray = sOutput.Split(sep);

                        // get the Personnel details
                        if (valueArray[0] == personnel)
                        {
                              // if it is not he standard format for this record type
                              // then we will not be reading it
                              if (valueArray.Length != 10)
                              {
                                    // not a valid start of job record
                                    string log_dir = logDir + "personnel.log";

                                    TextWriter tw_personnel = new StreamWriter(log_dir);

                                    // write to the log file
                                    tw_personnel.WriteLine("Not a valid Personnel Record - length - " + valueArray.Length + " - in file - " + file);

                                    tw_personnel.Close();

                              }
                              else
                              {
                                    
                                    string logfile_P = logDir + "readfile_Personnel.log";
                  
                                    // create a writer and open the file
                                    TextWriter tw_p = new StreamWriter(logfile_P);

                                    // write to the log file
                                    tw_p.WriteLine("In personnel ");

                                    if (new_flag != "F")
                                    {
                                          // we have not just ended a job so we will have to get
                                          // the end time for the operator and update the database
                                          timeStamp = valueArray[1];
                                          
                                          // get the activity number
                                          activity = valueArray[2];

                                          // get the operator number
                                          operator_number = System.Convert.ToDecimal(valueArray[3]);
                                          empCode = dao.GetEmplyeeCode(operator_number);

                                          // is the operator coming or going
                                          string opDesc = dao.GetOperatorDesc(activity);

                                          int code = dao.GetSolprintCC_Code(System.Convert.ToInt32(valueArray[9]));

                                          if (opDesc == "going" || opDesc == "going operator")
                                          {
                                                // update the system field in Jobgroup - set the operator no to blank
                                                string error = dao.UpdateOperatorNo(code, "");

                                                // the operator is logging off so update database
                                                // with their work details (JobTrans)
                                                operatorEndTime = getTime(timeStamp);
                                                operatorEndDate = getDate(timeStamp);

                                          }

                                          if (opDesc == "coming" || opDesc == "coming operator")
                                          {
                                                // update the system field in Jobgroup - set the operator no
                                                string error = dao.UpdateOperatorNo(code, empCode);

                                                // get the operator start time
                                                operatorStartTime = getTime(timeStamp);
                                                operatorStartDate = getDate(timeStamp);
                                                
                                                // update the activity table with the new employee code
                                                error = dao.UpdateEmpInActivity(job_number,job_part,job_section,empCode,solprintCC_Code);
                                          }
                                    }

                                    tw_p.WriteLine("empcode - " + empCode);

                                    tw_p.Close();
                              }
                        }
                        
                        //get the process messages
                        if (valueArray[0] == process)
                        {
                              
                              if (valueArray.Length != 15)
                              {
                                    // not a valid Process record, so write to the log file
                                    // and skip this line

                                    string log_dir = logDir + "process.log";

                                    TextWriter tw_personnel = new StreamWriter(log_dir);

                                    // write to the log file
                                    tw_personnel.WriteLine("Not a valid Process Record - length - " + valueArray.Length + " - in file - " + file);

                                    tw_personnel.Close();
                                                      
                                    new_flag = "";

                                    continue;

                              }
                              
                              string logfile3 = logDir + "readfilex.log";

                              // create a writer and open the file
                              TextWriter tw3 = new StreamWriter(logfile3);

                              // manipulate the timestamp to get the time and date
                              timeStamp = valueArray[1];

                              if (jobTime != 0) previous_time = jobTime;

                              // format the time and date
                              jobTime = getTime(timeStamp);
                              jobDate = getDate(timeStamp);

                              // write to the log file
                              tw3.WriteLine("In begining - previous_time - " + previous_time);

                              tw3.WriteLine("after get time - jobTime - " + jobTime);

                              tw3.Close();

                              // the job number/part/section is sometimes missing from the BDE file
                              // if this is the case use maintenence job number
                              if (valueArray[2] == "")
                              {
                                    // the job number is missing so get the maintenence job number
                                    job_number = dao.GetMaintJobNo();
                                    job_part = dummyJobNumber;
                                    job_section = dummyJobNumber;

                              }
                              else
                              {
                                    // we need to separate the ordering number
                                    // from the begining of the job number
                                    // e.g. 001-32452
                                    orderedJobNo = valueArray[2];
                                    jobNumber = orderedJobNo.Split(sep4);
                                    job_number = System.Convert.ToInt32(jobNumber[1]);
                                    job_part = System.Convert.ToInt32(valueArray[3]);
                                    job_section = System.Convert.ToInt32(valueArray[4]);

                              }

                              if (halt == "Y" && job_number == dummyJobNumber)
                              {
                                    // the last record was a halt
                                    // and this record has no job number
                                    // it must be logged as a fault
                                    //halt_start_time = jobTime;
                                    halt_activity_code = activity_code;
                                    halt_date = jobDate;
                                    fault = "Y";
                              }

                              if (valueArray[5] == "")
                              {
                                    // there is no cost centre so report an error
                                    string cclogfile = logDir + "noCCLog.log";
                  
                                    // create a writer and open the file
                                    TextWriter CC_tw = new StreamWriter(cclogfile);

                                    // write to the log file
                                    CC_tw.WriteLine("No Cost Centre on record");

                                    CC_tw.Close();
                              }
                              else
                              {
                                  // gat the Cost Centre code      
                                    ccCode = System.Convert.ToInt32(valueArray[5]);
                              }

                              if (valueArray[6] == "")
                              {
                                    // there is no activity so report an error
                                    string activitylogfile = logDir + "noActivityLog.log";
                  
                                    // create a writer and open the file
                                    TextWriter Activity_tw = new StreamWriter(activitylogfile);

                                    // write to the log file
                                    Activity_tw.WriteLine("No Activity code on record");

                                    Activity_tw.Close();

                              }
                              else
                              {
                                    // get the activity number
                                    activity = valueArray[6];
                              }

                              // get our cost centre code
                              solprintCC_Code = dao.GetSolprintCC_Code(ccCode);

                              string logfile5 = logDir + "readfilets.log";
                  
                              // create a writer and open the file
                              TextWriter tw5 = new StreamWriter(logfile5);

                              // write to the log file
                              tw5.WriteLine("before activity loookup - activity - " + activity + " ccCode - " + ccCode + " solprintCC_Code - " + solprintCC_Code);

                              tw5.Close();

                              jdf_activity_desc = dao.GetJDFDesc(ccCode,activity);

                              // is it an activity we are interested in
                              if (jdf_activity_desc == "")
                              {
                                    // this activity is not in the database so it is
                                    // one we are not interested in so skip the line
                                    continue;
                              }

                              string logfile18 = logDir + "readfile_act_lkup.log";
                  
                              // create a writer and open the file
                              TextWriter tw18 = new StreamWriter(logfile18);

                              // write to the log file
                              tw18.WriteLine("after activity loookup - " + activity_desc + " jdf_activity_desc - " + jdf_activity_desc);

                              tw18.Close();

                              if (jdf_activity_desc != "")
                              {
                                    // is it one of the pre-defined events
                                    switch(jdf_activity_desc)
                                    {
                                          case "S":

                                                // start of a job

                                                descArray = dao.ActivityCodeLookUp2(activity, ccCode);

                                                activity_desc = descArray[0];
                                                
                                                // check if the job was halted
                                                if (halt != "Y")
                                                {
                                                      qty_to_add = 0;

                                                      halt = "S";
                                                
                                                      string logfile_start = logDir + "start.log";
                                                      string startJobError = "";
                                                
                                                      // start of the activity
                                                      start_time = jobTime;

                                                      TextWriter tw60 = new StreamWriter(logfile_start);

                                                      // write to the log file
                                                      tw60.WriteLine("in start - ");

                                                      tw60.WriteLine("after ActivityCodeLookUp2 - description is - " + activity_desc);

                                                      tw60.Close();
                                                
                                                      // is the jdf operator code on this record
                                                      if (valueArray[13] == "")
                                                      {
                                                            // it's not so get the code from the system table
                                                            empCode = dao.GetSysEmplyeeCode(solprintCC_Code);

                                                            // if there is no code in the system table then
                                                            // use a dummy employee code
                                                            if (empCode == "")
                                                            {
                                                                  empCode = "SYSMAT";
                                                            }
                                                      }
                                                      else
                                                      {
                                                            // get the jdf operator Code from this record
                                                            operator_number = System.Convert.ToInt32(valueArray[13]);

                                                            // set the solprint employee code
                                                            empCode = dao.GetEmplyeeCode(operator_number);
                                                      }

                                                      activity_code = dao.GetActivityCode(activity, ccCode);

                                                      halt_previous_activity_code = activity_code;

                                                      startJobError = startOfJob(solprintCC_Code,job_number,job_part,job_section,empCode,
                                                            start_time,activity_code,jobDate,
                                                            activity_desc, qty_produced, jobTime, previous_job_number, previous_part, previous_solprintCC_Code, ccCode);
                                                }
                                                else
                                                {
                                                      // the job was halted and restarted
                                                      // new operator could have logged on
                                                      halt = "N";

                                                      // check if the operators have changed
                                                      if(empCode == halt_empCode)
                                                      {
                                                            // the operators have not changed so we don't need to
                                                            // add the qty to the Job Transaction table
                                                            halt_qty_produced = 0;
                                                      }

                                                      // if there were records in between the halt and the
                                                      // re-start, they must be logged as a fault
                                                      if (fault == "Y")
                                                      {
                                                            halt_activity = dao.GetHaltActivityCode(ccCode);
                                                            string logFaultError = dao.LogFaultError(halt_job_number,halt_job_part,halt_activity,halt_solprintCC_Code,halt_empCode,halt_start_time,jobTime,halt_date,halt_qty_produced);
                                                            fault = "N";
                                                      }

                                                      string haltJobError = haltJob(halt_job_number, halt_job_part, halt_job_section, halt_empCode, halt_solprintCC_Code, halt_start_time, halt_qty_produced, halt_qty_to_add);

                                                      // get the new start time
                                                      start_time = jobTime;
                                   
                                                      // update the current activity with new employee code and start time
                                                      string error = dao.UpdateActivity(job_number, job_part, job_section, empCode,solprintCC_Code, start_time);

                                                }
                                                break;

                                          case "E":

                                                // end of job

                                                currentActivity = "";
                                                halt_currentActivity = "";

                                                string logfile_end = logDir + "endOfJob.log";

                                                TextWriter tw70 = new StreamWriter(logfile_end);
                                                
                                                string endJobError = "";
                                                
                                                // if the job has ended straight after the start of the job,
                                                // i.e. there were no activities in between then
                                                // we need to igore this job as it will start again. So check
                                                // if the last activity was start of the job

                                                string lastActivity = dao.GetLastActivity(activity_code);

                                                if (lastActivity != "S")
                                                {
                                                      qty_produced = System.Convert.ToInt32(valueArray[9]) - halt_qty_produced;

                                                      end_time = jobTime;

                                                      // write to the log file
                                                      tw70.WriteLine("calling end of job ...");

                                                      // is it a legitimate job / part / section
                                                      if (job_number != dummyJobNumber || job_part != dummyJobNumber || job_section != dummyJobNumber)
                                                      {

                                                            endJobError = endOfJob(job_number, job_part, job_section, empCode, solprintCC_Code,end_time, qty_produced, qty_to_add);
                                                      }
                                                }
                                                else
                                                {
                                                      tw70.WriteLine("in start - deleting bcodedet");
                                                      // we need to delete the record in the BCODEDET table
                                                      // this records current activity
                                                      endJobError = dao.DeleteActivity(job_number,job_part, job_section, activity_code);
                                                }
                                                tw70.Close();

                                                halt_qty_produced = 0;

                                                break;

                                          case "N":

                                                // new process
                                                
                                                string newProcessError = "";

                                                if (start_time != 0) previous_start_time = start_time;
                                                start_time = jobTime;
                                                if (previous_time != 0) previous_end_time = previous_time;
                                                if (activity_code != 0) previous_activity_code = activity_code;

                                                descArray = dao.ActivityCodeLookUp(activity, ccCode, previous_activity_code);

                                                activity_desc = descArray[0];

                                                // need to get the activity code
                                                activity_code = dao.GetActivityCode(activity, ccCode);

                                                string logfile_new_process = logDir + "newProcess.log";
                                                TextWriter tw40 = new StreamWriter(logfile_new_process);

                                                // write to the log file
                                                tw40.WriteLine("in New Process - " + activity_desc);

                                                tw40.WriteLine("in New Process - activity_code - " + activity_code + "previous_time - " + previous_time + " currentActivity = " + currentActivity + " activity - " + activity);

                                                tw40.Close();
                                                
                                                // only call new process if it is the first time this activity has
                                                // been identified in the current section or the process was halted
                                                if (currentActivity != activity)
                                                {
                                                      if (job_number != dummyJobNumber || job_part != dummyJobNumber || job_section != dummyJobNumber)
                                                      {
                                                            currentActivity = activity;

                                                            if (halt_previous_activity_code != activity_code || halt_empCode != empCode)
                                                            {
                                                                  halt_previous_activity_code = activity_code;

                                                                  newProcessError = newProcess(job_number, job_part, job_section, empCode,
                                                                        solprintCC_Code, start_time, previous_time, previous_start_time, activity_code,
                                                                        activity_desc, jobTime, jobDate, qty_produced);
                                                            }
                                                      }
                                                }
                                                // the process could have been halted and restarted
                                                // we need to check that the counter wasn't reset
                                                // if it was we need to add the previous qty to the final qty
                                                else
                                                {
                                                      // if we are in the same section then the counter has
                                                      // been reset
                                                      if (qty_produced == 0)
                                                      {
                                                            // the qty has been reset so get previous qty
                                                            qty_to_add = qty_to_add + previous_qty_produced;

                                                            string logfile_qty_to_add = logDir + "qty_to_add.log";
                                                            TextWriter twr = new StreamWriter(logfile_qty_to_add);

                                                            // write to the log file
                                                            twr.WriteLine("qty_to_add - " + qty_to_add);

                                                            twr.Close();
                                                      }
                                                }
                                                
                                                break;

                                          case "C":

                                                // current count
                                                
                                                string logfile_cur_ct = logDir + "readfilec_t.log";
                                                string currentCountError = "";
                  
                                                // create a writer and open the file
                                                TextWriter tw30 = new StreamWriter(logfile_cur_ct);

                                                // write to the log file
                                                tw30.WriteLine("in Current count - " + activity_desc);

                                                descArray = dao.ActivityCodeLookUp2(activity, ccCode);

                                                activity_desc = descArray[0];

                                                activity_code = dao.GetActivityCode(activity, ccCode);
                                          
                                                qty_produced = System.Convert.ToInt32(valueArray[9]);
                                                
                                                tw30.WriteLine("in Current count - qty prod - " + qty_produced);
                                                
                                                // we only want to update the current count when we are in the
                                                // Print Run process

                                                useCount = dao.UseCurrentCount(activity, ccCode);

                                                tw30.WriteLine("use the current count - " + useCount);

                                                tw30.Close();

                                                if (useCount == "Y")
                                                {
                                                      // update the current count      
                                                      currentCountError = currentCount(job_number, job_part, job_section, empCode,
                                                            activity_code, activity_desc, solprintCC_Code, jobTime,
                                                            jobDate, qty_produced);
                                                }
                                                
                                                break;

                                                case "H":

                                                      // Halt operation
                                                      // This needs to be ignored, the next activity will be a
                                                      // start of job but this is just a continuation of current
                                                      // section
                                                      halt = "Y";

                                                      // get the information we need as we can not do the
                                                      // database amends until we know whether the operator
                                                      // is changing or not. we must wait to read the next records
                                                      

                                                      //currentActivity = "";
                                                      halt_currentActivity = "";

                                                      string logfile_halt= logDir + "haltJob.log";

                                                      TextWriter tw = new StreamWriter(logfile_halt);
                                                
                                                      //string haltJobError = "";
                                                
                                                // if the job has ended straight after the start of the job,
                                                // i.e. there were no activities in between then
                                                // we need to igore this job as it will start again. So check
                                                // if the last activity was start of the job

                                                      string lastActivity1 = dao.GetLastActivity(activity_code);

                                                      //if (lastActivity1 != "S")
                                                      //{
                                                            qty_produced = System.Convert.ToInt32(valueArray[9]);

                                                            end_time = jobTime;

                                                            // write to the log file
                                                            tw.WriteLine("halt job - activity_code " + activity_code);

                                                            // is it a legitimate job / part / section
                                                            //if (job_number != dummyJobNumber || job_part != dummyJobNumber || job_section != dummyJobNumber)
                                                            //{
                                                                  halt_job_number = job_number;
                                                                  halt_job_part = job_part;
                                                                  halt_job_section = job_section;
                                                                  halt_empCode = empCode;
                                                                  halt_solprintCC_Code = solprintCC_Code;
                                                                  halt_start_time = end_time;
                                                                  halt_qty_produced = qty_produced;
                                                                  halt_qty_to_add = qty_to_add;
                                                                  halt_activity = activity_code;
                                                                  //halt_previous_activity_code = previous_activity_code;
                                                                  //haltJobError = haltJob(job_number, job_part, job_section, empCode, solprintCC_Code,end_time, qty_produced, qty_to_add);
                                                                  tw.WriteLine(halt_job_number + " " + halt_job_part + " " + halt_job_section + " " + halt_empCode + " " + halt_solprintCC_Code + " " + halt_start_time + " " + halt_qty_produced + " " + halt_qty_to_add + " " + halt_activity + " halt_previous_activity_code - " + halt_previous_activity_code);
                                                            //}
                                                      //}
                                                      
                                                      tw.Close();

                                                break;
                                    }
                              }
                        }
                  }

                  // once we have finished reading the file
                  // rename file copied over so we keep the latest version

                  string sfile = logDir + "file.log";
                  
                  // create a writer and open the file
                  TextWriter tf = new StreamWriter(sfile);

                  // write to the log file
                  tf.WriteLine("destFile " + destFile + " srcFile - " + srcFile + " tempCopy - " + tempCopy);

                  string newFile = logDir + ccCode + ".bde";
                  string newFile2 = destDirectory + ccCode + ".bde";

                  tf.WriteLine("jdfCC - " + jdfCC + " newFile " + newFile + " newFile2 - " + newFile2);

                  tf.Close();

                  // Ensure that the target does not exist.
                  if (File.Exists(srcFile))    
                        File.Delete(srcFile);

                  // Move the file.
                  File.Move(destFile, srcFile);

                  // write the information needed for the next read to a log file
                  // so that if we are reading on a new call we don't loose the information
                  string Info = logDir + "lastInfo_ " + jdfCC + ".log";
                  
                  // create a writer and open the file
                  TextWriter lastInfo = new StreamWriter(Info);

                  // write to the log file
                  lastInfo.WriteLine(previous_bcodedet.ToString() + "\t" + previous_empCode.Trim() + "\t" + previous_jobSumID.Trim() + "\t" + previous_ccCode.ToString() + "\t" + previous_solprintCC_Code.ToString() + "\t" + previous_job_number.ToString() + "\t" + previous_part.ToString() + "\t" + previous_job_section.ToString() + "\t" + previous_qty_produced.ToString() + "\t" + previous_time.ToString() + "\t" + previous_start_time.ToString() + "\t" + previous_end_time.ToString() + "\t" + previous_activity_code.ToString() + "\t" + qty_to_add.ToString());

                  lastInfo.Close();

            }

            private string startOfJob(int solprintCC_Code, int job_number, int job_part, int job_section, string empCode,
                  decimal start_time, int activity_code, string jobDate, string activity_desc,
                  int qty_produced, decimal jobTime, int previous_job_number, int previous_part, int previous_solprintCC_Code, int ccCode)
            {
                  //string jobComplete = "";
                  string record = "";
                  string error_text= "";
                  string logDir = "";
                  int schedRecnum = 0;

                  // get the log directory from the database
                  logDir = dao.GetLogDirecectory();

                  string logfile7 = logDir + "startOfJob_function.log";
                  
                  // create a writer and open the file
                  TextWriter tw71 = new StreamWriter(logfile7);

                  // write to the log file
                  tw71.WriteLine("in startOfJob_function - " + record + " job details - " +  job_number.ToString() + job_part.ToString() + job_section.ToString());

                  tw71.Close();

                  // check that we gave the employee code
                  if (empCode == "")
                  {
                        empCode = dao.GetSysEmplyeeCode(solprintCC_Code);
                  }

                  string logfile71 = logDir + "readfilem.log";
                  
                  string logfile8 = logDir + "schedRecnum.log";
                  
                  // create a writer and open the file
                  TextWriter tw8 = new StreamWriter(logfile8);

                  // makeready only occurs at the start of a new job and not
                  // a new part or section of the same job so check if we
                  // are on a new job

                  if (job_number != previous_job_number)
                  {
                        // this is a new job so delete the previous job from the current activity table
                        error_text = dao.DeleteJobFromActivity(previous_job_number,previous_part,solprintCC_Code);
                  }
//
                  // if we are now on a new part of the same job we can update the
                  // completed field of the schedfil record for the previous part

                  tw8.WriteLine("job_number - " + job_number + " previous_job_number - " + previous_job_number);
                  tw8.WriteLine("previous_part - " + previous_part + " job_part - " + job_part);


                  if (job_number == previous_job_number && previous_part != job_part)
                  {
                        error_text = dao.UpdateSchedfil(previous_job_number,previous_part,previous_solprintCC_Code);
                        tw8.WriteLine("Updated schedfil ... ");

                        if (error_text != "")
                        {
                              string logfile19 = logDir + "UpdateSchedfil_2.log";
                  
                              // create a writer and open the file
                              TextWriter tw19 = new StreamWriter(logfile19);

                              // write to the log file
                              tw19.WriteLine("UpdateSchedfil 2 - " + error_text);

                              tw19.Close();
                        }
                  }

                  // get the schedfil recnum for the new activity
                  schedRecnum = dao.GetSchedRecnum(job_number,solprintCC_Code,job_part,activity_code);

                  tw8.WriteLine("schedRecnum - " + schedRecnum);

                  tw8.Close();

                  // there is no record so create a new activity
                  error_text = dao.CreateNewDCActivity(job_number,job_part,job_section,
                        empCode,start_time,activity_code,jobDate,
                        solprintCC_Code, activity_desc, qty_produced, jobTime, jobDate, schedRecnum);

                  string logfile9 = logDir + "readfiledd.log";
                  
                  // create a writer and open the file
                  TextWriter tw9 = new StreamWriter(logfile9);

                  // write to the log file
                  tw9.WriteLine("after new activity - " + error_text);

                  tw9.Close();
                  
                  return error_text;
            }

            private string endOfJob(int job_number, int job_part, int job_section,
                  string empCode, int solprintCC_Code, decimal end_time, int qty_produced, int qty_to_add)
            {
                                    
                  string jobSumID = "";
                  int estRecnum = 0;
                  int bcodedet = 0;
                  string error_text= "";
                  string logDir = "";

                  // get the log directory from the database
                  logDir = dao.GetLogDirecectory();

                  string logfile16 = logDir + "readfile_setComplete.log";
                  
                  // create a writer and open the file
                  TextWriter tw16 = new StreamWriter(logfile16);

                  tw16.WriteLine("In endOfJob ...qty_to_add" + qty_to_add);

                  // add the extra qty if it was reset during the run
                  qty_produced = qty_produced + qty_to_add;

                  // check that we gave the employee code
                  if (empCode == "")
                  {
                        empCode = dao.GetSysEmplyeeCode(solprintCC_Code);
                  }

                  // get the
                  jobSumID = dao.GetJobsumID(job_number);

                  // if jobSumID is blank then a record was not found in Jobsum
                  if (jobSumID == "")
                  {
                        // so create one - we need to get the estimate recnum first
                        estRecnum = dao.GetEstimateRecnum(job_number);
                        // create a record in the Jobsum table
                        error_text = dao.CreateJobsum(estRecnum,job_number);
                        // get the new jobSumID
                        jobSumID = dao.GetJobsumID(job_number);
                  }
                                    
                  // get the bcodedet recnum
                  bcodedet = dao.GetBcodedetRecnum(job_number,job_part,job_section,solprintCC_Code);
                  // now set the job as completed
                  error_text = dao.SetJobCompleted(bcodedet,empCode,jobSumID,end_time, qty_produced);

                  // write to the log file
                  tw16.WriteLine("after Set Complete - " + error_text);

                  tw16.Close();

                  return error_text;
            }

            private string haltJob(int job_number, int job_part, int job_section,
                  string empCode, int solprintCC_Code, decimal end_time, int qty_produced, int qty_to_add)
            {
                                    
                  string jobSumID = "";
                  int estRecnum = 0;
                  int bcodedet = 0;
                  string error_text= "";
                  string logDir = "";

                  // get the log directory from the database
                  logDir = dao.GetLogDirecectory();

                  string logfile16 = logDir + "readfile_setComplete.log";
                  
                  // create a writer and open the file
                  TextWriter tw16 = new StreamWriter(logfile16);

                  tw16.WriteLine("In endOfJob ...qty_to_add" + qty_to_add);

                  // add the extra qty if it was reset during the run
                  qty_produced = qty_produced + qty_to_add;

                  // check that we gave the employee code
                  if (empCode == "")
                  {
                        empCode = dao.GetSysEmplyeeCode(solprintCC_Code);
                  }

                  // get the
                  jobSumID = dao.GetJobsumID(job_number);

                  // if jobSumID is blank then a record was not found in Jobsum
                  if (jobSumID == "")
                  {
                        // so create one - we need to get the estimate recnum first
                        estRecnum = dao.GetEstimateRecnum(job_number);
                        // create a record in the Jobsum table
                        error_text = dao.CreateJobsum(estRecnum,job_number);
                        // get the new jobSumID
                        jobSumID = dao.GetJobsumID(job_number);
                  }
                                    
                  // get the bcodedet recnum
                  bcodedet = dao.GetBcodedetRecnum(job_number,job_part,job_section,solprintCC_Code);
                  // now set the job as completed
                  error_text = dao.SetJobHalted(bcodedet,empCode,jobSumID,end_time, qty_produced);

                  // write to the log file
                  tw16.WriteLine("after Set Complete - " + error_text);

                  tw16.Close();

                  return error_text;
            }

            private string currentCount(int job_number, int job_part, int job_section,
                  string empCode, int activity_code, string activity_desc, int solprintCC_Code,
                  decimal jobTime, string jobDate, int qty_produced)
            {
                  string error_text = "";

                  error_text = dao.UpdateCurrentCount(job_number,job_part,job_section,
                        activity_code, solprintCC_Code, jobTime, jobDate, qty_produced);

                  return error_text;
            }

            private string newProcess(int job_number, int job_part, int job_section,
                  string empCode, int solprintCC_Code, decimal start_time, decimal previous_end_time,
                  decimal previous_start_time, int activity_code, string activity_desc, decimal jobTime,
                  string jobDate, int qty_produced)
            {
                  string completed = "N";
                  string jobSumID = "";
                  string error_text = "";
                  int estRecnum = 0;
                  int bcodedet = 0;
                  int schedRecnum = 0;
                  string logDir = "";

                  // get the log directory from the database
                  logDir = dao.GetLogDirecectory();

                  // get the schedfil recnum for the new activity
                  schedRecnum = dao.GetSchedRecnum(job_number,solprintCC_Code,job_part,activity_code);

                  // get the jobSumID
                  jobSumID = dao.GetJobsumID(job_number);
           
                  // if jobSumID is blank then a record was not found in Jobsum
                  if (jobSumID == "")
                  {
                        // so create one - we need to get the estimate recnum first
                        estRecnum = dao.GetEstimateRecnum(job_number);
                        // create a record in the Jobsum table
                        error_text = dao.CreateJobsum(estRecnum,job_number);
                        // get the new jobSumID
                        jobSumID = dao.GetJobsumID(job_number);
                  }
                              
                  // get the bcodedet recnum
                  bcodedet = dao.GetBcodedetRecnum(job_number,job_part,job_section,solprintCC_Code);

                  string logfile = logDir + "readfile_update_1.log";
                  
                  // create a writer and open the file
                  TextWriter tw = new StreamWriter(logfile);

                  tw.WriteLine("in here ...");

                  tw.Close();
                  
                  // end the previous process
                  error_text = dao.SetProcessCompleted(bcodedet,empCode,jobSumID,previous_end_time, qty_produced);

                  // set new start time
                  error_text = dao.SetStartTime(bcodedet,start_time);

                  error_text = dao.UpdateDCActivity(job_number,job_part,job_section,
                        empCode, activity_code, activity_desc, solprintCC_Code, completed, start_time, jobDate, qty_produced, schedRecnum, bcodedet);
                                          
                  string logfile15 = logDir + "readfile_update.log";
                  
                  // create a writer and open the file
                  TextWriter tw15 = new StreamWriter(logfile15);

                  // write to the log file
                  tw15.WriteLine("update activity - qty - " + qty_produced);
                  tw15.WriteLine("start_time - " + start_time);
                  tw15.WriteLine("previous_end_time - " + previous_end_time);
                  tw15.WriteLine("after update activity - error text - " + error_text);

                  tw15.Close();

                  return error_text;

            }

            private string[] getJobDetails(string jobDetails)
            {
                  
                  string[] jobDetailsArray;
                  jobDetailsArray = new String[3];
                  char[] sep = {'/'};

                  jobDetailsArray = jobDetails.Split(sep);
                  return jobDetailsArray;
            }

            private decimal getTime(string timestamp)
            {
                  string hour = "";
                  decimal dhour = 0;
                  string minute = "";
                  decimal dminute = 0;
                  string seconds = "";
                  decimal dseconds = 0;
                  decimal jobTime = 0;

                  // separate out the hour minute and seconds from the timestamp string
                  hour = timestamp.Substring(8,2);
                  dhour = System.Convert.ToDecimal(hour);
                  minute = timestamp.Substring(10,2);
                  dminute = System.Convert.ToDecimal(minute);
                  seconds = timestamp.Substring(12,2);
                  dseconds = System.Convert.ToDecimal(seconds);
                  
                  // round up the minutes if the seconds is greater than 30
                  if (dseconds > 30)
                  {
                        dminute = dminute + 1;
                  }

                  // the time is stored as a decimal in the database
                  jobTime = Decimal.Round(dhour + (dminute / 60),2);
                  
                  return jobTime;
            }

            private string getDate(string timestamp)
            {
                  string year = "";
                  string month = "";
                  string day = "";
                  string jobDate = "";

                  year = timestamp.Substring(0,4);
                  month = timestamp.Substring(4,2);
                  day = timestamp.Substring(6,2);
                  jobDate = day + "/" + month + "/" + year;
                  
                  return jobDate;
            }

            public void KillThreads()
            {
                  MainWorkerThread.Interrupt();
                  FileDetectionThread.Interrupt();
            }

            public void StartMainThread()
            {
                  // create the thread
                  MainWorkerThread = new System.Threading.Thread(new
                  System.Threading.ThreadStart(this.MainWorker));

                  // Starts the File Detection thread
                  MainWorkerThread.Start();
            }
            
            // main worker thread - sole job is to start other worker threads at a specified time
            public void MainWorker()
            {
                  int pollTime = 0;

                  // get the data access object
                  dao = SolprintDAOFactory.GetSolprintDAO();

                  // get poll time
                  pollTime = dao.GetPollTime();

                  // poll time is stored in the database in seconds
                  // we need to convert this to milliseconds
                  pollTime *= 1000;

                  while(true)
                  {
                        // create the File Detection thread
                        FileDetectionThread = new System.Threading.Thread(new
                              System.Threading.ThreadStart(this.FileDetection));

                        // Starts the File Detection thread
                        FileDetectionThread.Start();
                        // wait the specified poll time and start a new thread.
                        Thread.Sleep(pollTime);
                        
                  }
            }
      }
}

at the moment the OnChanged method isn't being called and I am unsure on how to prevent the file being copied over if another file is still being read? Or do I create another thread to do this ...?

Any help would be appreciated!

Thanks
0
L_M
Asked:
L_M
1 Solution
 
Bob LearnedCommented:
Wow, that is sure a lot of code that people are going to have to wade through.  

How many threads would you say that you were creating?  Are you checking for deadlocks (if they are possible)?  Does threading solve a solution that could not be solved otherwise?  

Where is the FileSystemWatcher in all that?  Do any events fire or are you only interested in the OnChanged?  Is the path to watch set properly?  What is the value of the EnableRaisingEvents property?  Is the Filter string property clear?

Have you looked at the WaitForChanged synchronous method?

Bob
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now