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;
              }
        }
        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);
            }
        }
 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;
 }
 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;
 }
        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 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;
        }
        /// <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;
                }
        }
        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);
                                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;
        }
        /// <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;
        }
        /// <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;
        }
        /// <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;
        }
        /// <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;
            }
        }
示例#13
0
        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);

                                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 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;
        }