Esempio n. 1
0
        /// <summary>
        /// Used to execute custom commands after the conversion process is compelte just before the file is moved to the desination directory
        /// </summary>
        /// <param name="prefix">Prefix for reading lines from profile</param>
        /// <param name="profile">Profile name</param>
        /// <param name="taskName">Task Name</param>
        /// <param name="workingPath">Temp working path</param>
        /// <param name="destinationPath">Destination path for converted file</param>
        /// <param name="convertedFile">Full path to final converted file</param>
        /// <param name="sourceFile">Full path to original source file</param>
        /// <param name="remuxFile">Full path to intermediate remuxed file</param>
        /// <param name="edlFile">Full path to EDL file</param>
        /// <param name="srtFile">Full path to SRT file</param>
        /// <param name="metaData">Video metadata structure for source file</param>
        /// <param name="jobStatus">ref to JobStatus</param>
        /// <param name="jobLog">JobLog</param>
        public CustomCommand(string prefix, string profile, string taskName, string workingPath, string destinationPath, string convertedFile, string sourceFile, string remuxFile, string edlFile, string srtFile, VideoTags metaData, JobStatus jobStatus, Log jobLog)
        {
            _profile = profile;
            _taskName = taskName;
            _jobLog = jobLog;
            _jobStatus = jobStatus;
            _workingPath = workingPath;
            _destinationPath = destinationPath;
            _convertedFile = convertedFile;
            _sourceFile = sourceFile;
            _remuxFile = remuxFile;
            _edlFile = edlFile;
            _srtFile = srtFile;
            _metaData = metaData;
            _prefix = prefix;

            Ini ini = new Ini(GlobalDefs.ProfileFile);
            commandPath = ini.ReadString(profile, prefix + "Path", "").ToLower().Trim();
            commandParameters = ini.ReadString(profile, prefix + "Parameters", "");
            hangPeriod = ini.ReadInteger(profile, prefix + "HangPeriod", GlobalDefs.HANG_PERIOD_DETECT);
            customCommandCritical = ini.ReadBoolean(profile, prefix + "Critical", false); // NOTE: if customCommandCritical is TRUE will need to return false in case it's a failure
            customCommandUISession = ini.ReadBoolean(profile, prefix + "UISession", false); // Does the custom command need a UI Session (Session 1) with admin privileges
            customCommandShowWindow = ini.ReadBoolean(profile, prefix + "ShowWindow", true); // Show the window or hide it
            customCommandExitCodeCheck = ini.ReadBoolean(profile, prefix + "ExitCodeCheck", false); // Don't check for exit code

            _jobLog.WriteEntry(this, "Custom command parameters read -> " + " \n" + _prefix + "Path = " + commandPath + " \n" + _prefix + "Parameters = " + commandParameters + " \n" + _prefix + "HangPeriod = " + hangPeriod.ToString(System.Globalization.CultureInfo.InvariantCulture) + " \n" + _prefix + "Critical = " + customCommandCritical.ToString() + " \n" + _prefix + "UISession = " + customCommandUISession.ToString() + " \n" + _prefix + "ShowWindow = " + customCommandShowWindow.ToString() + " \n" + _prefix + "ExitCodeCheck = " + customCommandExitCodeCheck.ToString(), Log.LogEntryType.Debug);
        }
Esempio n. 2
0
        public RemoteEngineForm()
        {
            InitializeComponent();

            Ini tempIni = new Ini(GlobalDefs.TempSettingsFile);
            string remoteServerName = tempIni.ReadString("Engine", "RemoteServerName", GlobalDefs.MCEBUDDY_SERVER_NAME);
            int remoteServerPort = tempIni.ReadInteger("Engine", "RemoteServerPort", int.Parse(GlobalDefs.MCEBUDDY_SERVER_PORT));

            engineNameTxt.Text = remoteServerName;
            portNoTxt.Text = remoteServerPort.ToString(System.Globalization.CultureInfo.InvariantCulture);
        }
Esempio n. 3
0
        private void ReadConversionSettings(Ini configIni)
        {
            // Read the Conversion Tasks
            string[] conversionRecords = configIni.ReadString("Engine", "Tasks", "").Split(',');
            foreach (string conversionRecord in conversionRecords)
            {
                if (String.IsNullOrEmpty(conversionRecord))
                    continue;

                ConversionJobOptions cjo = new ConversionJobOptions();

                cjo.taskName = conversionRecord;
                cjo.profile = configIni.ReadString(conversionRecord, "Profile", "");
                cjo.destinationPath = configIni.ReadString(conversionRecord, "DestinationPath", "");
                CheckPathEnding(ref cjo.destinationPath);
                cjo.workingPath = configIni.ReadString(conversionRecord, "WorkingPath", "");
                CheckPathEnding(ref cjo.workingPath);
                cjo.fallbackToSourcePath = configIni.ReadBoolean(conversionRecord, "FallbackDestination", false);
                cjo.autoIncrementFilename = configIni.ReadBoolean(conversionRecord, "AutoIncrementFilename", false);
                cjo.skipReprocessing = configIni.ReadBoolean(conversionRecord, "SkipReprocessing", false);
                cjo.checkReprocessingHistory = configIni.ReadBoolean(conversionRecord, "CheckReprocessingHistory", false);
                cjo.addToiTunes = configIni.ReadBoolean(conversionRecord, "AddToiTunesLibrary", false);
                cjo.addToWMP = configIni.ReadBoolean(conversionRecord, "AddToWMPLibrary", false);
                cjo.maxWidth = configIni.ReadInteger(conversionRecord, "MaxWidth", 720);
                cjo.FPS = configIni.ReadString(conversionRecord, "FPS", "");
                cjo.renameBySeries = configIni.ReadBoolean(conversionRecord, "RenameBySeries", true);
                cjo.altRenameBySeries = configIni.ReadBoolean(conversionRecord, "AltRenameBySeries", false);
                cjo.customRenameBySeries = configIni.ReadString(conversionRecord, "CustomRenameBySeries", "");
                cjo.renameOnly = configIni.ReadBoolean(conversionRecord, "RenameOnly", false);
                cjo.fileSelection = configIni.ReadString(conversionRecord, "FileSelection", "");
                cjo.metaShowSelection = configIni.ReadString(conversionRecord, "MetaSelection", "");
                cjo.metaNetworkSelection = configIni.ReadString(conversionRecord, "MetaChannelSelection", "");
                string monitorNameList = configIni.ReadString(conversionRecord, "MonitorTaskNames", "");
                if (String.IsNullOrWhiteSpace(monitorNameList))
                    cjo.monitorTaskNames = null; // list should be empty if nothing is there
                else
                    cjo.monitorTaskNames = monitorNameList.Split(',');
                cjo.audioLanguage = configIni.ReadString(conversionRecord, "AudioLanguage", "");
                string audioOffsetStr = configIni.ReadString(conversionRecord, "AudioOffset", "0");
                double.TryParse(audioOffsetStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cjo.audioOffset);
                cjo.drc = configIni.ReadBoolean(conversionRecord, "DRC", true);
                cjo.stereoAudio = configIni.ReadBoolean(conversionRecord, "StereoAudio", true);
                cjo.encoderSelectBestAudioTrack = configIni.ReadBoolean(conversionRecord, "EncoderSelectBestAudioTrack", true);
                cjo.autoDeInterlace = configIni.ReadBoolean(conversionRecord, "AutoDeInterlace", true);
                cjo.preferHardwareEncoding = configIni.ReadBoolean(conversionRecord, "PreferHardwareEncoding", true);
                cjo.startTrim = configIni.ReadInteger(conversionRecord, "StartTrim", 0);
                cjo.endTrim = configIni.ReadInteger(conversionRecord, "EndTrim", 0);
                cjo.insertQueueTop = configIni.ReadBoolean(conversionRecord, "InsertQueueTop", false);
                cjo.extractXML = configIni.ReadBoolean(conversionRecord, "ExtractXML", false);
                cjo.writeMetadata = configIni.ReadBoolean(conversionRecord, "WriteMetadata", true);
                cjo.disableCropping = configIni.ReadBoolean(conversionRecord, "DisableCropping", false);
                cjo.commercialSkipCut = configIni.ReadBoolean(conversionRecord, "TaskCommercialSkipCut", false);
                cjo.skipCopyBackup = configIni.ReadBoolean(conversionRecord, "SkipCopyBackup", false);
                cjo.skipRemuxing = configIni.ReadBoolean(conversionRecord, "SkipRemux", false);
                cjo.ignoreCopyProtection = configIni.ReadBoolean(conversionRecord, "IgnoreCopyProtection", false);
                cjo.tivoMAKKey = configIni.ReadString(conversionRecord, "TiVOMAKKey", "");
                cjo.downloadSeriesDetails = configIni.ReadBoolean(conversionRecord, "DownloadSeriesDetails", true);
                cjo.downloadBanner = configIni.ReadBoolean(conversionRecord, "DownloadBanner", true);
                cjo.enabled = configIni.ReadBoolean(conversionRecord, "Enabled", true);
                cjo.extractCC = configIni.ReadString(conversionRecord, "ExtractCC", "");
                cjo.embedSubtitlesChapters = configIni.ReadBoolean(conversionRecord, "EmbedSubtitlesChapters", false);
                cjo.prioritizeOriginalBroadcastDateMatch = configIni.ReadBoolean(conversionRecord, "PrioritizeOriginalBroadcastDateMatch", false);

                string ccOffsetStr = configIni.ReadString(conversionRecord, "CCOffset", GlobalDefs.DefaultCCOffset);
                double.TryParse(ccOffsetStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cjo.ccOffset);

                string qualityMultiplierStr = configIni.ReadString(conversionRecord, "QualityMultiplier", "1");
                double.TryParse(qualityMultiplierStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cjo.qualityMultiplier);
                if (cjo.qualityMultiplier <= 0.01) cjo.qualityMultiplier = 0.01F;
                if (cjo.qualityMultiplier > 4) cjo.qualityMultiplier = 4F;

                string volumeMultiplierStr = configIni.ReadString(conversionRecord, "VolumeMultiplier", "0");
                double.TryParse(volumeMultiplierStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out cjo.volumeMultiplier);
                if (cjo.volumeMultiplier <= -20) cjo.volumeMultiplier = -20F; //-10db minimum
                if (cjo.volumeMultiplier > 60) cjo.volumeMultiplier = 60F; //30db max

                string metaShowType = configIni.ReadString(conversionRecord, "MetaShowTypeSelection", ShowType.Default.ToString());
                if (String.Compare(metaShowType, ShowType.Movie.ToString(), true) == 0)
                    cjo.metaShowTypeSelection = ShowType.Movie;
                else if (String.Compare(metaShowType, ShowType.Series.ToString(), true) == 0)
                    cjo.metaShowTypeSelection = ShowType.Series;
                else if (String.Compare(metaShowType, ShowType.Sports.ToString(), true) == 0)
                    cjo.metaShowTypeSelection = ShowType.Sports;
                else
                    cjo.metaShowTypeSelection = ShowType.Default;

                string drmType = configIni.ReadString(conversionRecord, "MetaDRMTypeSelection", DRMType.All.ToString());
                if (String.Compare(drmType, DRMType.Protected.ToString(), true) == 0)
                    cjo.metaDRMSelection = DRMType.Protected;
                else if (String.Compare(drmType, DRMType.Unprotected.ToString(), true) == 0)
                    cjo.metaDRMSelection = DRMType.Unprotected;
                else
                    cjo.metaDRMSelection = DRMType.All;

                string showType = configIni.ReadString(conversionRecord, "ForceShowType", ShowType.Default.ToString());
                if (String.Compare(showType, ShowType.Movie.ToString(), true) == 0)
                    cjo.forceShowType = ShowType.Movie;
                else if (String.Compare(showType, ShowType.Series.ToString(), true) == 0)
                    cjo.forceShowType = ShowType.Series;
                else if (String.Compare(showType, ShowType.Sports.ToString(), true) == 0)
                    cjo.forceShowType = ShowType.Sports;
                else
                    cjo.forceShowType = ShowType.Default;
                
                string commercialRemovalStr = configIni.ReadString(conversionRecord, "CommercialRemoval", CommercialRemovalOptions.Comskip.ToString());
                if (String.Compare(commercialRemovalStr, CommercialRemovalOptions.Comskip.ToString(), true) == 0)
                    cjo.commercialRemoval = CommercialRemovalOptions.Comskip;
                else if (String.Compare(commercialRemovalStr, CommercialRemovalOptions.ShowAnalyzer.ToString(), true) == 0)
                    cjo.commercialRemoval = CommercialRemovalOptions.ShowAnalyzer;
                else
                    cjo.commercialRemoval = CommercialRemovalOptions.None;
                
                cjo.comskipIni = configIni.ReadString(conversionRecord, "ComskipINI", "");

                cjo.domainName = configIni.ReadString(conversionRecord, "DomainName", "");
                cjo.userName = configIni.ReadString(conversionRecord, "UserName", "Guest");
                cjo.password = configIni.ReadString(conversionRecord, "Password", "");
                if (!String.IsNullOrEmpty(cjo.password))
                    cjo.password = Crypto.Decrypt(cjo.password); // Password is kept as encrypted

                int metaCorrectionsCount = configIni.ReadInteger(conversionRecord, "MetaCorrectionsCount", 0);
                if (metaCorrectionsCount < 1)
                    cjo.metadataCorrections = null;
                else
                {
                    cjo.metadataCorrections = new ConversionJobOptions.MetadataCorrectionOptions[metaCorrectionsCount];
                    for (int i = 0; i < metaCorrectionsCount; i++) // The entries are kept in their own section, easier to manage
                    {
                        cjo.metadataCorrections[i] = new ConversionJobOptions.MetadataCorrectionOptions();
                        cjo.metadataCorrections[i].originalTitle = configIni.ReadString(conversionRecord + "-MetaCorrectionEntries", "OriginalTitle" + i.ToString(), "");
                        cjo.metadataCorrections[i].correctedTitle = configIni.ReadString(conversionRecord + "-MetaCorrectionEntries", "CorrectedTitle" + i.ToString(), "");
                        cjo.metadataCorrections[i].tvdbSeriesId = configIni.ReadString(conversionRecord + "-MetaCorrectionEntries", "TVDBSeriesId" + i.ToString(), "");
                        cjo.metadataCorrections[i].imdbSeriesId = configIni.ReadString(conversionRecord + "-MetaCorrectionEntries", "IMDBSeriesId" + i.ToString(), "");
                    }
                }

                mceBuddyConfSettings.conversionTasks.Add(cjo); // Add the Monitor Task object
            }
        }
Esempio n. 4
0
        private void ReadGeneralSettings(Ini configIni)
        {
            // Read the General Settings
            ReadHourMinute(configIni, ref mceBuddyConfSettings.generalOptions.wakeHour, ref mceBuddyConfSettings.generalOptions.wakeMinute, "Wake");
            ReadHourMinute(configIni, ref mceBuddyConfSettings.generalOptions.startHour, ref mceBuddyConfSettings.generalOptions.startMinute, "Start");
            ReadHourMinute(configIni, ref mceBuddyConfSettings.generalOptions.stopHour, ref mceBuddyConfSettings.generalOptions.stopMinute, "Stop");

            mceBuddyConfSettings.generalOptions.domainName = configIni.ReadString("Engine", "DomainName", "");
            mceBuddyConfSettings.generalOptions.userName = configIni.ReadString("Engine", "UserName", "Guest");
            mceBuddyConfSettings.generalOptions.password = configIni.ReadString("Engine", "Password", "");
            if (!String.IsNullOrEmpty(mceBuddyConfSettings.generalOptions.password))
                mceBuddyConfSettings.generalOptions.password = Crypto.Decrypt(mceBuddyConfSettings.generalOptions.password); // Password is kept as encrypted
            mceBuddyConfSettings.generalOptions.daysOfWeek = configIni.ReadString("Engine", "DaysOfWeek", "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday");
            mceBuddyConfSettings.generalOptions.maxConcurrentJobs = configIni.ReadInteger("Engine", "MaxConcurrentJobs", 1);
            mceBuddyConfSettings.generalOptions.logJobs = configIni.ReadBoolean("Engine", "LogJobs", true);
            mceBuddyConfSettings.generalOptions.logLevel = configIni.ReadInteger("Engine", "LogLevel", 3);
            mceBuddyConfSettings.generalOptions.logKeepDays = configIni.ReadInteger("Engine", "LogKeepDays", 15);
            mceBuddyConfSettings.generalOptions.deleteOriginal = configIni.ReadBoolean("Engine", "DeleteOriginal", false);
            mceBuddyConfSettings.generalOptions.useRecycleBin = configIni.ReadBoolean("Engine", "UseRecycleBin", false);
            mceBuddyConfSettings.generalOptions.archiveOriginal = configIni.ReadBoolean("Engine", "ArchiveOriginal", false);
            mceBuddyConfSettings.generalOptions.deleteConverted = configIni.ReadBoolean("Engine", "DeleteConverted", false); 
            mceBuddyConfSettings.generalOptions.allowSleep = configIni.ReadBoolean("Engine", "AllowSleep", true);
            mceBuddyConfSettings.generalOptions.suspendOnBattery = configIni.ReadBoolean("Engine", "SuspendOnBattery", false);
            mceBuddyConfSettings.generalOptions.minimumAge = configIni.ReadInteger("Engine", "MinimumAge", 0);
            mceBuddyConfSettings.generalOptions.sendEmail = configIni.ReadBoolean("Engine", "SendEmail", false);
            mceBuddyConfSettings.generalOptions.locale = configIni.ReadString("Engine", "Locale", CultureInfo.CurrentCulture.Name);
            mceBuddyConfSettings.generalOptions.tempWorkingPath = configIni.ReadString("Engine", "TempWorkingPath", "");
            CheckPathEnding(ref mceBuddyConfSettings.generalOptions.tempWorkingPath);
            mceBuddyConfSettings.generalOptions.archivePath = configIni.ReadString("Engine", "ArchivePath", "");
            CheckPathEnding(ref mceBuddyConfSettings.generalOptions.archivePath);
            mceBuddyConfSettings.generalOptions.failedPath = configIni.ReadString("Engine", "FailedPath", "");
            CheckPathEnding(ref mceBuddyConfSettings.generalOptions.failedPath);
            mceBuddyConfSettings.generalOptions.spaceCheck = configIni.ReadBoolean("Engine", "SpaceCheck", true);
            mceBuddyConfSettings.generalOptions.comskipPath = configIni.ReadString("Engine", "CustomComskipPath", "");
            mceBuddyConfSettings.generalOptions.customProfilePath = configIni.ReadString("Engine", "CustomProfilePath", "");
            mceBuddyConfSettings.generalOptions.hangTimeout = configIni.ReadInteger("Engine", "HangPeriod", GlobalDefs.HANG_PERIOD_DETECT);
            mceBuddyConfSettings.generalOptions.pollPeriod = configIni.ReadInteger("Engine", "PollPeriod", GlobalDefs.MONITOR_POLL_PERIOD);
            mceBuddyConfSettings.generalOptions.processPriority = configIni.ReadString("Engine", "ProcessPriority", "Normal");
            mceBuddyConfSettings.generalOptions.CPUAffinity = (IntPtr) configIni.ReadLong("Engine", "CPUAffinity", 0);
            mceBuddyConfSettings.generalOptions.engineRunning = configIni.ReadBoolean("Engine", "EngineRunning", false);
            mceBuddyConfSettings.generalOptions.localServerPort = configIni.ReadInteger("Engine", "LocalServerPort", int.Parse(GlobalDefs.MCEBUDDY_SERVER_PORT));
            mceBuddyConfSettings.generalOptions.uPnPEnable = configIni.ReadBoolean("Engine", "UPnPEnable", false);
            mceBuddyConfSettings.generalOptions.firewallExceptionEnabled = configIni.ReadBoolean("Engine", "FirewallExceptionEnable", false);
            string srtSegmentOffset = configIni.ReadString("Engine", "SubtitleSegmentOffset", GlobalDefs.SEGMENT_CUT_OFFSET_GOP_COMPENSATE);
            double.TryParse(srtSegmentOffset, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out mceBuddyConfSettings.generalOptions.subtitleSegmentOffset);
            
            ReadEMailSettings(configIni);
        }
Esempio n. 5
0
 private void ReadEMailSettings(Ini configIni)
 {
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.smtpServer = configIni.ReadString("Engine", "eMailServer", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.port = configIni.ReadInteger("Engine", "eMailPort", 25); // default port is 25
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.ssl = configIni.ReadBoolean("Engine", "eMailSSL", false);
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.fromAddress = configIni.ReadString("Engine", "eMailFrom", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.toAddresses = configIni.ReadString("Engine", "eMailTo", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.successEvent = configIni.ReadBoolean("Engine", "eMailSuccess", true);
     mceBuddyConfSettings.generalOptions.eMailSettings.failedEvent = configIni.ReadBoolean("Engine", "eMailFailed", true);
     mceBuddyConfSettings.generalOptions.eMailSettings.cancelledEvent = configIni.ReadBoolean("Engine", "eMailCancelled", true);
     mceBuddyConfSettings.generalOptions.eMailSettings.startEvent = configIni.ReadBoolean("Engine", "eMailStart", true);
     mceBuddyConfSettings.generalOptions.eMailSettings.downloadFailedEvent = configIni.ReadBoolean("Engine", "eMailDownloadFailed", true);
     mceBuddyConfSettings.generalOptions.eMailSettings.queueEvent = configIni.ReadBoolean("Engine", "eMailQueue", true);
     mceBuddyConfSettings.generalOptions.eMailSettings.successSubject = configIni.ReadString("Engine", "eMailSuccessSubject", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.failedSubject = configIni.ReadString("Engine", "eMailFailedSubject", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.cancelledSubject = configIni.ReadString("Engine", "eMailCancelledSubject", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.startSubject = configIni.ReadString("Engine", "eMailStartSubject", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.downloadFailedSubject = configIni.ReadString("Engine", "eMailDownloadFailedSubject", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.queueSubject = configIni.ReadString("Engine", "eMailQueueSubject", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.skipBody = configIni.ReadBoolean("Engine", "eMailSkipBody", false);
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.userName = configIni.ReadString("Engine", "eMailUsername", "");
     mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.password = configIni.ReadString("Engine", "eMailPassword", "");
     if (!String.IsNullOrEmpty(mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.password))
         mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.password = Util.Crypto.Decrypt(mceBuddyConfSettings.generalOptions.eMailSettings.eMailBasicSettings.password); // password is stored encrypted
 }
Esempio n. 6
0
        private void ReadHourMinute(Ini configIni, ref int hour, ref int minute, string prefix)
        {
            hour = configIni.ReadInteger("Engine", prefix + "Hour", -1);
            minute = configIni.ReadInteger("Engine", prefix + "Minute", -1);

            if ((hour < 0) || (hour > 24)) hour = -1;
            if ((minute < 0) || (minute > 59)) minute = -1;
        }
Esempio n. 7
0
        /// <summary>
        /// Tries to keep connected to the MCEBuddy Engine over TCP/IP. Once connected it downloads the MCEBuddy Config options from the server.
        /// </summary>
        /// <returns>True if it is connected to the Pipe</returns>
        private void TryConnect()
        {
            while (!_exit) // Keep trying to connect as long as app is running
            {
                bool configLockTaken = false; // Flag to see state of lock
                
                try
                {
                    Monitor.Enter(_configLock, ref configLockTaken); // Take a lock before getting settings, incase Settings are being changed by the user
                    if (_pipeProxy.ServiceShutdownBySystem()) // Has the system initated shutdown, if so we need to shutdown the GUI (to avoid uninstall issues)
                    {
                        Monitor.Exit(_configLock);
                        configLockTaken = false;
                        _exit = true; // We are done, release all threads and resources
                        this.Close(); // Close the GUI
                        continue;
                    }
                    MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(_pipeProxy.GetConfigParameters()); // Get the parameters from the Engine we are connected to
                    _jobs = _pipeProxy.GetAllJobsInQueueStatus();
                    _isEngineRunning = _pipeProxy.EngineRunning();
                    _isEngineSuspended = _pipeProxy.IsSuspended();
                    _isEngineCrashed = _pipeProxy.EngineCrashed();
                    _isWithinConversionTimes = _pipeProxy.WithinConversionTimes();
                    Monitor.Exit(_configLock);
                    configLockTaken = false;
                    _isEngineConnected = true; // All good, we are connected

                    Thread.Sleep(_connectPeriod * (WindowState == FormWindowState.Minimized ? GlobalDefs.GUI_MINIMIZED_ENGINE_POLL_SLOW_FACTOR : 1)); // Check again in x seconds, refresh y times slower
                    continue;
                }
                catch (Exception) // Whoops pipe broken!
                {
                    if (configLockTaken)
                    {
                        Monitor.Exit(_configLock); // Release the lock
                        configLockTaken = false;
                    }
                    _isWithinConversionTimes = _isEngineConnected = _isEngineCrashed = _isEngineRunning = _isEngineSuspended = false; // We are no longer connected
                    _pipeProxy = null; // We should start over
                }

                try // Try to reconnect
                {
                    ChannelFactory<ICore> pipeFactory;
                    string serverString;

                    Ini tempIni = new Ini(GlobalDefs.TempSettingsFile);
                    string remoteServerName = tempIni.ReadString("Engine", "RemoteServerName", GlobalDefs.MCEBUDDY_SERVER_NAME);
                    int remoteServerPort = tempIni.ReadInteger("Engine", "RemoteServerPort", int.Parse(GlobalDefs.MCEBUDDY_SERVER_PORT));

                    if (serverInfoLbl.InvokeRequired) // Cannot access UI elements directly from a non UI thread
                        serverInfoLbl.Invoke(new MethodInvoker(delegate { serverInfoLbl.Text = "Engine: " + remoteServerName + "  Port: " + remoteServerPort.ToString(); }));
                    else
                        serverInfoLbl.Text = "Engine: " + remoteServerName + "  Port: " + remoteServerPort.ToString();

                    // If it's LOCALHOST, we use local NAMED PIPE else network SOAP WEB SERVICES
                    if (remoteServerName == GlobalDefs.MCEBUDDY_SERVER_NAME)
                    {
                        // local NAMED PIPE
                        serverString = GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE;
                        NetNamedPipeBinding npb = new NetNamedPipeBinding();
                        TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT;
                        npb.OpenTimeout = npb.CloseTimeout = npb.SendTimeout = npb.ReceiveTimeout = timeoutPeriod;
                        npb.TransferMode = TransferMode.Buffered;
                        npb.MaxReceivedMessageSize = npb.MaxBufferPoolSize = npb.MaxBufferSize = Int32.MaxValue;
                        npb.ReaderQuotas = XmlDictionaryReaderQuotas.Max;
                        pipeFactory = new ChannelFactory<ICore>(npb, new EndpointAddress(serverString));
                    }
                    else
                    {
                        // network SOAP WEB SERVICES
                        serverString = GlobalDefs.MCEBUDDY_WEB_SOAP_PIPE;
                        serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_NAME, remoteServerName); // Update the Server Name with that from the config file
                        serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_PORT, remoteServerPort.ToString(CultureInfo.InvariantCulture)); // Update the Server Port with that from the config file
                        BasicHttpBinding ntb = new BasicHttpBinding(GlobalDefs.MCEBUDDY_PIPE_SECURITY);
                        TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT;
                        ntb.OpenTimeout = ntb.CloseTimeout = ntb.SendTimeout = ntb.ReceiveTimeout = timeoutPeriod;
                        ntb.TransferMode = TransferMode.Buffered;
                        ntb.MaxReceivedMessageSize = ntb.MaxBufferPoolSize = ntb.MaxBufferSize = Int32.MaxValue;
                        ntb.ReaderQuotas = XmlDictionaryReaderQuotas.Max;
                        pipeFactory = new ChannelFactory<ICore>(ntb, new EndpointAddress(serverString));
                    }

                    // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
                    foreach (OperationDescription operation in pipeFactory.Endpoint.Contract.Operations)
                    {
                        DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                        if (dataContractBehavior != null)
                            dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }

                    Monitor.Enter(_configLock, ref configLockTaken);
                    ICore tempPipeProxy = pipeFactory.CreateChannel();
                    MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(tempPipeProxy.GetConfigParameters()); // Get the parameters from the Engine we are connected to
                    _jobs = tempPipeProxy.GetAllJobsInQueueStatus();
                    _isEngineRunning = tempPipeProxy.EngineRunning();
                    _isEngineSuspended = tempPipeProxy.IsSuspended();
                    _isEngineCrashed = tempPipeProxy.EngineCrashed();
                    _isWithinConversionTimes = tempPipeProxy.WithinConversionTimes();
                    GlobalDefs.profilesSummary = tempPipeProxy.GetProfilesSummary(); // Get a list of all the profiles and descriptions
                    GlobalDefs.engineProcessorCount = tempPipeProxy.GetProcessorCount(); // Number of processors on the engine machine
                    try // special case, ShowAnalyzer sometimes hangs the system and fails to respond, ignore and continue with log
                    {
                        GlobalDefs.showAnalyzerInstalled = tempPipeProxy.ShowAnalyzerInstalled(); // Check if Showanalyzer is installed
                    }
                    catch (Exception e)
                    {
                        Log.WriteSystemEventLog("Unable to get status of ShowAnalyzer, please reinstall ShowAnalyzer and reboot the system. Error " + e.ToString(), EventLogEntryType.Error);
                        MessageBox.Show(Localise.GetPhrase("ShowAnalyzer is not responding. Please the reboot system or reinstall ShowAnalyzer."), Localise.GetPhrase("ShowAnalyzer Not Responding"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    Monitor.Exit(_configLock);
                    configLockTaken = false;

                    // all good again, update the status
                    _pipeProxy = tempPipeProxy;
                    _versionMismatch = false; // set after pipeProxy
                    _isEngineConnected = true;
                }
                catch (Exception e)
                {
                    // Check for version mistmatch
                    if ((e.InnerException is System.Runtime.Serialization.SerializationException) || (e is System.ServiceModel.ActionNotSupportedException))
                        _versionMismatch = true;
                    else
                        _versionMismatch = false;

                    //WriteEventLog(Localise.GetPhrase("MCEBuddy GUI: Unable to create pipe to MCEBuddy service"), EventLogEntryType.Warning); //not required since this call will fail when MCEBuddy Service has not started and will overflow the eventlog. The message will be shown on the GUI
                    if (configLockTaken)
                    {
                        Monitor.Exit(_configLock);
                        configLockTaken = false;
                    }
                    _isWithinConversionTimes = _isEngineConnected = _isEngineCrashed = _isEngineRunning = _isEngineSuspended = false; // Still broken
                    _pipeProxy = null; // Last item

                    Thread.Sleep(_connectPeriod * (WindowState == FormWindowState.Minimized ? GlobalDefs.GUI_MINIMIZED_ENGINE_POLL_SLOW_FACTOR : 1)); // Try to connect every x seconds
                }

                if (_isEngineConnected) // SetUserLocale should never be called from within a try catch statement since it can cause an exception if there is an application restart
                    SetUserLocale(); // ReInitialize MCEBuddy (we may have been disconnected and parameters changed, connected to a new engine etc)
            }
        }