Click here to Skip to main content
15,348,645 members
Home / Discussions / C#
   

C#

 
AnswerRe: Monitoring file changes and changing data within the file... Pin
Pete O'Hanlon3-Oct-12 2:26
mvaPete O'Hanlon3-Oct-12 2:26 
GeneralRe: Monitoring file changes and changing data within the file... Pin
Dave Kreskowiak3-Oct-12 5:33
mveDave Kreskowiak3-Oct-12 5:33 
GeneralRe: Monitoring file changes and changing data within the file... Pin
Pete O'Hanlon3-Oct-12 5:37
mvaPete O'Hanlon3-Oct-12 5:37 
GeneralRe: Monitoring file changes and changing data within the file... Pin
Dave Kreskowiak3-Oct-12 13:38
mveDave Kreskowiak3-Oct-12 13:38 
AnswerRe: Monitoring file changes and changing data within the file... Pin
BobJanova3-Oct-12 2:42
MemberBobJanova3-Oct-12 2:42 
GeneralRe: Monitoring file changes and changing data within the file... Pin
Pete O'Hanlon3-Oct-12 3:10
mvaPete O'Hanlon3-Oct-12 3:10 
GeneralRe: Monitoring file changes and changing data within the file... Pin
JD863-Oct-12 13:59
MemberJD863-Oct-12 13:59 
GeneralRe: Monitoring file changes and changing data within the file... Pin
JD8612-Oct-12 5:27
MemberJD8612-Oct-12 5:27 
Alright so here is what I ended up with. It seems to work... catches the IO exceptions and continues running. So far it is working good enough for me

C#
using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace QBiniMonitor
{
    public partial class QBMonitor : ServiceBase
    {
        // Watches the qbw.ini directory
        FileSystemWatcher watcher2012;
        FileSystemWatcher watcher2011;

        // Path to the folder where qbw.ini is stored
        string QB2012 = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%") + @"\Intuit\QuickBooks 2012\";
        string QB2011 = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%") + @"\Intuit\QuickBooks 2011\";

        // Version
        enum Version
        {
            QB2011,
            QB2012
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public QBMonitor()
        {
            InitializeComponent();
        }

        /// <summary>
        /// When service starts we need to start our FileSystemWatcher
        /// </summary>
        protected override void OnStart(string[] args)
        {
            StartNewWatcher(Version.QB2011);
            StartNewWatcher(Version.QB2012);
        }

        /// <summary>
        /// Starts the FileSystemWatcher for Quickbooks 2012 & 2011
        /// </summary>
        private void StartNewWatcher(Version watcherVersion)
        {
            if (watcherVersion == Version.QB2011)
            {
                watcher2011 = new FileSystemWatcher();
                watcher2011.Path = QB2011;
                watcher2011.Filter = "qbw.ini";
                watcher2011.NotifyFilter = NotifyFilters.LastWrite;

                watcher2011.Changed += new FileSystemEventHandler(watcher_Changed);

                // Start the watcher
                StartStopWatcher(Version.QB2011, true);
            }
            else if (watcherVersion == Version.QB2012)
            {
                watcher2012 = new FileSystemWatcher();
                watcher2012.Path = QB2012;
                watcher2012.Filter = "qbw.ini";
                watcher2012.NotifyFilter = NotifyFilters.LastWrite;

                watcher2012.Changed += new FileSystemEventHandler(watcher_Changed);

                // Start the watcher
                StartStopWatcher(Version.QB2012, true);
            }
        }

        /// <summary>
        /// When the file is written to we need to remove the last username
        /// </summary>
        private void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            // Get our file system watcher object
            FileSystemWatcher watcher = sender as FileSystemWatcher;

            // Find what version it is and stop the file system watcher
            if (watcher.Path == QB2012)
                StartStopWatcher(Version.QB2012, false);
            else if (watcher.Path == QB2011)
                StartStopWatcher(Version.QB2011, false);

            // Variable if we should change the file or not
            bool saveFile = false;

            // Variable that keeps our old value
            string oldValue = string.Empty;

            // Contains all the text in the file when we read it
            StringBuilder sb = new StringBuilder();

            try
            {
                using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        while (sr.Peek() >= 0)
                        {
                            // Read the current line
                            string currentLine = sr.ReadLine();

                            // If the line is LASTUSERNAME we need to make sure the value is Admin.
                            if (currentLine.StartsWith("LASTUSERNAME="))
                            {
                                // If the line is not just LASTUSERNAME=Admin then change it
                                if (!currentLine.Equals("LASTUSERNAME=Admin"))
                                {
                                    // LASTUSERNAME contains a value. We must change
                                    sb.AppendLine("LASTUSERNAME=Admin");

                                    // Log what the previous value was
                                    oldValue = currentLine;

                                    // Only save file if we change data
                                    saveFile = true;
                                }
                                else
                                    sb.AppendLine(currentLine); // Value is LASTUSERNAME=Admin (blank) so we are good
                            }
                            else
                                sb.AppendLine(currentLine); // Does not start with LASTUSERNAME=Admin
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("QBiniMonitor", "watcher_Changed::: " + ex.ToString(), EventLogEntryType.Error);
            }

            // If we are supposed to save the file then call WriteFile
            if (saveFile)
            {
                // If we are here that means LASTUSERNAME has a value and we must remove it
                if (watcher.Path == QB2012)
                    WriteFile(Version.QB2012, e.FullPath, sb, oldValue, 1);
                else if (watcher.Path == QB2011)
                    WriteFile(Version.QB2011, e.FullPath, sb, oldValue, 1);
            }
            else
            {
                if (watcher.Path == QB2012)
                    StartStopWatcher(Version.QB2012, true);
                else if (watcher.Path == QB2011)
                    StartStopWatcher(Version.QB2011, true);
            }
        }

        private static readonly object SyncLock = new object();
        private void WriteFile(Version watcherVersion, string file, StringBuilder sb, string oldValue, int retryCount)
        {
            if (retryCount < 5)
            {
                try
                {
                    using (StreamWriter sw = new StreamWriter(file, false))
                    {
                        // Write the file
                        sw.Write(sb.ToString());
                    }

                    // Log
                    EventLog.WriteEntry("QBiniMonitor", "Version: " + watcherVersion.ToString() + ". The value for the last username was cleared. The previous value was: " + oldValue, EventLogEntryType.Information);

                    // Start watching again
                    StartStopWatcher(watcherVersion, true);
                }
                catch (IOException)
                {
                    // Wait for 1 seconds before trying again
                    lock (SyncLock)
                    {
                        EventLog.WriteEntry("QBiniMonitor", "Version: " + watcherVersion.ToString() + ". File was locked. Waiting 2 seconds and trying again. Retry number: " + retryCount);
                        Monitor.Wait(SyncLock, 2000);
                    }

                    // Increase the retry count
                    retryCount = retryCount + 1;

                    // Call our method to try to write the file again
                    WriteFile(watcherVersion, file, sb, oldValue, retryCount);
                }
            }
            else
            {
                // Reached our retry limit so stop trying
                EventLog.WriteEntry("QBiniMonitor", "WriteFile::: " + "Retry limit of 5 was reached while trying to change the data in the file. (Because the file was locked)", EventLogEntryType.Warning);

                // Start watching again
                StartStopWatcher(watcherVersion, true);
            }
        }

        /// <summary>
        /// Starts or stops the file system watcher
        /// </summary>
        /// <param name="watcherVersion"></param>
        /// <param name="start"></param>
        private void StartStopWatcher(Version watcherVersion, bool start)
        {
            try
            {
                switch (watcherVersion)
                {
                    case Version.QB2011:
                        if (start)
                        {
                            watcher2011.EnableRaisingEvents = true;
                            //EventLog.WriteEntry("QBiniMonitor", "Started watching file " + watcher2011.Path + "\\" + watcher2011.Filter, EventLogEntryType.Information);
                        }
                        else
                        {
                            watcher2011.EnableRaisingEvents = false;
                            //EventLog.WriteEntry("QBiniMonitor", "Stopped watching file " + watcher2011.Path + "\\" + watcher2011.Filter, EventLogEntryType.Information);
                        }
                        break;

                    case Version.QB2012:
                        if (start)
                        {
                            watcher2012.EnableRaisingEvents = true;
                            //EventLog.WriteEntry("QBiniMonitor", "Started watching file " + watcher2012.Path + "\\" + watcher2012.Filter, EventLogEntryType.Information);
                        }
                        else
                        {
                            watcher2012.EnableRaisingEvents = false;
                            //EventLog.WriteEntry("QBiniMonitor", "Stopped watching file " + watcher2012.Path + "\\" + watcher2012.Filter, EventLogEntryType.Information);
                        }
                        break;

                    default:
                        break;
                }
            }
            catch (IOException ex)
            {
                // Log the error in the event log
                EventLog.WriteEntry("QBiniMonitor", "StartStopWatcher::: " + ex.ToString(), EventLogEntryType.Error);

                // Stop because of error (most likely because we couldn't find the file)
                Stop();
            }
            catch (Exception ex)
            {
                // Log the error in the event log
                EventLog.WriteEntry("QBiniMonitor", "StartStopWatcher::: " + ex.ToString(), EventLogEntryType.Error);

                // Stop because of error (most likely because we couldn't find the file)
                Stop();
            }
        }

        /// <summary>
        /// When the service stops
        /// </summary>
        protected override void OnStop()
        {
            if (watcher2011 != null)
            {
                watcher2011.EnableRaisingEvents = false;
                watcher2011.Dispose();
            }

            if (watcher2012 != null)
            {
                watcher2012.EnableRaisingEvents = false;
                watcher2012.Dispose();
            }
        }
    }
}

QuestionC# setup and deploy project templates located at? Pin
dcof2-Oct-12 5:10
Memberdcof2-Oct-12 5:10 
AnswerRe: C# setup and deploy project templates located at? Pin
isenthil2-Oct-12 6:30
Memberisenthil2-Oct-12 6:30 
GeneralRe: C# setup and deploy project templates located at? Pin
dcof2-Oct-12 17:48
Memberdcof2-Oct-12 17:48 
GeneralRe: C# setup and deploy project templates located at? Pin
Dave Kreskowiak3-Oct-12 2:28
mveDave Kreskowiak3-Oct-12 2:28 
AnswerRe: C# setup and deploy project templates located at? Pin
Dave Kreskowiak2-Oct-12 12:33
mveDave Kreskowiak2-Oct-12 12:33 
Questionsyntax Pin
messages2-Oct-12 4:29
Membermessages2-Oct-12 4:29 
AnswerRe: syntax Pin
Eddy Vluggen2-Oct-12 4:31
professionalEddy Vluggen2-Oct-12 4:31 
GeneralRe: syntax Pin
messages2-Oct-12 5:28
Membermessages2-Oct-12 5:28 
AnswerRe: syntax Pin
Richard MacCutchan2-Oct-12 5:54
mveRichard MacCutchan2-Oct-12 5:54 
GeneralRe: syntax Pin
messages2-Oct-12 6:09
Membermessages2-Oct-12 6:09 
Questionmultiple loading of assemblies - does it have any associated problems? Pin
Danzy832-Oct-12 2:53
MemberDanzy832-Oct-12 2:53 
AnswerRe: multiple loading of assemblies - does it have any associated problems? Pin
Eddy Vluggen2-Oct-12 3:23
professionalEddy Vluggen2-Oct-12 3:23 
GeneralRe: multiple loading of assemblies - does it have any associated problems? Pin
Danzy832-Oct-12 3:29
MemberDanzy832-Oct-12 3:29 
AnswerRe: multiple loading of assemblies - does it have any associated problems? Pin
Eddy Vluggen2-Oct-12 4:29
professionalEddy Vluggen2-Oct-12 4:29 
AnswerRe: multiple loading of assemblies - does it have any associated problems? Pin
jschell2-Oct-12 8:42
Memberjschell2-Oct-12 8:42 
AnswerRe: multiple loading of assemblies - does it have any associated problems? Pin
Dave Kreskowiak2-Oct-12 12:29
mveDave Kreskowiak2-Oct-12 12:29 
SuggestionRe: multiple loading of assemblies - does it have any associated problems? Pin
Guirec2-Oct-12 18:11
professionalGuirec2-Oct-12 18:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.