private Option <ADSK.File> DownloadConfiguration(string configPath, int networkRetries, string synchronizerConfigurationPath, Option <MCADCommon.LogCommon.DisposableFileLogger> logger, List <string> errors)
        {
            ADSK.File[]        configurationFiles = connection.WebServiceManager.DocumentService.FindLatestFilesByPaths(new String[] { synchronizerConfigurationPath });
            Option <ADSK.File> configurationFile  = Option.None;

            if (configurationFiles.Count() > 0)
            {
                VaultCommunication.DownloadFilesWithChecksum(connection, new List <VaultEagleLib.Model.DataStructures.DownloadFile>()
                {
                    new VaultEagleLib.Model.DataStructures.DownloadFile(configurationFiles[0], configPath, false, false)
                }, logger, networkRetries);                                                                                                                                                                                                                            /*MCADCommon.VaultCommon.FileOperations.DownloadFile(connection, configurationFiles[0], path: configPath);*/
                if (VaultUtils.HandleNetworkErrors(() => !System.IO.File.Exists(Path.Combine(configPath, configurationFiles[0].Name)), networkRetries))
                {
                    logger.IfSomeDo(l => l.Error("Failed to download configuration file."));
                    errors.Add("Failed to download configuration file.");
                    //if (mailInfo.IsSome)
                    //{
                    //    MCADCommon.MailCommon.Mailer mailer = new MCADCommon.MailCommon.Mailer(mailInfo.Get());
                    //    mailer.Mail("Vault synchronizer failed", errors.StringJoin("\n\r"), new List<string>());
                    //}
                }
                configurationFile = configurationFiles[0].AsOption();
            }
            else
            {
                logger.IfSomeDo(l => l.Error("Could not find configuration file."));
                errors.Add("Could not find configuration file.");
                //if (mailInfo.IsSome)
                //{
                //    MCADCommon.MailCommon.Mailer mailer = new MCADCommon.MailCommon.Mailer(mailInfo.Get());
                //    mailer.Mail("Vault synchronizer failed", errors.StringJoin("\n\r"), new List<string>());
                //}
            }
            return(configurationFile);
        }
        private bool IsFileInServerLocalFolder(FileFolder fileFolder, string localPath)
        {
            string serverName = VaultUtils.GetServerName(localPath);

            return(fileFolder.Folder.FullName.StartsWith("$/LocalDesign/" + serverName + "/", StringComparison.InvariantCultureIgnoreCase));
        }
        /**********************************************************************************************************************/
        public List <Tuple <string, string> > Synchronize(string configPath, int networkRetries, string synchronizerConfigurationPath, bool useNotification, Option <MCADCommon.LogCommon.DisposableFileLogger> logger, ref Option <string> mailFrom)
        {
            bool disposeLog = false;
            List <Tuple <string, string> > filesToMove = new List <Tuple <string, string> >();

            try
            {
                NotifyIcon trayIcon = new NotifyIcon();
                trayIcon.Text           = "Fetching files to synchronize.";
                trayIcon.Icon           = VaultEagleLib.Properties.Resources.Eagle;
                trayIcon.BalloonTipText = "Fetching files to synchronize.";

                ContextMenu trayMenu = new ContextMenu();

                trayIcon.ContextMenu = trayMenu;
                trayIcon.Visible     = true;
                if (useNotification)
                {
                    trayIcon.ShowBalloonTip(4000);
                }
                errors = new List <string>();
                // Fetch configuration file, mail on failure.
                Option <ADSK.File> configurationFile = Option.None;
                string             path;
                logger.IfSomeDo(l => l.Trace("Before downloading configuration."));
                if (synchronizerConfigurationPath.StartsWith("$"))
                {
                    configurationFile = DownloadConfiguration(configPath, networkRetries, synchronizerConfigurationPath, logger, errors);
                    if (configurationFile.IsNone)
                    {
                        return(filesToMove);
                    }
                    path = Path.Combine(configPath, configurationFile.Get().Name);
                }
                else
                {
                    path = Environment.ExpandEnvironmentVariables(synchronizerConfigurationPath);
                }
                logger.IfSomeDo(l => l.Trace("After downloading configuration."));


                VaultEagleLib.SynchronizerSettings configuration = VaultEagleLib.SynchronizerSettings.Read(networkRetries, logger, path);
                if (logger.IsNone && configuration.LogFile.IsSome)
                {
                    logger     = new MCADCommon.LogCommon.DisposableFileLogger(MCADCommon.LogCommon.DisposableFileLogger.CreateLogFilePath(configuration.configPath, configuration.LogFile.Get()), configuration.LogLevel).AsOption();
                    disposeLog = true;
                }

                //   Option<Logg
                //  if (configuration.LogFile.IsSome)
                logger.IfSomeDo(l => l.Info("Synchronizing vault files."));

                // Fetch files to sync, mail on failure.
                //  List<FileFolder> filesAndFoldersToUpdate = /*new List<FileFolder>();*/FetchingFilesFromVaultToSynchronize(ref mailInfo, lastSyncTime, logger, errors, configuration);
                if (configuration.OverrideMailSender.IsSome)
                {
                    mailFrom = configuration.OverrideMailSender;
                }
                /*List<Tuple<ADSK.File, string, bool, bool>>*/ List <VaultEagleLib.Model.DataStructures.DownloadItem> filesToUpdate = FindFilesChangedSinceLastSync(connection, configuration.UseLastSync, configuration.LastSyncTime, configuration.VaultRoot, networkRetries, trayIcon, configuration.Items.ToArray(), logger);

                foreach (VaultEagleLib.SynchronizationItem item in configuration.Items)
                {
                    foreach (Tuple <string, string> tempFileAndFinalPath in item.TempFilesAndFinalPath)
                    {
                        filesToMove.Add(tempFileAndFinalPath);
                    }
                }

                string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                logger.IfSomeDo(l => l.Info("Synchronizing: " + filesToUpdate.Count + " files."));
                //  if (filesToUpdate.Count > 0)
                {
                    trayIcon.Text = "Downloaded 0 of " + filesToUpdate.Count + " files.";

                    try
                    {
                        errors.AddRange(SynchronizeFiles(networkRetries, logger, errors, configuration, filesToUpdate, trayIcon));
                        List <VaultEagleLib.Model.DataStructures.DownloadFile> downloadedFiles = filesToUpdate.OfType <VaultEagleLib.Model.DataStructures.DownloadFile>().ToList();
                        foreach (string getAndRun in configuration.GetAndRun)
                        {
                            // string test1 = filesToUpdate[filesToUpdate.Count - 1].Item2.Replace(configuration.VaultRoot, "$").Replace("\\", "/") + "/" + filesToUpdate[filesToUpdate.Count - 1].Item1.Name;
                            if (downloadedFiles.Any(f => getAndRun.Equals(f.VaultFileName(configuration.VaultRoot))))
                            {
                                VaultEagleLib.Model.DataStructures.DownloadFile file = downloadedFiles.Where(f => getAndRun.Equals(f.VaultFileName(configuration.VaultRoot))).First();
                                VaultEagle.VaultUtils.HandleNetworkErrors(() =>
                                {
                                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                    proc.StartInfo.FileName         = file.LocalFileName;
                                    proc.Start();
                                    proc.WaitForExit();
                                }, networkRetries);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.IfSomeDo(l => l.Error(ex.Message));
                        errors.Add("Failure synchronizing files.");
                    }

                    if (errors.Count == 0 && configuration.LastSyncFile.IsSome)
                    {
                        if (!VaultUtils.HandleNetworkErrors(() => System.IO.Directory.Exists(configuration.configPath), networkRetries))
                        {
                            VaultUtils.HandleNetworkErrors(() => System.IO.Directory.CreateDirectory(configuration.configPath), networkRetries);
                        }

                        if (VaultUtils.HandleNetworkErrors(() => System.IO.File.Exists(Path.Combine(configuration.configPath, configuration.LastSyncFile.Get() + ".txt")), networkRetries))
                        {
                            VaultUtils.HandleNetworkErrors(() => System.IO.File.Delete(Path.Combine(configuration.configPath, configuration.LastSyncFile.Get() + ".txt")), networkRetries);
                        }

                        try
                        {
                            using (TextWriter tw = new StreamWriter(VaultUtils.HandleNetworkErrors(() => System.IO.File.Create(Path.Combine(configuration.configPath, configuration.LastSyncFile.Get() + ".txt")), networkRetries)))
                                tw.WriteLine(now);
                        }
                        catch { }
                    }
                    if (useNotification)
                    {
                        if (errors.Count > 0)
                        {
                            trayIcon.BalloonTipText = "Errors synchronizing files.";
                            if (useNotification)
                            {
                                trayIcon.ShowBalloonTip(2000);
                            }
                        }
                        else
                        {
                            trayIcon.BalloonTipText = "Finished synchronizing files.";
                            if (useNotification)
                            {
                                trayIcon.ShowBalloonTip(2000);
                            }
                        }
                    }
                }
                trayIcon.DisposeUnlessNull(ref trayIcon);
            }
            catch (Exception ex)
            {
                logger.IfSomeDo(l => l.Error(ex.Message));
            }
            logger.IfSomeDo(l => l.Trace("Synchronizing complete."));
            if (disposeLog && logger.IsSome)
            {
                logger.Get().Dispose();
            }


            return(filesToMove);
        }