Beispiel #1
0
 private static Operations.SavedOpData ErrorResult(Operations.SavedOpData update, IInstallationResult installationRes, string message)
 {
     update.success = false.ToString().ToLower();
     update.error   = message + ": " + installationRes.HResult + ", Result code: " + installationRes.ResultCode;
     Logger.Log("Update Failed to Install: {0}", LogLevel.Info, update.filedata_app_name + ", Error: " + update.error);
     return(update);
 }
Beispiel #2
0
        private void InstallSendResults(Operations.SavedOpData updateData, RvSofOperation operation, List <RVsofResult.AppsToAdd2> appsToAdd = null, List <RVsofResult.AppsToDelete2> appsToDelete = null)
        {
            try
            {
                var results = new RVsofResult();

                results.AppsToAdd    = results.AppsToAdd != null ? appsToAdd : new List <RVsofResult.AppsToAdd2>();
                results.AppsToDelete = results.AppsToDelete != null ? appsToDelete : new List <RVsofResult.AppsToDelete2>();

                results.AppId          = updateData.filedata_app_id;
                results.Operation      = updateData.operation;
                results.OperationId    = updateData.operation_id;
                results.Error          = updateData.error;
                results.RebootRequired = updateData.reboot_required;
                results.Success        = updateData.success;

                switch (updateData.operation)
                {
                case OperationValue.InstallWindowsUpdate:
                    results             = WindowsUpdates.AddAppDetailsToResults(results);
                    operation.RawResult = RvFormatter.Install(results);
                    break;

                case OperationValue.InstallCustomApp:
                    results             = CustomAppsManager.AddAppDetailsToResults(results);
                    operation.RawResult = RvFormatter.Install(results);
                    break;

                case OperationValue.InstallSupportedApp:
                    results             = SupportedAppsManager.AddAppDetailsToResults(results);
                    operation.RawResult = RvFormatter.Install(results);
                    break;

                case OperationValue.InstallAgentUpdate:
                    results             = AgentUpdateManager.AddAppDetailsToResults(results);
                    operation.RawResult = RvFormatter.AgentUpdate(results);
                    break;

                case OperationValue.Uninstall:
                    operation.RawResult = RvFormatter.Install(results);
                    break;
                }

                operation.Id     = updateData.operation_id;
                operation.Plugin = "rv";

                Operations.UpdateStatus(updateData, Operations.OperationStatus.ResultsPending);

                Logger.Log("Sending back results for {0}.", LogLevel.Info, updateData.filedata_app_name);
                if (SendResults(operation))
                {
                    Operations.CleanAllOperationData(updateData);
                }
            }
            catch (Exception e)
            {
                Logger.Log("Failed when attempting to send back results, Exception inside InstallSendResults().");
                Logger.LogException(e);
            }
        }
Beispiel #3
0
 private static Operations.SavedOpData ErrorResultsException(Operations.SavedOpData update, Exception e)
 {
     update.reboot_required = false.ToString().ToLower();
     update.error           = e.Message;
     update.success         = false.ToString().ToLower();
     Logger.Log("Update Failed: {0}", LogLevel.Debug, update.filedata_app_name);
     return(update);
 }
Beispiel #4
0
        private static UpdateCollection BundleRecursion(IUpdate bundle, Operations.SavedOpData updateData)
        {
            var collection   = new UpdateCollection();
            var index        = 0;
            var updateFolder = Path.Combine(UpdateDirectory, updateData.filedata_app_id);

            if (!Directory.Exists(updateFolder))
            {
                return(collection);
            }
            IList <string> updateFiles = Directory.GetFiles(updateFolder);

            foreach (IUpdate insideBundle in bundle.BundledUpdates)
            {
                //Recursive Call if there are more bundles inside this bundle.
                if (insideBundle.BundledUpdates.Count > 0)
                {
                    Logger.Log("    Found bundles inside {0}", LogLevel.Debug, insideBundle.Title);
                    var totalBundles = BundleRecursion(insideBundle, updateData);
                    Logger.Log("          - Loading {0} bundles for {1}", LogLevel.Debug, totalBundles.Count, insideBundle.Title);
                    foreach (IUpdate item in totalBundles)
                    {
                        Logger.Log("Adding {0}", LogLevel.Info, item.Title);
                        collection.Add(item);
                    }
                }

                if (insideBundle.IsInstalled != true)
                {
                    var finalFileCollection = new StringCollection();

                    List <DownloadUri> nodes = GrabLocalUpdateBundle(bundle.Identity.UpdateID, insideBundle.Title);

                    foreach (var iteration in nodes)
                    {
                        var fileCollection = new StringCollection();

                        foreach (var item in updateFiles)
                        {
                            var strip         = item.Split(new[] { '\\' });
                            var localFilename = strip[strip.Length - 1];

                            if (Operations.StringToFileName(localFilename).ToLower() == Operations.StringToFileName(iteration.FileName).ToLower())
                            {
                                fileCollection.Add(item);
                                finalFileCollection = fileCollection;
                                break;
                            }
                        }
                    }

                    ((IUpdate2)bundle.BundledUpdates[index]).CopyToCache(finalFileCollection);
                    collection.Add(bundle);
                }
                index++;
            }
            return(collection);
        }
Beispiel #5
0
        /// <summary>
        /// Gets the initial json send from server.
        /// Seperates the opertaion depending on which supported app is been installed.
        /// </summary>
        /// <param name="supportedApp">Json file from server.</param>
        /// <returns>Return SavedOpData populated with results.</returns>
        public static Operations.SavedOpData InstallSupportedAppsOperation(Operations.SavedOpData supportedApp)
        {
            var installResult = new InstallResult();

            try
            {
                if (supportedApp.filedata_app_name.ToLowerInvariant().Contains("flash"))
                {
                    installResult = ProcessFlash(supportedApp);
                }

                if (supportedApp.filedata_app_name.ToLowerInvariant().Contains("java"))
                {
                    installResult = ProcessJava(supportedApp);
                }

                if (supportedApp.filedata_app_name.ToLowerInvariant().Contains("reader") ||
                    supportedApp.filedata_app_name.ToLowerInvariant().Contains("acrobat"))
                {
                    installResult = ProcessReader(supportedApp);
                }

                //Supported App Failed to Install.
                if (!installResult.Success)
                {
                    supportedApp.success         = false.ToString().ToLower();
                    supportedApp.error           = String.Format("Failed: {0}", installResult.ExitCodeMessage);
                    supportedApp.reboot_required = false.ToString().ToLower();

                    Logger.Log("Supported ThirdParty App Failed to Install, Exit code {0}: {1}", LogLevel.Info, installResult.ExitCode, supportedApp.filedata_app_name + ", Error: " + supportedApp.error);
                    return(supportedApp);
                }

                //Supported App Installed OK
                supportedApp.success         = true.ToString().ToLower();
                supportedApp.error           = string.Empty;
                supportedApp.reboot_required = installResult.Restart.ToString().ToLower();

                Logger.Log("Supported ThirdParty App Installed Successfully: {0}", LogLevel.Info, supportedApp.filedata_app_name);
                return(supportedApp);
            }
            catch (Exception e)
            {
                supportedApp.success = false.ToString().ToLower();
                supportedApp.error   = String.Format("Failed to install Supported ThirdParty App, Exception error: {0}", e.Message);

                Logger.Log("Supported ThirdParty App failed to Install: {0}", LogLevel.Info, supportedApp.filedata_app_name + ", Error: " + supportedApp.error);
                return(supportedApp);
            }
        }
Beispiel #6
0
        private static UpdateCollection LoadUpdateCache(Operations.SavedOpData updateData, UpdateCollection updateCollection)
        {
            try
            {
                if (updateCollection == null)
                {
                    Logger.Log("Error when attempting to populate bundles for update, The UpdateCollection inside LoadUpdateCache() was NULL, ");
                    return(null);
                }

                foreach (IUpdate update in updateCollection)
                {
                    if (!String.Equals(updateData.filedata_app_name.Trim(), update.Title.Trim(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }

                    try
                    {
                        var collection = BundleRecursion(update, updateData);
                        Logger.Log("{0} bundles ready for {1}", LogLevel.Info, collection.Count, update.Title);
                        return(collection);
                    }
                    catch (Exception e)
                    {
                        Logger.Log("Unable to copy local files for update, possible that not all required update bundle files were included, Installation of {0} will not proceed. ", LogLevel.Info, updateData.filedata_app_name);
                        Logger.LogException(e);
                        if (e.InnerException != null)
                        {
                            Logger.LogException(e.InnerException);
                        }
                        return(null);
                    }
                }
                return(null);
            }
            catch (Exception e)
            {
                Logger.Log("Unable to load WUApi UpdateCache method. Its possible that WUAPI is corrupted, refer to C:\\Windows\\WindowsUpdate.log for details.", LogLevel.Error);
                Logger.LogException(e);
                if (e.InnerException != null)
                {
                    Logger.LogException(e.InnerException);
                }
                return(null);
            }
        }
Beispiel #7
0
        public static void WriteJsonFile(string filePath, Operations.SavedOpData tempSavedOpData)
        {
            var stream = new MemoryStream();

            var serializer = new DataContractJsonSerializer(typeof(Operations.SavedOpData));

            serializer.WriteObject(stream, tempSavedOpData);

            var json = Encoding.Default.GetString(stream.ToArray());

            //json = Security.Encrypt(json);

            stream.Close();

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            File.WriteAllText(filePath, json);
        }
        private static Operations.SavedOpData InstallOperation(string setupName, string clioptions)
        {
            try
            {
                var installResult = Tools.ExeInstall(setupName, clioptions);

                if (!installResult.Success)
                {
                    Data.Logger("FAILED");
                    var results = new Operations.SavedOpData();
                    results.success = false.ToString().ToLower();
                    results.operation_status = Operations.OperationStatus.Failed;
                    results.error = String.Format("Upgrade of RV Agent failed to complete: {0}. {1}. Exit code: {2}.",
                                                  setupName, installResult.ExitCodeMessage, installResult.ExitCode);
                    Operations.UpdateOperation(results, false, false, Operations.OperationStatus.Failed);
                    return results;
                }
                else
                {
                    Data.Logger("SUCCESS");
                    var results = new Operations.SavedOpData();
                    results.success = true.ToString().ToLower();
                    results.operation_status = Operations.OperationStatus.Installed;
                    results.error = string.Empty;
                    Operations.UpdateOperation(results, true, false, Operations.OperationStatus.Installed);
                    return results;
                }

            }
            catch (Exception e)
            {
                Data.Logger("FAILED, Exception inside InstallOperation()");
                var results = new Operations.SavedOpData();
                results.success = false.ToString();
                results.error = String.Format("Failed while installing RV Agent update, Exception: " + e.Message);
                Operations.UpdateOperation(results, false, false, Operations.OperationStatus.Failed);
                return results;
            }
        }
        private static Operations.SavedOpData InstallOperation(string setupName, string clioptions)
        {
            try
            {
                var installResult = Tools.ExeInstall(setupName, clioptions);

                if (!installResult.Success)
                {
                    Data.Logger("FAILED");
                    var results = new Operations.SavedOpData();
                    results.success          = false.ToString().ToLower();
                    results.operation_status = Operations.OperationStatus.Failed;
                    results.error            = String.Format("Upgrade of RV Agent failed to complete: {0}. {1}. Exit code: {2}.",
                                                             setupName, installResult.ExitCodeMessage, installResult.ExitCode);
                    Operations.UpdateOperation(results, false, false, Operations.OperationStatus.Failed);
                    return(results);
                }
                else
                {
                    Data.Logger("SUCCESS");
                    var results = new Operations.SavedOpData();
                    results.success          = true.ToString().ToLower();
                    results.operation_status = Operations.OperationStatus.Installed;
                    results.error            = string.Empty;
                    Operations.UpdateOperation(results, true, false, Operations.OperationStatus.Installed);
                    return(results);
                }
            }
            catch (Exception e)
            {
                Data.Logger("FAILED, Exception inside InstallOperation()");
                var results = new Operations.SavedOpData();
                results.success = false.ToString();
                results.error   = String.Format("Failed while installing RV Agent update, Exception: " + e.Message);
                Operations.UpdateOperation(results, false, false, Operations.OperationStatus.Failed);
                return(results);
            }
        }
Beispiel #10
0
        public static Operations.SavedOpData DownloadUpdate(Operations.SavedOpData update)
        {
            var uris = new List <DownloadUri>();

            foreach (var uriData in update.filedata_app_uris)
            {
                var tempDownloadUri = new DownloadUri();
                tempDownloadUri.FileName = uriData.file_name;
                tempDownloadUri.FileSize = uriData.file_size;
                tempDownloadUri.Hash     = uriData.file_hash;

                foreach (var uri in uriData.file_uris)
                {
                    tempDownloadUri.Uris.Add(uri);
                }

                uris.Add(tempDownloadUri);
            }

            try
            {
                if (Directory.Exists(AgentUpdateDirectory))
                {
                    Directory.Delete(AgentUpdateDirectory, true);
                }
                Directory.CreateDirectory(AgentUpdateDirectory);
            }catch {}


            foreach (var file in uris)
            {
                // Just in case the web server is using a self-signed cert.
                // Webclient won't validate the SSL/TLS cerficate if it's not trusted.
                var tempCallback = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

                var filepath = Path.Combine(AgentUpdateDirectory, file.FileName);

                try
                {
                    using (var client = new WebClient())
                    {
                        if (Settings.Proxy != null)
                        {
                            client.Proxy = Settings.Proxy;
                        }

                        var downloaded = false;
                        foreach (var uriSingle in file.Uris)
                        {
                            try
                            {
                                var splitted    = uriSingle.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
                                var splitted2   = splitted[1].Split(new[] { '/' });
                                var relayserver = splitted2[0];

                                if (downloaded)
                                {
                                    break;
                                }

                                Logger.Log("Attempting to download {1} from {0} with file size of {2}.", LogLevel.Info, relayserver, file.FileName, file.FileSize);

                                byte NetThrottle = byte.Parse(update.net_throttle);
                                if (NetThrottle > 0 || NetThrottle == null)
                                {
                                    Agent.RV.Utils.NetworkThrottle.DownloadThrottle(filepath, uriSingle, file.FileName, NetThrottle);
                                }
                                else
                                {
                                    client.DownloadFile(uriSingle, filepath);
                                }

                                if (File.Exists(filepath))
                                {
                                    var localFileHash = RvUtils.Md5HashFile(filepath).ToLower();
                                    Logger.Log("Download Complete,  {0}", LogLevel.Info, file.FileName);
                                    Logger.Log("Checking MD5 Hash...");
                                    Logger.Log("Incoming Hash: {0}", LogLevel.Info, file.Hash);
                                    Logger.Log("Local Hash: {0}", LogLevel.Info, localFileHash);
                                    downloaded = true;

                                    if (localFileHash != file.Hash.ToLower())
                                    {
                                        Logger.Log("Local file {0} Hash did not match remote's. Retrying with a different server.", LogLevel.Info, file.FileName);
                                        update.error   = "Local file Hash did not match remote. Bad file integrity. ";
                                        update.success = false.ToString().ToLower();
                                        downloaded     = false;
                                    }
                                }
                                else
                                {
                                    Logger.Log("File {0} did not download. Retrying with a different server.", LogLevel.Info, file.FileName);
                                    update.error   = "File did not download successfully, it was not found on disk. Please check download server.";
                                    update.success = false.ToString().ToLower();
                                    downloaded     = false;
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Log("File {0} failed to download correctly... Possible connection issue, Retrying with a different server.", LogLevel.Info, file.FileName);
                                update.error   = "File did not download correctly, Exception message: " + e.Message + ". Please check download server connectivity.";
                                update.success = false.ToString().ToLower();
                                downloaded     = false;
                            }
                        }

                        //Check if the file was successfully downloaded and return.
                        if (downloaded)
                        {
                            update.error   = String.Empty;
                            update.success = true.ToString().ToLower();
                        }
                    }
                }
                catch (Exception e)
                {
                    //Critical exception occurred.
                    update.error   = "Agent update did not download successfully, Exception occured, refer to log for details.";
                    update.success = false.ToString().ToLower();
                    Logger.Log("One or more Agent update Files were not downloaded successfully; {0}.",
                               LogLevel.Error, file.FileName);
                    Logger.LogException(e);
                    return(update);
                }

                ServicePointManager.ServerCertificateValidationCallback = tempCallback;
            }

            return(update);
        }
Beispiel #11
0
        private void InstallAgentUpdate(RvSofOperation operation)
        {
            var submittedInstall = false;
            var counter          = 30;
            var savedOperations  = Operations.LoadOpDirectory().Where(p => p.operation == OperationValue.InstallAgentUpdate).ToList();

            if (!savedOperations.Any())
            {
                Logger.Log("There are no operations remaining, Unable to update RV Agent: {0}", LogLevel.Warning, operation.Type);
                return;
            }

            Operations.SavedOpData updateDownloadResults = AgentUpdateManager.DownloadUpdate(savedOperations.First());

            if (String.IsNullOrEmpty(updateDownloadResults.error))
            {
                do
                {
                    switch (updateDownloadResults.operation_status)
                    {
                    case Operations.OperationStatus.Pending:
                        if (submittedInstall)
                        {
                            break;
                        }

                        Logger.Log("Agent Updater Application, preparing to upgrade RV Agent to the most recent version.");
                        var startInfo = new ProcessStartInfo();
                        var fileName  = String.Empty;

                        foreach (var item in updateDownloadResults.filedata_app_uris)
                        {
                            var splitted = item.file_name.Split(new[] { '.' });
                            if (splitted[0] == "UpdateInstaller")
                            {
                                fileName = item.file_name;
                            }
                        }

                        if (String.IsNullOrEmpty(fileName))
                        {
                            fileName = "UpdateInstaller.exe";
                        }

                        var filePath = Path.Combine(AgentUpdateManager.AgentUpdateDirectory, fileName);

                        startInfo.FileName               = filePath;
                        startInfo.Arguments              = updateDownloadResults.filedata_app_clioptions;
                        startInfo.UseShellExecute        = false;
                        startInfo.RedirectStandardOutput = false;

                        Operations.UpdateStatus(updateDownloadResults, Operations.OperationStatus.Processing);
                        Process.Start(startInfo);
                        submittedInstall = true;
                        break;
                    }
                    Thread.Sleep(5000);
                    counter--;
                } while (counter >= 0);
            }
            else
            if (!String.IsNullOrEmpty(updateDownloadResults.error))
            {
                InstallSendResults(updateDownloadResults, operation);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Process for Java
        /// Gets the required paramters from the json and sends if over, depending on use.
        /// Processes it depending on file type.
        /// </summary>
        /// <param name="javadata">SavedOpdata json type.</param>
        /// <returns>Returns results formatted --> InstallResult.</returns>
        private static InstallResult ProcessJava(Operations.SavedOpData javadata)
        {
            var appDirectory = Path.Combine(Settings.SupportedAppDirectory, javadata.filedata_app_id);
            var appFiles     = Directory.GetFiles(appDirectory);
            var file         = appFiles[0];

            var           extension = Path.GetExtension(file);
            InstallResult installResult;

            switch (extension)
            {
            case Extension.Exe:
                Logger.Log("Installing: {0}", LogLevel.Info, javadata.filedata_app_name);
                installResult = ExeInstall(file, javadata.filedata_app_clioptions);
                break;

            case Extension.Msi:
                Logger.Log("Installing: {0}", LogLevel.Info, javadata.filedata_app_name);
                installResult = MsiInstall(file, javadata.filedata_app_clioptions);
                break;

            case Extension.Msp:
                Logger.Log("Installing: {0}", LogLevel.Info, javadata.filedata_app_name);
                installResult = MspInstall(file, javadata.filedata_app_clioptions);
                break;

            default:
                throw new Exception(String.Format("{0} is not a supported file format.", extension));
            }


            //Process result
            switch (installResult.ExitCode)
            {
            case 1035:
            case 1305:
            case 1311:
            case 1324:
            case 1327:
            case 1335:
            case 1600:
            case 1601:
            case 1606:
            case 1624:
            case 1643:
            case 1722:
            case 1744:
            case 1788:
            case 2352:
            case 2753:
            case 2755:
                //Java version(s): 6.0, 7.0
                //Platform(s): Windows 8, Windows 7, Vista, Windows XP
                //Possibly registry corruption as per Java.
                //Cause: These errors are seen during installation process, which indicate that an installation did not complete.
                //http://www.java.com/en/download/help/error_installshield.xml
                installResult.ExitCodeMessage = "Java was not able to install due to some unknown error caused by a possible corrupted registry key. Refer to this Microsoft Fix it utility to attempt and repair, then retry. http://support.microsoft.com/mats/Program_Install_and_Uninstall/en";
                break;

            case 0:
                //OK
                installResult.ExitCodeMessage = String.Empty;
                break;

            case -1:
                //Fatal error
                installResult.ExitCodeMessage = "Installation failed due to a fatal error, check that Java Quick Starter application is not currently running. Its best to deploy Java updates when users are not logged in to avoid conflicts. ";
                break;

            case -2:
                //Installation failed due to an internal XML parsing error
                installResult.ExitCodeMessage = "Installation failed due to an internal XML parsing error. Recommended to reboot the system and attempt install when no users are logged in to the system. ";
                break;

            default:
                installResult.ExitCodeMessage = "Installation failed due to an unknown error.  Its best to deploy Java updates when users are not logged in to avoid conflicts, reboot the system and try running Microsoft Fix it tool to repair any corrupted registry entries http://support.microsoft.com/mats/Program_Install_and_Uninstall/en";
                break;
            }
            return(installResult);
        }
Beispiel #13
0
        public static Operations.SavedOpData InstallWindowsUpdate(Operations.SavedOpData update)
        {
            try
            {
                IUpdateSession session          = new UpdateSession();
                var            updatesToInstall = LoadUpdateCache(update, _allAvailableUpdatesList);
                var            installer        = (IUpdateInstaller2)session.CreateUpdateInstaller();

                //Check that there were no errors when processing LoadUpdateCache()
                if (updatesToInstall == null)
                {
                    update.error   = update.filedata_app_name + " failed to install, Internal Windows Update API Error occured when attempting to install this Update. Please refer to agent logs for details.";
                    update.success = false.ToString().ToLower();
                    return(update);
                }

                //Make sure we have some updates to install
                if (updatesToInstall.Count <= 0)
                {
                    update.success = false.ToString().ToLower();
                    update.error   = "There are no available updates to install, its possible that this update was manually installed and as a result, is not longer available.";
                    Logger.Log("The update was not available for install: {0}", LogLevel.Info, update.filedata_app_name + ", Debug: updatesToInstall is empty.");
                    return(update);
                }

                //Check if the update is already installed and remove it from the list of updates to install.
                for (int x = 0; x < updatesToInstall.Count; x++)
                {
                    if (updatesToInstall[x].IsInstalled)
                    {
                        updatesToInstall.RemoveAt(x);
                    }
                }

                //Final preparation for the installer, assigning the list of updates with all bundles in place to the Updates property.
                installer.ForceQuiet         = true;
                installer.AllowSourcePrompts = false;
                installer.Updates            = updatesToInstall;

                //Verify if we require a reboot before installing any updates.
                if (installer.RebootRequiredBeforeInstallation)
                {
                    update.success         = false.ToString().ToLower();
                    update.error           = "A System Reboot is required before attempting a Windows Update installation.";
                    update.reboot_required = true.ToString().ToLower();
                    Logger.Log("A System Reboot is required before attempting a Windows Update installation, sending back results.");
                    return(update);
                }

                //Iterate each update to accept the EULA (Mandatory)
                foreach (IUpdate updateNode in installer.Updates)
                {
                    updateNode.AcceptEula();
                }

                //Perform the installation and retrieve the results for the update.
                var installationRes = installer.Install();
                var installResult   = installationRes.GetUpdateResult(0);

                if (installResult.ResultCode == OperationResultCode.orcSucceeded)
                {
                    update.success         = true.ToString().ToLower();
                    update.reboot_required = installResult.RebootRequired.ToString();
                    Logger.Log("Update Installed Successfully: {0}", LogLevel.Info, update.filedata_app_name);
                    return(update);
                }
                return(ErrorResult(update, installationRes, "Update failed"));
            }
            catch (Exception e)
            {
                return(ErrorResultsException(update, e));
            }
        }
        private static void StartPatchProcess(StringCollection files, string newVersion)
        {
            const string tpaServiceName         = "TpaService";
            const string tpaMaintenance         = "TpaMaintenance";
            var          tpaServiceFilePath     = Path.Combine(Tools.RetrieveInstallationPath(), "Agent.RV.Service.exe");
            var          tpaMaintenanceFilePath = Path.Combine(Tools.RetrieveInstallationPath(), "Agent.RV.WatcherService.exe");

            try
            {
                Operations.SavedOpData operation = null;

                Operations.FindUpdateLocalContent();
                if (Data.SavedOperations != null && Data.SavedOperations.Count > 0)
                {
                    operation = (from n in Data.SavedOperations
                                 where n.operation == "install_agent_update"
                                 select n).First();

                    Data.Logger("Updating current operation status to Processing.");
                    Operations.UpdateOperation(operation, false, false, Operations.OperationStatus.Process);
                    Operations.SaveCopyOfJsonToBackup();
                    Data.Logger("Saved copy of operation.");
                }

                Data.Logger("Stopping Services");
                Tools.StopService(tpaMaintenance, 8000);
                Tools.StopService(tpaServiceName, 8000);
                Thread.Sleep(2000);
                Data.Logger("Uninstalling Services");
                Tools.UninstallService(tpaMaintenanceFilePath, 8000);
                Tools.UninstallService(tpaServiceFilePath, 8000);
                Thread.Sleep(2000);

                var pluginsDir  = Tools.GetPluginDirectory();
                var installPath = Tools.RetrieveInstallationPath();

                Data.Logger("Retriving Directory information: " + pluginsDir + " and " + installPath);
                Data.Logger(" ");
                Data.Logger("PATCHING CORE: ");
                foreach (var file in files)
                {
                    var stripped = file.Split(new[] { '\\' });
                    var filename = stripped[stripped.Length - 1];

                    switch (filename)
                    {
                    case "Agent.RV.dll":
                        Data.Logger(filename);
                        Tools.CopyFile(file, Path.Combine(pluginsDir, "Agent.RV.dll"));
                        Data.Logger("Copied to: " + pluginsDir);
                        break;

                    case "Agent.RA.dll":
                        Data.Logger(filename);
                        Tools.CopyFile(file, Path.Combine(pluginsDir, "Agent.RA.dll"));
                        Data.Logger("Copied to: " + pluginsDir);
                        break;

                    case "Agent.Monitoring.dll":
                        Data.Logger(filename);
                        Tools.CopyFile(file, Path.Combine(pluginsDir, "Agent.Monitoring.dll"));
                        Data.Logger("Copied to: " + pluginsDir);
                        break;

                    case "Agent.Core.dll":
                        Data.Logger(filename);
                        Tools.CopyFile(file, Path.Combine(installPath, "Agent.Core.dll"));
                        Data.Logger("Copied to: " + installPath);
                        break;

                    default:
                        continue;
                    }
                }
                Data.Logger("PATCHING COMPLETE!");
                Data.Logger(" ");
                Tools.SetNewVersionNumber(newVersion);
                RegistryTool.SetAgentVersionNumber(newVersion);
                Data.Logger("Changed revision to:" + newVersion);

                if (operation != null)
                {
                    //Passed, Copy back operation file and backed up configfile to send results to server.
                    var operationDir = Tools.GetOpDirectory();
                    Data.Logger("Retriving TopPatch Operations Folder.");
                    if (!Directory.Exists(operationDir))
                    {
                        Directory.CreateDirectory(operationDir);
                    }

                    Operations.UpdateOperation(operation, true, false, Operations.OperationStatus.Installed, Data.BackupJsonDataFilePath);
                    Data.Logger("Updated operation status to: Installed ");

                    var operationToSendBack = Path.Combine(operationDir, operation.filedata_app_id + ".data");
                    Data.Logger("Copying json data file back to Operations folder from: " + Data.BackupJsonDataFilePath);
                    Thread.Sleep(2000);
                    File.Copy(Data.BackupJsonDataFilePath, operationToSendBack, true);
                }

                Thread.Sleep(2000);
                Data.Logger("Installing Services...");
                Tools.InstallService(tpaMaintenanceFilePath, 8000);
                Tools.InstallService(tpaServiceFilePath, 8000);
                Thread.Sleep(2000);
                Data.Logger("Starting up Services...");
                Tools.StartService(tpaMaintenance, 8000);
                Tools.StartService(tpaServiceName, 8000);
                Data.Logger("Done.");
            }
            catch (Exception e)
            {
                Data.Logger("  ");
                Data.Logger("EXCEPTION ERROR: " + e.Message + "  -  " + e.StackTrace);
                Data.Logger("Installing Services...");
                Tools.InstallService(tpaMaintenanceFilePath, 8000);
                Tools.InstallService(tpaServiceFilePath, 8000);
                Thread.Sleep(2000);
                Data.Logger("Starting up Services...");
                Tools.StartService(tpaMaintenance, 8000);
                Tools.StartService(tpaServiceName, 8000);
            }
        }
        /// <summary>
        /// Gets an Operation send from the server for installing a CustomeApp.
        /// Determines what type of install it is(exe, msi, msp).
        /// And sends it to the appropriate method to prepair it for install.
        /// </summary>
        /// <param name="customApp">Json Operatoin from the server.</param>
        /// <returns>Returns updated Operation with the results.</returns>
        public static Operations.SavedOpData InstallCustomAppsOperation(Operations.SavedOpData customApp)
        {
            try
            {
                var appDirectory = Path.Combine(Settings.CustomAppDirectory, customApp.filedata_app_id);
                var appFiles     = Directory.GetFiles(appDirectory);
                var file         = appFiles[0];

                var extension = Path.GetExtension(file);

                InstallResult installResult;
                switch (extension.ToLower())
                {
                case Extension.Exe:
                    Logger.Log("Installing: {0}", LogLevel.Info, customApp.filedata_app_name);
                    installResult = ExeInstall(file, customApp.filedata_app_clioptions);
                    break;

                case Extension.Msi:
                    Logger.Log("Installing: {0}", LogLevel.Info, customApp.filedata_app_name);
                    installResult = MsiInstall(file, customApp.filedata_app_clioptions);
                    break;

                case Extension.Msp:
                    Logger.Log("Installing: {0}", LogLevel.Info, customApp.filedata_app_name);
                    installResult = MspInstall(file, customApp.filedata_app_clioptions);
                    break;

                default:
                    Logger.Log("{0} is not a supported file format.", LogLevel.Warning, extension);
                    throw new Exception(String.Format("{0} is not a supported file format.", extension));
                }


                if (!installResult.Success)
                {
                    //Custom App Failed to Install
                    customApp.success         = false.ToString().ToLower();
                    customApp.error           = String.Format("Failed to install {0}. {1}. Exit code: {2}.", customApp.filedata_app_name, installResult.ExitCodeMessage, installResult.ExitCode);
                    customApp.reboot_required = installResult.Restart.ToString().ToLower();

                    Logger.Log("Custom App Failed to Install: {0}", LogLevel.Warning, customApp.filedata_app_name + ", Error: " + customApp.error);
                    return(customApp);
                }

                //Custom App Installed OK
                customApp.success         = true.ToString().ToLower();
                customApp.error           = string.Empty;
                customApp.reboot_required = installResult.Restart.ToString().ToLower();

                Logger.Log("Custom App Installed Successfully: {0}", LogLevel.Info, customApp.filedata_app_name);
                return(customApp);
            }
            catch (Exception e)
            {
                //Error when attempting to install custom app.
                customApp.success = false.ToString().ToLower();
                customApp.error   = String.Format("Failed to install Custom App, Exception error: {0}", e.Message);

                Logger.Log("Custom App Failed to Install: {0}", LogLevel.Info, customApp.filedata_app_name + ", Error: " + customApp.error);
                return(customApp);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Process Flash.
        /// Gets the required parameters from the json and send it over, depending on use.
        /// Processit depeing on file type.
        /// </summary>
        /// <param name="flashdata">SavedOpdata json type.</param>
        /// <returns></returns>
        private static InstallResult ProcessFlash(Operations.SavedOpData flashdata)
        {
            var appDirectory = Path.Combine(Settings.SupportedAppDirectory, flashdata.filedata_app_id);
            var appFiles     = Directory.GetFiles(appDirectory);
            var file         = appFiles[0];

            var           extension = Path.GetExtension(file);
            InstallResult installResult;

            switch (extension)
            {
            case Extension.Exe:
                Logger.Log("Installing: {0}", LogLevel.Info, flashdata.filedata_app_name);
                installResult = ExeInstall(file, flashdata.filedata_app_clioptions);
                break;

            case Extension.Msi:
                Logger.Log("Installing: {0}", LogLevel.Info, flashdata.filedata_app_name);
                installResult = MsiInstall(file, flashdata.filedata_app_clioptions);
                break;

            case Extension.Msp:
                Logger.Log("Installing: {0}", LogLevel.Info, flashdata.filedata_app_name);
                installResult = MspInstall(file, flashdata.filedata_app_clioptions);
                break;

            default:
                throw new Exception(String.Format("{0} is not a supported file format.", extension));
            }


            //Process result
            switch (installResult.ExitCode)
            {
            case 0:
                //OK
                installResult.ExitCodeMessage = String.Empty;
                break;

            case 3:
                //Does not have admin permissions
                installResult.ExitCodeMessage = "Proper administrative permission was not found for this system.";
                break;

            case 4:
                //Unsupported OS
                installResult.ExitCodeMessage = "Unsupported Operating System for this version of Flash.";
                break;

            case 5:
                //Previously installed with elevated permissions
                installResult.ExitCodeMessage = "Previously installed with elevated permissions.";
                break;

            case 6:
                //Insufficient disk space
                installResult.ExitCodeMessage = "Insufficient disk space to proceed with installation.";
                break;

            case 7:
                //Trying to install older revision
                installResult.ExitCodeMessage = "Attempting to install older revision of this software.";
                break;

            case 8:
                //Browser is open
                installResult.ExitCodeMessage = "A web browser instance appears to be open, please close all web browser's and retry.";
                break;

            case 1003:
                //Invalid argument passed to installer
                installResult.ExitCodeMessage = "Invalid argument passed to installer, unable to proceed with installation.";
                break;

            case 1011:
                //Install already in progress
                installResult.ExitCodeMessage = "There appears to be an setup instance already running, please wait for the other application to finish and retry.";
                break;

            case 1013:
                //Downgrade attempt
                installResult.ExitCodeMessage = "The version currently install on the system is greater than the version selected for upgrade. Install did not complete. If you wish to install an older version, please use the downgrade tool provided by Adobe ";
                break;

            case 1012:
                //Does not have admin permissions on XP
                installResult.ExitCodeMessage = "Review permissions, it appears that this Windows XP system doesn't have the proper Administrative permissions to install this software.";
                break;

            case 1022:
                //Does not have admin permissions (Vista, Windows 7)
                installResult.ExitCodeMessage = "Review permissions, it appears that this Vista/Windows 7 system doesn't have the proper Administrative permissions to install this software.";
                break;

            case 1025:
                //Existing Player in use
                installResult.ExitCodeMessage = "Existing version of this software is currently in use and can not be removed. Please reboot the system and retry.";
                break;

            case 1032:
                //ActiveX registration failed
                installResult.ExitCodeMessage = "Possible corrupted system Registry; A damaged Windows system registry or incorrect registry permissions settings can prevent you from installing Flash Player. Refer to http://helpx.adobe.com/flash-player/kb/flash-player-windows-registry-permissions.html";
                break;

            default:
                installResult.ExitCodeMessage = "Flash update fails if any of the applications that use flash player are running while the installation is in progress. Please ensure that all web browsers are closed before installing flash player updates.";
                break;
            }
            return(installResult);
        }
Beispiel #17
0
        private void InstallWindowsUpdate(RvSofOperation operation)
        {
            var savedOperations = Operations.LoadOpDirectory().Where(p => p.operation == OperationValue.InstallWindowsUpdate).ToList();

            if (!savedOperations.Any())
            {
                Logger.Log("There are no operations remaining, Unable to install windows update: {0}", LogLevel.Warning, operation.Type);
                return;
            }

            WindowsUpdates.PopulateAvailableUpdatesList();
            WindowsUpdates.PopulateInstalledUpdatesList();

            foreach (var update in savedOperations)
            {
                //Check if update is already installed.
                ///////////////////////////////////////////////////////////////////////////////////////////
                if (WindowsUpdates.IsUpdateInstalled(update.filedata_app_name))
                {
                    Logger.Log("Update is already installed ({0}), sending back results.", LogLevel.Info, update.filedata_app_name);
                    Operations.UpdateStatus(update, Operations.OperationStatus.ResultsPending);
                    InstallSendResults(update, operation);
                    continue; //Move on to next update.
                }

                Logger.Log("Preparing to download");
                Operations.SavedOpData updateDownloadResults = Downloader.DownloadFile(update, Downloader.UpdateDirectories.OSUpdateDir);

                //If download fails, send back results to server and move to next package (if any).
                ////////////////////////////////////////////////////////////////////////////////////////////
                if (!String.IsNullOrEmpty(updateDownloadResults.error))
                {
                    Operations.UpdateStatus(updateDownloadResults, Operations.OperationStatus.ResultsPending);
                    InstallSendResults(updateDownloadResults, operation);
                    continue;
                }
                Logger.Log("Download completed for {0}", LogLevel.Info, update.filedata_app_name);

                Logger.Log("Installing {0} ", LogLevel.Info, update.filedata_app_name);
                Operations.SavedOpData updateInstallResults = WindowsUpdates.InstallWindowsUpdate(update);

                //If installation fails, send back results to server and move to next package (if any).
                /////////////////////////////////////////////////////////////////////////////////////////////
                if (!String.IsNullOrEmpty(updateInstallResults.error))
                {
                    Operations.UpdateStatus(updateDownloadResults, Operations.OperationStatus.ResultsPending);
                    InstallSendResults(updateInstallResults, operation);
                    continue;
                }
                Logger.Log("Installation of {0} was a success.", LogLevel.Info, update.filedata_app_name);
                Operations.UpdateStatus(updateDownloadResults, Operations.OperationStatus.ResultsPending);



                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                //Check scenerio for this update, react accordingly.
                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                if (Convert.ToBoolean(updateInstallResults.reboot_required) && Convert.ToBoolean(updateInstallResults.success) && (updateInstallResults.restart == "optional" || updateInstallResults.restart == "forced"))
                {
                    Operations.UpdateOperation(updateInstallResults, true, true, Operations.OperationStatus.Rebooting);
                    Operations.DeleteLocalUpdateBundleFolder(updateInstallResults);
                    Logger.Log("Rebooting system as per update requirement.");
                    RvUtils.RestartSystem();
                    Stop(); //System will restart to continue Windows update configuration, then ResumeOperations will start where we left off.
                }
                else if (Convert.ToBoolean(updateInstallResults.reboot_required) && !Convert.ToBoolean(updateInstallResults.success) && (updateInstallResults.restart == "optional" || updateInstallResults.restart == "forced"))
                {
                    Operations.UpdateOperation(updateInstallResults, false, true, Operations.OperationStatus.Rebooting);
                    Operations.DeleteLocalUpdateBundleFolder(updateInstallResults);
                    Logger.Log("Rebooting system as per update requirement.");
                    RvUtils.RestartSystem();
                    Stop(); //System will restart to continue Windows update configuration, then ResumeOperations will start where we left off.
                }
                else if (Convert.ToBoolean(updateInstallResults.reboot_required) && Convert.ToBoolean(updateInstallResults.success) && updateInstallResults.restart == "none")
                {
                    InstallSendResults(updateInstallResults, operation);
                }
                else if (Convert.ToBoolean(updateInstallResults.reboot_required) && !Convert.ToBoolean(updateInstallResults.success) && updateInstallResults.restart != "none")
                {
                    Operations.UpdateOperation(updateInstallResults, false, true, Operations.OperationStatus.Rebooting);
                    Operations.DeleteLocalUpdateBundleFolder(updateInstallResults);
                    RvUtils.RestartSystem();
                    Stop(); //System will restart to continue Windows update configuration, then ResumeOperations will start where we left off.
                }
                else if (Convert.ToBoolean(updateInstallResults.reboot_required) && updateInstallResults.restart != "none")
                {
                    var isInstalled = WindowsUpdates.IsUpdateInstalled(updateInstallResults.filedata_app_name);
                    Logger.Log("Rebooting system as per update requirement.");
                    Operations.UpdateOperation(updateInstallResults, isInstalled, true, Operations.OperationStatus.Rebooting);
                    RvUtils.RestartSystem();
                    Stop(); //System will restart to continue Windows update configuration, then ResumeOperations will start where we left off.
                }
                else
                {
                    InstallSendResults(updateInstallResults, operation);
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Process for Adobe Reader
        /// Gets the required parameters from json and sends it over depending on use.
        /// Processes it depending on file type.
        /// </summary>
        /// <param name="readerdata">SavedOpdata json type.</param>
        /// <returns>Returns results formatted --> InstallResult.</returns>
        private static InstallResult ProcessReader(Operations.SavedOpData readerdata)
        {
            var appDirectory = Path.Combine(Settings.SupportedAppDirectory, readerdata.filedata_app_id);
            var appFiles     = Directory.GetFiles(appDirectory);
            var file         = appFiles[0];

            var           extension = Path.GetExtension(file);
            InstallResult installResult;

            switch (extension)
            {
            case Extension.Exe:
                Logger.Log("Installing: {0}", LogLevel.Info, readerdata.filedata_app_name);
                installResult = ExeInstall(file, readerdata.filedata_app_clioptions);
                break;

            case Extension.Msi:
                Logger.Log("Installing: {0}", LogLevel.Info, readerdata.filedata_app_name);
                installResult = MsiInstall(file, readerdata.filedata_app_clioptions);
                break;

            case Extension.Msp:
                Logger.Log("Installing: {0}", LogLevel.Info, readerdata.filedata_app_name);
                installResult = MspInstall(file, readerdata.filedata_app_clioptions);
                break;

            default:
                throw new Exception(String.Format("{0} is not a supported file format.", extension));
            }


            //Process result
            switch (installResult.ExitCode)
            {
            case 0:
                //OK
                installResult.ExitCodeMessage = String.Empty;
                break;

            case 1067:
                //Update Failed
                installResult.ExitCodeMessage = "Update failed. The process terminated unexpectedly. Please try again, making sure Acrobat Reader is not running when the install/update is taking place.";
                break;

            case 1039:
                //Error attempting to open source file
                installResult.ExitCodeMessage = "Error attempting to open the source file C:\\Windows\\system32\\Macromed\\Flash\\FlashPlayerTrust\\AcrobatConnect.cfg, Refer to this Link for a possible solution directly from Adobe. http://kb2.adobe.com/cps/403/kb403915.html";
                break;

            case 1500:
                //Another install in progres
                installResult.ExitCodeMessage = "Another installation is already in progress. Complete that install before proceeding with this installation. Refer to http://kb2.adobe.com/cps/403/kb403945.html ";
                break;

            case 1601:
                //Out of disk space
                installResult.ExitCodeMessage = "Please ensure that you have enough disk space on your primary disk and update again.";
                break;

            case 1603:
                //fatal error
                installResult.ExitCodeMessage = "A fatal error occurred during installation. Shut down Microsoft Office and all web browsers. Then attempt to upgrade Acrobat or Reader. Refer to http://kb2.adobe.com/cps/408/kb408716.html   ";
                break;

            case 1606:
                //Coul not access network location
                installResult.ExitCodeMessage = "Try using the Microsoft Fix it wizard, available at support.microsoft.com/kb/886549. This wizard updates the Windows registry. Disclaimer: Adobe does not support third-party software and provides this information as a courtesy only. If you cannot resolve the problem after using the Fix it wizard, see the solutions in http://kb2.adobe.com/cps/402/kb402867.html ";
                break;

            case 1612:
            case 1635:
                //Source file for install is missing
                installResult.ExitCodeMessage = "The installation source for this product is not available. Verify that the source exists and that you can access it. This patch package could not be opened. Verify that the patch package exists and that you can access it. Or, contact the application vendor to verify that it is a valid Windows Installer patch package. Try using the Microsoft Fix it wizard, available at http://support.microsoft.com/kb/971187. The wizard updates the Windows registry so that you can usually uninstall previous versions of the program, or install or update the current version successfully. Disclaimer: Adobe does not support third-party software and provides this information as a courtesy only.";
                break;

            case 1618:
                //Another install in progess
                installResult.ExitCodeMessage = "Another installation is already in progress. Complete that installation before proceeding with this install. MSI is busy; Quit an installer or wait for the first one to finish and retry.";
                break;

            case 1704:
                //Suspended install of unkown name?
                installResult.ExitCodeMessage = "An installation of Unknown Name is currently suspended. Refer to http://kb2.adobe.com/cps/403/kb403945.html ";
                break;

            case 1714:
                //Older version cannot be removed
                installResult.ExitCodeMessage = "The older version cannot be removed. Try using the Microsoft Fix it wizard, available at http://support.microsoft.com/kb/971187. The wizard updates the Windows registry so that you can usually uninstall previous versions of the program, or install or update the current version successfully. Disclaimer: Adobe does not support third-party software and provides this information as a courtesy only. If you cannot uninstall, install, or update the program after using the Fix it wizard, see the solutions in http://kb2.adobe.com/cps/332/332773.html";
                break;

            default:
                installResult.ExitCodeMessage = "Installation failed due to an unknown error.  Its best to deploy Acrobat and Reader updates when Web browsers, and Adobe products are not being used.  Disclaimer: Adobe does not support third-party software and provides this information as a courtesy only. Reboot the system and try running Microsoft Fix it tool to repair any corrupted registry entries http://support.microsoft.com/mats/Program_Install_and_Uninstall/en";
                break;
            }
            return(installResult);
        }
Beispiel #19
0
        private void InstallSupportedApplication(RvSofOperation operation)
        {
            var registry         = new RegistryReader();
            var tempAppsToAdd    = new List <RVsofResult.AppsToAdd2>();
            var tempAppsToDelete = new List <RVsofResult.AppsToDelete2>();

            var savedOperations = Operations.LoadOpDirectory().Where(p => p.operation == OperationValue.InstallSupportedApp).ToList();

            if (!savedOperations.Any())
            {
                Logger.Log("There are no operations remaining, Unable to install supported app: {0}", LogLevel.Warning, operation.Type);
                return;
            }

            foreach (var update in savedOperations)
            {
                if (operation.ListOfInstalledApps.Count > 0)
                {
                    operation.ListOfInstalledApps.Clear();
                }
                if (operation.ListOfAppsAfterInstall.Count > 0)
                {
                    operation.ListOfAppsAfterInstall.Clear();
                }

                operation.ListOfInstalledApps = registry.GetRegistryInstalledApplicationNames();

                Logger.Log("Preparing to Install {0}", LogLevel.Info, update.filedata_app_name);

                Operations.SavedOpData updateDownloadResults = Downloader.DownloadFile(update, Downloader.UpdateDirectories.SupportedAppDir);
                Operations.UpdateStatus(updateDownloadResults, Operations.OperationStatus.Processing);

                //If download fails, send back results to server and move to next package (if any)
                if (!String.IsNullOrEmpty(updateDownloadResults.error))
                {
                    InstallSendResults(updateDownloadResults, operation);
                    continue;
                }
                Logger.Log("Download completed for {0}", LogLevel.Info, update.filedata_app_name);

                Operations.SavedOpData updateInstallResults = SupportedAppsManager.InstallSupportedAppsOperation(updateDownloadResults);

                //Get all installed application after installing..
                operation.ListOfAppsAfterInstall = registry.GetRegistryInstalledApplicationNames();

                //GET DATA FOR APPSTOADD/APPSTODELETE
                var appListToDelete = RegistryReader.GetAppsToDelete(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall);
                var appListToAdd    = RegistryReader.GetAppsToAdd(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall);

                //APPS TO DELETE
                #region Apps to Delete
                if (appListToDelete != null)
                {
                    var temp = registry.GetAllInstalledApplicationDetails();
                    foreach (var app in appListToDelete)
                    {
                        var appsToDelete = new RVsofResult.AppsToDelete2();
                        var version      = (from d in temp where d.Name == updateInstallResults.filedata_app_name select d.Version).FirstOrDefault();

                        appsToDelete.Name    = (String.IsNullOrEmpty(app)) ? String.Empty : app;
                        appsToDelete.Version = (String.IsNullOrEmpty(version)) ? String.Empty : version;

                        tempAppsToDelete.Add(appsToDelete);
                    }
                }
                #endregion

                //APPS TO ADD
                #region Apps to Add
                if (appListToAdd != null)
                {
                    var installedAppsDetails = registry.GetAllInstalledApplicationDetails();

                    foreach (var app in appListToAdd)
                    {
                        var temp        = new RVsofResult.AppsToAdd2();
                        var localApp    = app;
                        var version     = (from d in installedAppsDetails where d.Name == updateInstallResults.filedata_app_name select d.Version).FirstOrDefault(); //Default NULL
                        var vendor      = (from d in installedAppsDetails where d.Name == localApp select d.VendorName).FirstOrDefault();                            //Default NULL
                        var installDate = Tools.ConvertDateToEpoch((from d in installedAppsDetails where d.Name == localApp select d.Date).FirstOrDefault());        //Default 0.0D

                        temp.AppsToAdd.Name           = (String.IsNullOrEmpty(localApp)) ? String.Empty : localApp;
                        temp.AppsToAdd.Version        = (String.IsNullOrEmpty(version)) ? String.Empty : version;
                        temp.AppsToAdd.InstallDate    = (installDate.Equals(0.0D)) ? 0.0D : installDate;
                        temp.AppsToAdd.VendorName     = (String.IsNullOrEmpty(vendor)) ? String.Empty : vendor;
                        temp.AppsToAdd.RebootRequired = "no";
                        temp.AppsToAdd.ReleaseDate    = 0.0;
                        temp.AppsToAdd.Status         = "installed";
                        temp.AppsToAdd.Description    = String.Empty;
                        temp.AppsToAdd.SupportUrl     = String.Empty;
                        temp.AppsToAdd.VendorId       = String.Empty;
                        temp.AppsToAdd.VendorSeverity = String.Empty;
                        temp.AppsToAdd.KB             = String.Empty;

                        tempAppsToAdd.Add(temp);
                    }
                }
                #endregion

                InstallSendResults(updateInstallResults, operation, tempAppsToAdd, tempAppsToDelete);
            }
        }
        public static Operations.SavedOpData DownloadFile(Operations.SavedOpData update, UpdateDirectories updateTypePath)
        {
            var    uris = new List <DownloadUri>();
            string updateDirectory;

            switch (updateTypePath)
            {
            case UpdateDirectories.SupportedAppDir:
                updateDirectory = Settings.SupportedAppDirectory;
                break;

            case UpdateDirectories.CustomAppDir:
                updateDirectory = Settings.CustomAppDirectory;
                break;

            case UpdateDirectories.OSUpdateDir:
                updateDirectory = Settings.UpdateDirectory;
                break;

            default:
                updateDirectory = Settings.UpdateDirectory;
                break;
            }

            var savedir = Path.Combine(updateDirectory, update.filedata_app_id);

            foreach (var uriData in update.filedata_app_uris)
            {
                var tempDownloadUri = new DownloadUri();
                tempDownloadUri.FileName = uriData.file_name;
                tempDownloadUri.FileSize = uriData.file_size;
                tempDownloadUri.Hash     = uriData.file_hash;

                //add uri link from WSUS if its enabled
                if (WSUS.IsWSUSEnabled())
                {
                    var tempAvilApp = Agent.RV.WindowsApps.WindowsUpdates.GetAvailableUpdates();
                    foreach (var application in tempAvilApp)
                    {
                        if (application.Name == update.filedata_app_name)
                        {
                            foreach (var availUri in application.FileData)
                            {
                                tempDownloadUri.Uris.Add(availUri.Uri);
                            }
                        }
                    }
                }

                foreach (var uri in uriData.file_uris)
                {
                    tempDownloadUri.Uris.Add(uri);
                }

                uris.Add(tempDownloadUri);
            }

            if (Directory.Exists(savedir))
            {
                Directory.Delete(savedir, true);
            }
            Directory.CreateDirectory(savedir);

            foreach (var file in uris)
            {
                // Just in case the web server is using a self-signed cert.
                // Webclient won't validate the SSL/TLS cerficate if it's not trusted.
                var tempCallback = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

                var filepath = Path.Combine(savedir, file.FileName);

                try
                {
                    using (var client = new WebClient())
                    {
                        if (Settings.Proxy != null)
                        {
                            client.Proxy = Settings.Proxy;
                        }

                        var downloaded = false;
                        foreach (var uriSingle in file.Uris)
                        {
                            try
                            {
                                var splitted    = uriSingle.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
                                var splitted2   = splitted[1].Split(new[] { '/' });
                                var relayserver = splitted2[0];

                                if (downloaded)
                                {
                                    break;
                                }

                                Logger.Log("Attempting to download {1} from {0} with file size of {2}.", LogLevel.Info, relayserver, file.FileName, file.FileSize);
                                client.DownloadFile(uriSingle, filepath);

                                if (File.Exists(filepath))
                                {
                                    var localFileHashMd5    = RvUtils.Md5HashFile(filepath).ToLower();
                                    var localFileHashSha1   = RvUtils.Sha1HashFile(filepath).ToLower();
                                    var localFileHashSha256 = RvUtils.Sha256HashFile(filepath).ToLower();

                                    Logger.Log("Download Complete,  {0}", LogLevel.Info, file.FileName);
                                    Logger.Log("Checking Hashes...");
                                    Logger.Log("Incoming Hash: {0}", LogLevel.Info, file.Hash);
                                    Logger.Log("Local MD5 Hash: {0}", LogLevel.Info, localFileHashMd5);
                                    Logger.Log("Local SHA1 Hash: {0}", LogLevel.Info, localFileHashSha1);
                                    Logger.Log("Local SHA256 Hash: {0}", LogLevel.Info, localFileHashSha256);
                                    downloaded = true;

                                    if (localFileHashMd5 != file.Hash.ToLower() && localFileHashSha1 != file.Hash.ToLower() && localFileHashSha256 != file.Hash.ToLower())
                                    {
                                        Logger.Log("Local file {0} Hash did not match remote's. Retrying with a different server.", LogLevel.Info, file.FileName);
                                        update.error   = "Local file Hash did not match remote. Bad file integrity. ";
                                        update.success = false.ToString().ToLower();
                                        downloaded     = false;
                                    }
                                }
                                else
                                {
                                    Logger.Log("File {0} did not download. Retrying with a different server.", LogLevel.Info, file.FileName);
                                    update.error   = "File did not download successfully, it was not found on disk. Please check download server.";
                                    update.success = false.ToString().ToLower();
                                    downloaded     = false;
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Log("File {0} failed to download correctly... Possible connection issue, Retrying with a different server.", LogLevel.Info, file.FileName);
                                update.error   = "File did not download correctly, Exception message: " + e.Message + ". Please check download server connectivity.";
                                update.success = false.ToString().ToLower();
                                downloaded     = false;
                            }
                        }

                        //Check if the file was successfully downloaded and return.
                        if (downloaded)
                        {
                            update.error   = String.Empty;
                            update.success = true.ToString().ToLower();
                        }
                    }
                }
                catch (Exception e)
                {
                    //Critical exception occurred.
                    update.error   = "Application did not download, Exception occured, refer to log for details.";
                    update.success = false.ToString().ToLower();
                    Logger.Log("One or more Application Files were not downloaded successfully; {0}.",
                               LogLevel.Error, file.FileName);
                    Logger.LogException(e);
                    return(update);
                }

                ServicePointManager.ServerCertificateValidationCallback = tempCallback;
            }

            return(update);
        }
        private static void StartPatchProcess(StringCollection files, string newVersion)
        {
            const string tpaServiceName = "TpaService";
            const string tpaMaintenance = "TpaMaintenance";

            var rootDirectoryTp = Tools.RetrieveInstallationPath();

            Data.Logger("Retrieving Service install location: " + rootDirectoryTp);
            var tpaServiceFilePath     = Path.Combine(rootDirectoryTp, "Agent.RV.Service.exe");
            var tpaMaintenanceFilePath = Path.Combine(rootDirectoryTp, "Agent.RV.WatcherService.exe");

            try
            {
                var savedOperations = Operations.LoadOpDirectory().Where(p => p.operation == OperationType).ToList();
                var operation = new Operations.SavedOpData();

                if (savedOperations.Any())
                {
                    foreach (var item in savedOperations)
                    {
                      var data = (from d in item.filedata_app_uris
                                  where d.file_name.ToLower() == InstallerName
                                  select d).FirstOrDefault();
                      if (data != null)
                          operation = item;
                      else
                          operation = null;
                    }
                }
                else
                {
                    Data.Logger("There are no update operations in Agent Operations folder. Proceeding but server will not receive results.");
                }

                Data.Logger("Uninstalling Services");
                #region Uninstalling Services
                try
                {
                    Tools.UninstallService(tpaMaintenance);
                    Tools.UninstallService(tpaServiceName);
                    Thread.Sleep(5000);
                }
                catch
                {}

                for (int s = 0; s < 5; s++)
                {
                    if (!Tools.ServiceExists(tpaMaintenance))
                    {
                        Data.Logger("Service Removed.");
                        break;
                    }
                }

                for (int s = 0; s < 5; s++)
                {
                    if (!Tools.ServiceExists(tpaServiceName))
                    {
                        Data.Logger("Service Removed.");
                        break;
                    }
                    Thread.Sleep(1000);
                }
                Data.Logger("Service Uninstall, successfull.");
                #endregion

                var pluginsDir      = Tools.GetPluginDirectory();
                var opensshDir      = Path.Combine(Tools.GetBinDirectory(), "openssh");
                var vncDir          = Path.Combine(Tools.GetBinDirectory(), "vnc");
                var etcDir          = Tools.GetEtcDirectory();
                var installPath     = Tools.RetrieveInstallationPath();

                if (!Directory.Exists(opensshDir))
                    Directory.CreateDirectory(opensshDir);
                if (!Directory.Exists(vncDir))
                    Directory.CreateDirectory(vncDir);
                if (!Directory.Exists(etcDir))
                    Directory.CreateDirectory(etcDir);

                Data.Logger("PATCHING RV AGENT FILES: ");
                #region Patching Files
                foreach (var file in files)
                {
                    var stripped = file.Split(new[] {'\\'});
                    var filename = stripped[stripped.Length - 1];

                    try
                    {
                        switch (filename)
                        {
                            case "Agent.RV.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(pluginsDir, "Agent.RV.dll")))
                                    throw new Exception("Unable to copy Agent.RV.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + pluginsDir);
                                break;
                            case "Agent.RA.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(pluginsDir, "Agent.RA.dll")))
                                    throw new Exception("Unable to copy Agent.RA.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + pluginsDir);
                                break;
                            case "Agent.Monitoring.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(pluginsDir, "Agent.Monitoring.dll")))
                                    throw new Exception("Unable to copy Agent.Monitoring.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + pluginsDir);
                                break;
                            case "Agent.Core.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(installPath, "Agent.Core.dll")))
                                    throw new Exception("Unable to copy Agent.Core.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "RestSharp.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(installPath, "RestSharp.dll")))
                                    throw new Exception("Unable to copy RestSharp.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "Agent.RV.Service.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(installPath, "Agent.RV.Service.exe")))
                                    throw new Exception("Unable to copy Agent.RV.Service.exe, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "Agent.RV.WatcherService.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(installPath, "Agent.RV.WatcherService.exe")))
                                    throw new Exception(
                                        "Unable to copy Agent.RV.WatcherService.exe, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "NLog.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(installPath, "NLog.dll")))
                                    throw new Exception("Unable to copy NLog.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "Newtonsoft.Json.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(installPath, "Newtonsoft.Json.dll")))
                                    throw new Exception("Unable to copy Newtonsoft.Json.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "Microsoft.Deployment.Compression.dll":
                                Data.Logger(filename);
                                if (
                                    !Tools.CopyFile(file,
                                        Path.Combine(installPath, "Microsoft.Deployment.Compression.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "Microsoft.Deployment.Compression.Cab.dll":
                                Data.Logger(filename);
                                if (
                                    !Tools.CopyFile(file,
                                        Path.Combine(installPath, "Microsoft.Deployment.Compression.Cab.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + installPath);
                                break;
                            case "addUser.cmd":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "addUser.cmd")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "bash.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "bash.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "chmod.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "chmod.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "chown.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "chown.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygcrypt0.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygcrypt-0.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygcrypto0.9.7.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygcrypto-0.9.7.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygcrypto0.9.8.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygcrypto-0.9.8.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygedit0.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygedit-0.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cyggcc_s1.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cyggcc_s-1.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygiconv2.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygiconv-2.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygintl2.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygintl-2.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygintl3.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygintl-3.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygintl8.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygintl-8.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygminires.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygminires.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygncurses10.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygncurses-10.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygpath.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygpath.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygrunsrv.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygrunsrv.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygssp0.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygssp-0.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygwin1.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygwin1.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygwrap0.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygwrap-0.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "cygz.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "cygz.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "false.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "false.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "last.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "last.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "ls.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "ls.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "mkdir.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "mkdir.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "mkgroup.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "mkgroup.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "mkpasswd.c":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "mkpasswd.c")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "mkpasswd.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "mkpasswd.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "quietcmd.bat":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "quietcmd.bat")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "rm.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "rm.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "scp.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "scp.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sftp.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "sftp.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sh.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "sh.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "ssh.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "ssh.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sshadd.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "ssh-add.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sshagent.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "ssh-agent.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sshkeygen.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "ssh-keygen.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sshkeyscan.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "ssh-keyscan.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "switch.c":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "switch.c")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "switch.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(opensshDir, "switch.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + opensshDir);
                                break;
                            case "sas.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(vncDir, "sas.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + vncDir);
                                break;
                            case "screenhooks32.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(vncDir, "screenhooks32.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + vncDir);
                                break;
                            case "screenhooks64.dll":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(vncDir, "screenhooks64.dll")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + vncDir);
                                break;
                            case "tvnserver32.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(vncDir, "tvnserver32.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + vncDir);
                                break;
                            case "tvnserver64.exe":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(vncDir, "tvnserver64.exe")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + vncDir);
                                break;
                            case "tunnel":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(etcDir, "tunnel")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + etcDir);
                                break;
                            case "tunnel.pub":
                                Data.Logger(filename);
                                if (!Tools.CopyFile(file, Path.Combine(etcDir, "tunnel.pub")))
                                    throw new Exception(
                                        "Unable to copy Microsoft.Deployment.Compression.Cab.dll, access denied by the OS.");
                                Data.Logger("Copied to: " + etcDir);
                                break;
                            default:
                                continue;
                        }
                    }
                    catch
                    {
                        Data.Logger("Error " + filename);
                    }
                }

                Data.Logger("PATCHING COMPLETE!");
                Data.Logger(" ");
                #endregion

                Tools.SetNewVersionNumber(newVersion);
                RegistryTool.SetAgentVersionNumber(newVersion);
                Data.Logger("Changed revision to: "  + newVersion);

                Thread.Sleep(3000);

                if (operation != null)
                {
                    var operationDir = Tools.GetOpDirectory();
                    Data.Logger("Retriving TopPatch Operations Folder.");
                    if (!Directory.Exists(operationDir))
                        Directory.CreateDirectory(operationDir);

                    operation.success = true.ToString().ToLower();
                    operation.reboot_required = false.ToString().ToLower();
                    operation.operation_status = Operations.OperationStatus.ResultsPending;
                    Data.Logger("Updated operation status to: ResultsPending, All files were upgraded successfully. ");

                    Data.Logger("Deleting old agent operations... ");
                    int fileCount = Directory.GetFiles(operationDir, "*.*", SearchOption.AllDirectories).Length;
                    if (fileCount > 0)
                    {
                        Directory.Delete(operationDir,true);
                        Data.Logger("Deleted. ");
                        Directory.CreateDirectory(operationDir);
                    }

                    var tempRootOperationsFile = Path.Combine(Tools.GetOpDirectory(), operation.filedata_app_id + ".data");
                    Data.Logger("Saving operation information to:  " + tempRootOperationsFile);
                    Tools.WriteJsonFile(tempRootOperationsFile, operation);
                    Data.Logger("Operation Saved OK. ");

                    Data.Logger("Deleting old folders...");
                    Tools.DeleteOldFolders();
                    Data.Logger("Done.");
                }

                Data.Logger("Installing Services...");
                #region Installing Services
                ServiceTools.ServiceInstaller.InstallAndStart(tpaMaintenance, "TpaMaintenance", tpaMaintenanceFilePath);
                ServiceTools.ServiceInstaller.InstallAndStart(tpaServiceName, "TpaService", tpaServiceFilePath);

                for (int s = 0; s < 5; s++)
                {
                    if (Tools.ServiceExists(tpaMaintenance))
                    {
                        Data.Logger("TpaMaintenance Started OK.");
                        break;
                    }
                }
                Thread.Sleep(2000);
                for (int s = 0; s < 5; s++)
                {
                    if (Tools.ServiceExists(tpaServiceName))
                    {
                        Data.Logger("TpaService Started OK.");
                        break;
                    }
                }
                Thread.Sleep(1000);
                #endregion
                Data.Logger("Done.");
                Data.Logger("");
                Data.Logger("=========================================================");
                Data.Logger("");
                try
                {
                    Directory.Delete(AppDomain.CurrentDomain.BaseDirectory, true);
                }
                catch
                {
                }
            }
            catch (Exception e)
            {
                Data.Logger("  ");
                Data.Logger("EXCEPTION ERROR: " + e.Message + "  -  " + e.StackTrace);
                Data.Logger("Upate may have not completely successfully. Installing and Starting Services.");

                ServiceTools.ServiceInstaller.InstallAndStart(tpaMaintenance, "TpaMaintenance", tpaMaintenanceFilePath);
                ServiceTools.ServiceInstaller.InstallAndStart(tpaServiceName, "TpaService", tpaServiceFilePath);
            }
        }