public override void OnShown(bool skip) { base.OnShown(skip); treeView1.Nodes.Clear(); treeView1.Nodes.Add(necessary); treeView1.Nodes.Add(optional); var icp = PanelManager.GetPanel <InstallComponentPanel>(); installInfo = icp.InstallInfo; if (installInfo.PPD) { treeView1.Nodes[0].Nodes.Add(NotYet, ppd); } if (installInfo.IPAFont) { treeView1.Nodes[0].Nodes.Add(NotYet, ipaFont); } if (installInfo.BMSTOPPD) { treeView1.Nodes[1].Nodes.Add(NotYet, bmsToPpd); } if (installInfo.LAVFilters) { treeView1.Nodes[1].Nodes.Add(NotYet, lavFilters); } treeView1.ExpandAll(); }
public static void SetUpCalculator(InstallInfo info) { using (ClientContext ctx = ContextHelper.GetAppOnlyContext(info.HostUrl)) { Console.WriteLine("Connected to sharepoint"); string ListName = "Calculator"; List calculatorList = null; Console.WriteLine("Creating LIst if not exists"); if (!ctx.Web.ListExists(ListName)) { calculatorList = ctx.Web.CreateList(ListTemplateType.GenericList, ListName, false); } else { calculatorList = ctx.Web.GetListByTitle(ListName); } Console.WriteLine("Setting up fields and content types"); string pathToXML = AppDomain.CurrentDomain.BaseDirectory + @"\SPContent\Fields.xml"; ctx.Site.RootWeb.CreateFieldsFromXMLFile(pathToXML); ctx.Site.RootWeb.CreateContentTypeFromXMLFile(pathToXML); if (!calculatorList.ContentTypeExistsByName("Calculator")) { calculatorList.AddContentTypeToListById("0x01002B999C32793148858FE620188A8353AC", true, true); calculatorList.RemoveContentTypeByName("Item"); } SetUpRemoteEventReciver(ctx, info.AppUrlServiceEndPoint); } }
public ResponseBase RegisterInstallInfo(RequestBase request) { RegisterInstallInfoRequset registerRequest = (RegisterInstallInfoRequset)request; return(Service <RegisterInstallInfoResponse>(() => { RegisterInstallInfoResponse response = new RegisterInstallInfoResponse(); if (registerRequest == null) { throw new Exception("null input!"); } using (IUnitOfWork unitOfwork = RepositoryFactory.GetUnitOfWork()) { IInstallInfoRepository installRepository = (IInstallInfoRepository)RepositoryFactory .Get(typeof(IInstallInfoRepository), unitOfwork); InstallInfo register = new InstallInfo() { CNumber = registerRequest.CNumber, InstallMethod = registerRequest.InstallMethod, MaintancePeriod = registerRequest.MaintancePeriod, Principal = registerRequest.Principal, ProductId = registerRequest.ProductId, Site = registerRequest.Site, StartTime = registerRequest.StartTime }; register.Register(); installRepository.Add(register); unitOfwork.Commit(); response.IsSucess = true; response.InstallInfo = register.Map <InstallInfoView, InstallInfo>(); } return response; })); }
static void Main(string[] args) { Version = typeof(Program).Assembly.GetName().Version; string message = $"HA Climate Deskband {Version} Installer"; Console.Title = message; Console.WriteLine(message); InstallInfo info = new InstallInfo { FilesToCopy = new List <string> { DllName }, FilesToRegister = new List <string> { DllName }, TargetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "HAClimateDeskband") }; if (args.Length > 0 && args[0].ToLower() == "/uninstall") { RollBack(info); } else { Install(info); } Console.WriteLine("Press any key to close this window.."); Console.ReadKey(); }
static void Main(string[] args) { Console.Title = "Taskbar Monitor Installer"; InstallInfo info = new InstallInfo { FilesToCopy = new List <string> { "TaskbarMonitor.dll", "Newtonsoft.Json.dll" }, FilesToRegister = new List <string> { "TaskbarMonitor.dll" }, //TargetPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "TaskbarMonitor") TargetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "TaskbarMonitor") }; if (args.Length > 0 && args[0].ToLower() == "/uninstall") { RollBack(info); } else { Install(info); } // pause Console.WriteLine("Press any key to close this window..."); Console.ReadKey(); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void InstallApp([QueueTrigger(Constants.INSTALL_QUEUE_NAME)] string message, TextWriter log) { Console.WriteLine(message); InstallInfo info = JsonConvert.DeserializeObject <InstallInfo>(message); CalculatorHelper.SetUpCalculator(info); }
public void Update() { if (this.updatedManifest == null) { throw new UpdateException("You must call CheckForUpdate first to determine if an update is available."); } if (this.updateAvailable) { if (Directory.Exists(this.updateTempFolder)) { Directory.Delete(updateTempFolder, true); } Directory.CreateDirectory(this.updateTempFolder); InstallInfo info = new InstallInfo(); info.ZipFile = Path.Combine(updateTempFolder, "update.zip"); info.SetupFile = Path.Combine(updateTempFolder, "setup.exe"); info.Folder = updateTempFolder; Growl.CoreLibrary.WebClientEx downloader = new Growl.CoreLibrary.WebClientEx(); using (downloader) { downloader.Headers.Add("User-Agent", "Element.AutoUpdate.Updater"); downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged); downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted); downloader.DownloadFileAsync(new Uri(this.updatedManifest.InstallerLocation), info.ZipFile, info); } } }
public InstallUpdateExecutor(string filePath, VersionInfo installversion, InstallInfo installInfo, int index, Control control) : base(control) { FilePath = filePath; InstallInfo = installInfo; Index = index; InstallVersion = installversion; }
static void Install(InstallInfo info) { RestartExplorer restartExplorer = new RestartExplorer(); //restartExplorer.ReportProgress += Console.WriteLine; //restartExplorer.ReportPercentage += (percentage) => //Console.WriteLine($"Percentage: {percentage}"); // Create directory if (!Directory.Exists(info.TargetPath)) { Console.Write("Creating target directory... "); Directory.CreateDirectory(info.TargetPath); Console.WriteLine("OK."); // First copy files to program files folder foreach (var item in info.FilesToCopy) { var targetFilePath = Path.Combine(info.TargetPath, item); Console.Write(string.Format("Copying {0}... ", item)); File.Copy(item, targetFilePath, true); Console.WriteLine("OK."); } } else { //foreach (var item in info.FilesToRegister) //{ // var targetFilePath = System.IO.Path.Combine(info.TargetPath, item); // RegisterDLL(targetFilePath, false, true); // RegisterDLL(targetFilePath, true, true); // Console.WriteLine("OK."); //} restartExplorer.Execute(() => { // First copy files to program files folder foreach (var item in info.FilesToCopy) { var targetFilePath = Path.Combine(info.TargetPath, item); Console.Write($"Copying {item}... "); File.Copy(item, targetFilePath, true); Console.WriteLine("OK."); } }); } // Register assemblies //RegistrationServices regAsm = new RegistrationServices(); foreach (var item in info.FilesToRegister) { var targetFilePath = Path.Combine(info.TargetPath, item); Console.Write($"Registering {item}... "); RegisterDLL(targetFilePath, true, false); Console.WriteLine("OK."); } }
private static void CopyFiles(InstallInfo info) { foreach (string filename in info.FilesToCopy) { string targetFilePath = Path.Combine(info.TargetPath, filename); Console.Write($"Copying {filename}.. "); WriteEmbeddedResourceToFile(filename, targetFilePath); Console.WriteLine("OK."); } }
private void InitProductInfos() { try { mListProductInfos.Clear(); if (mInstallInfo == null) { mInstallInfo = new InstallInfo(); //从注册表获取已经安装的产品 for (int i = 0; i < mListProductGUIDs.Count; i++) { string strGUID = mListProductGUIDs[i]; string path; if (Environment.Is64BitOperatingSystem) { path = string.Format( @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{0}", strGUID); } else { path = string.Format(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{0}", strGUID); } try { RegistryKey rootKey = Registry.LocalMachine; RegistryKey umpKey = rootKey.OpenSubKey(path); if (umpKey != null) { InstallProduct product = new InstallProduct(); product.ProductGuid = strGUID; product.ProductName = umpKey.GetValue("DisplayName").ToString(); product.DisplayName = umpKey.GetValue("DisplayName").ToString(); product.InstallPath = umpKey.GetValue("InstallLocation").ToString(); product.Version = umpKey.GetValue("DisplayVersion").ToString(); mInstallInfo.ListProducts.Add(product); } } catch (Exception ex) { App.WriteLog("InitProductInfos", string.Format("Get product info fail.\t{0}", ex.Message)); } } } } catch (Exception ex) { ShowException(ex.Message); } }
public static bool IsModInstalledAndUpToDate() { if (File.Exists(InstallInfoPath)) { InstallInfo info = JsonConvert.DeserializeObject <InstallInfo>(File.ReadAllText(InstallInfoPath)); if (info.Version == CURRENT_VERSION && info.SourceFiles != null) { foreach ((string filePath, string md5) in info.SourceFiles) { if (!File.Exists(filePath) || InteropHelper.CalculateMD5(filePath) != md5) { return(false); } } return(true); } } return(false); }
static bool RollBack(InstallInfo info) { // Unregister assembly //RegistrationServices regAsm = new RegistrationServices(); foreach (var item in info.FilesToRegister) { var targetFilePath = Path.Combine(info.TargetPath, item); RegisterDLL(targetFilePath, false, true); RegisterDLL(targetFilePath, true, true); } // Delete files RestartExplorer restartExplorer = new RestartExplorer(); restartExplorer.Execute(() => { // First copy files to program files folder foreach (var item in info.FilesToCopy) { var targetFilePath = Path.Combine(info.TargetPath, item); if (File.Exists(targetFilePath)) { Console.Write($"Deleting {item}... "); File.Delete(targetFilePath); Console.WriteLine("OK."); } } }); if (Directory.Exists(info.TargetPath)) { Console.Write("Deleting target directory... "); Directory.Delete(info.TargetPath); Console.WriteLine("OK."); } return(true); }
private void LoadInstallInfo() { try { string strPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), ConstValue.VCT_COMPANY_SHORTNAME, ConstValue.UMP_PRODUCTER_SHORTNAME); if (!Directory.Exists(strPath)) { Directory.CreateDirectory(strPath); } string strFile = Path.Combine(strPath, InstallInfo.FILE_NAME); if (!File.Exists(strFile)) { App.WriteLog("LoadInstallInfo", string.Format("InstallInfo file not exist.\t{0}", strFile)); return; } OperationReturn optReturn = XMLHelper.DeserializeFile <InstallInfo>(strFile); if (!optReturn.Result) { App.WriteLog("LoadInstallInfo", string.Format("InstallInfo file invalid.\t{0}\t{1}", optReturn.Code, optReturn.Message)); return; } InstallInfo installInfo = optReturn.Data as InstallInfo; if (installInfo == null) { App.WriteLog("LoadInstallInfo", string.Format("InstallInfo is null")); return; } mInstallInfo = installInfo; } catch (Exception ex) { ShowException(ex.Message); } }
void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) { UpdateErrorEventArgs args = new UpdateErrorEventArgs(e.Error, "An error occurred while downloading the necessary update files. Please try again later."); this.OnUpdateError(args); } else if (e.Cancelled) { UpdateException ex = new UpdateException("Update was cancelled"); UpdateErrorEventArgs args = new UpdateErrorEventArgs(ex, "Update cancelled."); this.OnUpdateError(args); } else { this.OnDownloadComplete(EventArgs.Empty); // unzip files InstallInfo info = (InstallInfo)e.UserState; Installation.Unzipper.UnZipFiles(info.ZipFile, info.Folder, false); // start the update installer string setupFile = info.SetupFile; System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(setupFile); System.Diagnostics.Process.Start(si); // exit this application ApplicationMain.Program.ExitApp(); } Growl.CoreLibrary.WebClientEx downloader = (Growl.CoreLibrary.WebClientEx)sender; downloader.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged); downloader.DownloadFileCompleted -= new AsyncCompletedEventHandler(downloader_DownloadFileCompleted); downloader.Dispose(); downloader = null; }
public ActionResult DBInstall() { HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("IFDBSignIn"); if (cookie == null) { return(RedirectToAction("DBInstallLogin")); } else { InstallInfo info = new InstallInfo(); string appVersion = ConfigReader.GetAppSetting(); info.AppVersion = appVersion; try { DBSetup setup = new DBSetup(); DBObject db = setup.Initialize(); info.DBVersion = VersionReader.DatabaseVersion(db).ToString(); info.DBDrive = db.DbDrive.ToString(); info.DBCreateNew = false; info.DBServer = db.DbServer; info.DBUserID = db.UserId; info.DBPassWord = db.Password; info.DBName = db.DbName; } catch { info.DBVersion = "1.0"; info.DBDrive = "SqlServer2005"; info.DBCreateNew = false; info.DBServer = ""; info.DBUserID = ""; info.DBPassWord = ""; info.DBName = ""; } //Mongo string mongoStr = ""; try { mongoStr = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString; } catch {} if (mongoStr == "") { info.MongoSetting = false; } else { info.MongoSetting = true; //mongodb://10.210.160.98:20001/test //mongodb://libin1:[email protected]:27017/test //要区分@ 和没有@两种情况 string[] mongoArr = new string[] { }; if (mongoStr.Contains('@')) { mongoArr = mongoStr.Split(new char[] { '/', ':', '@' }); info.MongoUserName = mongoArr[3]; info.MongoPassword = mongoArr[4]; } else { mongoArr = mongoStr.Split(new char[] { '/', ':' }); info.MongoUserName = "******"; info.MongoPassword = "******"; } info.MongoServer = mongoArr[mongoArr.Length - 3] + ":" + mongoArr[mongoArr.Length - 2]; info.MongoDBName = mongoArr[mongoArr.Length - 1]; } Account configAccout = ConfigReader.GetAccount(); info.LoginUser = configAccout.UserName; info.LoginPassword = configAccout.PassWord; return(View(info)); } }
static bool RollBack(InstallInfo info) { // Unregister assembly foreach (string item in info.FilesToRegister) { string targetFilePath = Path.Combine(info.TargetPath, item); RegisterDLL(targetFilePath, false, true); RegisterDLL(targetFilePath, true, true); } // Delete files RestartExplorer restartExplorer = new RestartExplorer(); restartExplorer.Execute(() => { // Remove files foreach (string filename in info.FilesToCopy) { string targetFilePath = Path.Combine(info.TargetPath, filename); if (File.Exists(targetFilePath)) { Console.Write($"Deleting {filename}.. "); File.Delete(targetFilePath); Console.WriteLine("OK."); } } }); Console.Write($"Deleting {InstallerExecutableName}.. "); try { if (Win32Api.DeleteFile(Path.Combine(info.TargetPath, InstallerExecutableName))) { Console.WriteLine("OK."); } else { Win32Api.MoveFileEx(Path.Combine(info.TargetPath, InstallerExecutableName), null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT); Console.WriteLine("Scheduled for deletion after next reboot."); } } catch { Win32Api.MoveFileEx(Path.Combine(info.TargetPath, InstallerExecutableName), null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT); Console.WriteLine("Scheduled for deletion after next reboot."); } if (Directory.Exists(info.TargetPath)) { Console.Write("Deleting target directory.. "); try { Directory.Delete(info.TargetPath); Console.WriteLine("OK."); } catch { Win32Api.MoveFileEx(info.TargetPath, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT); Console.WriteLine("Scheduled for deletion after next reboot."); } } Console.Write("Removing uninstall info from registry.. "); DeleteUninstaller(); Console.WriteLine("OK."); return(true); }
static void Install(InstallInfo info) { Console.WriteLine($"Installing HA Climate Deskband {Version} on your computer, please wait."); RestartExplorer restartExplorer = new RestartExplorer(); try { // Create directory if (!Directory.Exists(info.TargetPath)) { Console.Write("Creating target directory.. "); Directory.CreateDirectory(info.TargetPath); Console.WriteLine("OK."); CopyFiles(info); // Copy the uninstaller too File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(info.TargetPath, InstallerExecutableName), true); } else { restartExplorer.Execute(() => { CopyFiles(info); // Copy the uninstaller too File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(info.TargetPath, InstallerExecutableName), true); }); } // Register assemblies foreach (string filename in info.FilesToRegister) { string targetFilePath = Path.Combine(info.TargetPath, filename); Console.Write($"Registering {filename}.. "); RegisterDLL(targetFilePath, true, false); Console.WriteLine("OK."); } Console.Write("Registering uninstaller.. "); FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(Path.Combine(info.TargetPath, DllName)); CreateUninstaller(Path.Combine(info.TargetPath, InstallerExecutableName), Version.Parse(fileVersionInfo.FileVersion)); Console.WriteLine("OK."); // Remove pending delete operations Console.Write("Cleaning up previous pending uninstalls.. "); if (CleanUpPendingDeleteOperations(info.TargetPath, out string errorMessage)) { Console.WriteLine("OK."); } else { Console.WriteLine($"ERROR: {errorMessage}"); } } catch (Exception ex) { Console.WriteLine("Error while installing.."); Console.WriteLine(ex.ToString()); } }
/// <summary> /// Performs software updates. /// </summary> /// <param name="status">software status, as retrieved via SoftwareStatus.query()</param> /// <param name="timeoutPerUpdate">maximum time in seconds to wait per update</param> /// <returns>Returns the number of updated application in case of success. /// Returns a negative value equal to -1 - number of updated applications, if an error occurred.</returns> public static int update(List <QueryEntry> status, uint timeoutPerUpdate = defaultTimeout) { if (null == status) { return(-1); } if (status.Count == 0) { logger.Info("No known software was found, so no update will be performed."); return(-1); } // set some reasonable timeout, if necessary if (timeoutPerUpdate <= minimumTimeout) { timeoutPerUpdate = defaultTimeout; } int updatedApplications = 0; foreach (var entry in status) { if (!entry.needsUpdate) { continue; } InstallInfo instInfo = null; switch (entry.type) { case ApplicationType.Bit32: instInfo = entry.software.info().install32Bit; break; case ApplicationType.Bit64: instInfo = entry.software.info().install64Bit; break; case ApplicationType.Unknown: logger.Warn("Warning: Unknown application type detected for " + entry.software.info().Name + "! Update will be skipped."); continue; default: logger.Warn("Warning: Unknown application type detected for " + entry.software.info().Name + "! Update will be aborted."); return(-1 - updatedApplications); } // If no verification method is provided, we do not even try to download the file. if (!instInfo.canBeVerified()) { logger.Error("Error: No checksum and no signature information for download of " + entry.software.info().Name + " is available!"); logger.Error("Since installing unverified software can" + " pose a security thread to your system, the update is cancelled."); return(-1 - updatedApplications); } // check for blocking processes if (utility.Processes.processesExist(entry.software.blockerProcesses(entry.detected))) { logger.Warn("Warning: At least one process was found that " + "blocks the update of " + entry.software.info().Name + "! Update will be omitted."); continue; } // download file if (string.IsNullOrWhiteSpace(instInfo.downloadUrl)) { logger.Error("Error: No known download URL for " + entry.software.info().Name + "!"); return(-1 - updatedApplications); } logger.Info("Downloading " + instInfo.downloadUrl + "..."); string downloadedFile = download(instInfo.downloadUrl); if (string.IsNullOrWhiteSpace(downloadedFile)) { logger.Error("Error: Could not download installer from " + instInfo.downloadUrl + "!"); return(-1 - updatedApplications); } // file verification bool verifiedChecksum = false; bool verifiedSignature = false; // checksum verification if (instInfo.hasChecksum()) { // calculate checksum logger.Info("Calculating checksum of " + downloadedFile + " ..."); string hash = utility.Checksum.calculate(downloadedFile, instInfo.algorithm); if (string.IsNullOrWhiteSpace(hash)) { logger.Error("Error: Could not calculate checksum of file " + downloadedFile + "!"); File.Delete(downloadedFile); return(-1 - updatedApplications); } if (!utility.Checksum.areEqual(hash, instInfo.checksum)) { logger.Error("Error: Checksum of file " + downloadedFile + " is " + hash + ", but expected checksum is " + instInfo.checksum + "!"); File.Delete(downloadedFile); return(-1 - updatedApplications); } logger.Info("Info: Checksum of " + downloadedFile + " is correct."); verifiedChecksum = true; } // if checksum // signature verification if (instInfo.hasVerifiableSignature()) { logger.Info("Verifying signature of " + downloadedFile + " ..."); if (!utility.Verificator.verifySignature(downloadedFile, instInfo.signature.publisher)) { logger.Error("Error: Signature of file " + downloadedFile + " is invalid or missing! The file may also have the wrong publisher."); File.Delete(downloadedFile); return(-1 - updatedApplications); } logger.Info("Info: Signature and publisher of " + downloadedFile + " are correct."); verifiedSignature = true; } // if signature if (!verifiedChecksum && !verifiedSignature) { logger.Error("Error: Downloaded file " + downloadedFile + " could not be verified to be authentic!"); logger.Error("Since installing unverified software can" + " pose a security thread to your system, the update is cancelled."); File.Delete(downloadedFile); return(-1 - updatedApplications); } // Check for blocking processes - again, because download can take // enough time to start some new processes. if (utility.Processes.processesExist(entry.software.blockerProcesses(entry.detected))) { logger.Warn("Warning: At least one process was found that " + "blocks the update of " + entry.software.info().Name + "! Update will be omitted."); File.Delete(downloadedFile); continue; } // start update process try { // preparational process needed? if (entry.software.needsPreUpdateProcess(entry.detected)) { var preProcs = entry.software.preUpdateProcess(entry.detected); if (null == preProcs) { logger.Error("Error: Pre-update process for " + entry.software.info().Name + " is null!"); return(-1 - updatedApplications); } foreach (System.Diagnostics.Process preProc in preProcs) { logger.Info("Info: Starting pre-update task for " + entry.software.info().Name + "..."); try { preProc.Start(); uint intervalCounter = 0; do { System.Threading.Thread.Sleep(1000); ++intervalCounter; if (preProc.HasExited) { logger.Info("Info: Pre-update process exited after " + intervalCounter.ToString() + " second(s) with code " + preProc.ExitCode.ToString() + "."); break; } // only wait up to timeoutPerUpdate seconds } while (intervalCounter <= timeoutPerUpdate); bool success = preProc.HasExited && (preProc.ExitCode == 0); // Kill it, if it is not done yet. if (!preProc.HasExited) { logger.Error("Error: Killing pre-update process, because timeout has been reached."); preProc.Kill(); return(-1 - updatedApplications); } if (!success) { if (!entry.software.allowPreUpdateProcessFailure(entry.detected, preProc)) { logger.Error("Error: Could not perform pre-update task for " + entry.software.info().Name + "."); return(-1 - updatedApplications); } else { logger.Warn("Info: Pre-update task for " + entry.software.info().Name + " failed, but that is allowed."); } } } // try-c catch (Exception ex) { logger.Error("Error: An exception occurred while running a pre-update tast for " + entry.software.info().Name + ": " + ex.Message); return(-1 - updatedApplications); } } // foreach } // if preparational process is needed var proc = instInfo.createInstallProccess(downloadedFile, entry.detected); if (null == proc) { // error while creating install process - should never happen logger.Error("Error: Could not create install process for " + entry.software.info().Name + "!"); return(-1 - updatedApplications); } try { logger.Info("Info: Starting update of " + entry.software.info().Name + "..."); logger.Debug("Command line: " + proc.StartInfo.FileName + " " + proc.StartInfo.Arguments); bool startedNew = proc.Start(); uint intervalCounter = 0; do { System.Threading.Thread.Sleep(1000); ++intervalCounter; if (proc.HasExited) { logger.Info("Info: Update process exited after " + intervalCounter.ToString() + " second(s) with code " + proc.ExitCode.ToString() + "."); break; } // only wait up to timeoutPerUpdate seconds } while (intervalCounter <= timeoutPerUpdate); // Update was successful, if process has exited already, // i.e. there was no timeout. // Additionally, the exit code must be zero. // However, for MSI processes the exit code 3010 means // the the update succeeded, but a reboot is required. bool success = proc.HasExited && ((proc.ExitCode == 0) || ((proc.ExitCode == InstallInfoMsi.successRebootRequired) && (instInfo is InstallInfoMsi))); // Kill it, if it is not done yet. if (!proc.HasExited) { logger.Warn("Warning: Killing update process, because timeout has been reached."); proc.Kill(); } if (success) { logger.Info("Info: Update of " + entry.software.info().Name + " was successful."); ++updatedApplications; if ((instInfo is InstallInfoMsi) && (proc.ExitCode == InstallInfoMsi.successRebootRequired)) { logger.Warn("Warning: A reboot is required to" + " finish the update of " + entry.software.info().Name + "."); } // if MSI installer requires reboot } // if success else { logger.Error("Error: Could not update " + entry.software.info().Name + "."); return(-1 - updatedApplications); } } // try-c catch (Exception ex) { logger.Error("Error: Exception occurred while updating " + entry.software.info().Name + ": " + ex.Message); return(-1 - updatedApplications); } // try-catch } // try-fin finally { try { File.Delete(downloadedFile); } catch (Exception ex) { logger.Error("Error: Could not delete installer file " + downloadedFile + " after update: " + ex.Message); } } // try-finally } // foreach return(updatedApplications); }
//---------------------------------------------------------------------------------------------------- public static InstallInfo GetInstallState() { var rtn = new InstallInfo() { InstallState = InstallInfo.InstallStates.NotSet }; rtn.AboutPageInfo = UI.PageParts.About.Backend.AboutPageLogic.Get(); string exc_Message = ""; try { rtn.ConnectionString = ConfigurationManager.ConnectionStrings["ASPdb_AppData"].ConnectionString; } catch (Exception exc) { ASPdb.Framework.Debug.RecordException(exc); } if (String.IsNullOrEmpty(rtn.ConnectionString)) { rtn.InstallState = InstallInfo.InstallStates.NoConnectionString; } else { try { rtn.InstallState = InstallInfo.InstallStates.Installed; var tableNames = new string[] { "ASPdb_Connections", "ASPdb_Permissions", "ASPdb_Tables", "ASPdb_UserGroups", "ASPdb_Users", "ASPdb_UsersToGroups", "ASPdb_Values" }; string sql = ""; foreach (string table in tableNames) { sql = String.Format("select top 1 * from [{0}].[{1}];", Config.SystemProperties.AppSchema, table); using (DbConnectionCommand command = UniversalADO.OpenConnectionCommand(rtn.ConnectionString, sql)) { using (DbReaderWrapper reader = command.ExecuteReaderWrapper()) { if (reader.Read()) { } } } } int usersCount = 0; sql = String.Format("select count(*) as [Count1] from [{0}].[ASPdb_Users] where Len([Password]) > 0", Config.SystemProperties.AppSchema); using (DbConnectionCommand command = UniversalADO.OpenConnectionCommand(rtn.ConnectionString, sql)) { using (DbReaderWrapper reader = command.ExecuteReaderWrapper()) { if (reader.Read()) { usersCount = reader.Get("Count1", 0); } } } if (usersCount < 1) { throw new Exception("Users table is empty."); } } catch (Exception exc) { ASPdb.Framework.Debug.RecordException(exc); string exc_L = exc.Message.ToLower(); if (exc_L.Contains("cannot open database") || exc_L.Contains("login failed")) { rtn.InstallState = InstallInfo.InstallStates.CannotConnectToDB; } else { rtn.InstallState = InstallInfo.InstallStates.DatabaseNotReady; } exc_Message = exc.Message; // +"<br />" + exc.StackTrace; //throw exc; } } var cache = Memory.AppCache.Get(); if (cache.AnyData.ContainsKey(AppKey_IsInstalled)) { cache.AnyData.Remove(AppKey_IsInstalled); } if (rtn.InstallState == InstallInfo.InstallStates.Installed) { cache.AnyData.Add(AppKey_IsInstalled, "true"); } rtn.ResponseMsg = rtn.InstallState.ToString(); switch (rtn.InstallState) { case InstallInfo.InstallStates.NoConnectionString: rtn.ResponseMsg = "Connection string not found."; break; case InstallInfo.InstallStates.CannotConnectToDB: rtn.ResponseMsg = "Could not connect to database. <hr />" + exc_Message; break; case InstallInfo.InstallStates.DatabaseNotReady: break; case InstallInfo.InstallStates.Installed: break; } ASPdb.Framework.Debug.WriteLine("002a..." + rtn.InstallState.ToString()); return(rtn); }
static void Install(InstallInfo info) { Console.WriteLine("Installing taskbar-monitor on your computer, please wait."); RestartExplorer restartExplorer = new RestartExplorer(); // Create directory if (!Directory.Exists(info.TargetPath)) { Console.Write("Creating target directory... "); Directory.CreateDirectory(info.TargetPath); Console.WriteLine("OK."); // First copy files to program files folder foreach (var file in info.FilesToCopy) { var item = file.Key; var targetFilePath = Path.Combine(info.TargetPath, item); Console.Write(string.Format("Copying {0}... ", item)); File.WriteAllBytes(targetFilePath, file.Value); //File.Copy(item, targetFilePath, true); Console.WriteLine("OK."); } // copy the uninstaller too File.Copy("TaskbarMonitorInstaller.exe", Path.Combine(info.TargetPath, "TaskbarMonitorInstaller.exe")); } else { restartExplorer.Execute(() => { // First copy files to program files folder foreach (var file in info.FilesToCopy) { var item = file.Key; var targetFilePath = Path.Combine(info.TargetPath, item); Console.Write($"Copying {item}... "); File.WriteAllBytes(targetFilePath, file.Value); //File.Copy(item, targetFilePath, true); Console.WriteLine("OK."); } // copy the uninstaller too File.Copy("TaskbarMonitorInstaller.exe", Path.Combine(info.TargetPath, "TaskbarMonitorInstaller.exe"), true); }); } // Register assemblies //RegistrationServices regAsm = new RegistrationServices(); foreach (var item in info.FilesToRegister) { var targetFilePath = Path.Combine(info.TargetPath, item); Console.Write($"Registering {item}... "); RegisterDLL(targetFilePath, true, false); Console.WriteLine("OK."); } Console.Write("Registering uninstaller... "); CreateUninstaller(Path.Combine(info.TargetPath, "TaskbarMonitorInstaller.exe")); Console.WriteLine("OK."); // remove pending delete operations { Console.Write("Cleaning up previous pending uninstalls... "); if (CleanUpPendingDeleteOperations(info.TargetPath, out string errorMessage)) { Console.WriteLine("OK."); } else { Console.WriteLine("ERROR: " + errorMessage); } } }
static bool RollBack(InstallInfo info) { // Unregister assembly //RegistrationServices regAsm = new RegistrationServices(); foreach (var item in info.FilesToRegister) { var targetFilePath = Path.Combine(info.TargetPath, item); RegisterDLL(targetFilePath, false, true); RegisterDLL(targetFilePath, true, true); } // Delete files RestartExplorer restartExplorer = new RestartExplorer(); restartExplorer.Execute(() => { // First copy files to program files folder foreach (var file in info.FilesToCopy) { var item = file.Key; var targetFilePath = Path.Combine(info.TargetPath, item); if (File.Exists(targetFilePath)) { Console.Write($"Deleting {item}... "); File.Delete(targetFilePath); Console.WriteLine("OK."); } } }); { var item = "TaskbarMonitorInstaller.exe"; Console.Write($"Deleting {item}... "); try { if (Win32Api.DeleteFile(Path.Combine(info.TargetPath, item))) { Console.WriteLine("OK."); } else { Win32Api.MoveFileEx(Path.Combine(info.TargetPath, item), null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT); Console.WriteLine("Scheduled for deletion after next reboot."); } } catch { Win32Api.MoveFileEx(Path.Combine(info.TargetPath, item), null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT); Console.WriteLine("Scheduled for deletion after next reboot."); } } if (Directory.Exists(info.TargetPath)) { Console.Write("Deleting target directory... "); try { Directory.Delete(info.TargetPath); Console.WriteLine("OK."); } catch { Win32Api.MoveFileEx(info.TargetPath, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT); Console.WriteLine("Scheduled for deletion after next reboot."); } } Console.Write("Removing uninstall info from registry... "); DeleteUninstaller(); Console.WriteLine("OK."); return(true); }
public void Update() { if (this.updatedManifest == null) throw new UpdateException("You must call CheckForUpdate first to determine if an update is available."); if (this.updateAvailable) { if (Directory.Exists(this.updateTempFolder)) Directory.Delete(updateTempFolder, true); Directory.CreateDirectory(this.updateTempFolder); InstallInfo info = new InstallInfo(); info.ZipFile = Path.Combine(updateTempFolder, "update.zip"); info.SetupFile = Path.Combine(updateTempFolder, "setup.exe"); info.Folder = updateTempFolder; Growl.CoreLibrary.WebClientEx downloader = new Growl.CoreLibrary.WebClientEx(); using (downloader) { downloader.Headers.Add("User-Agent", "Element.AutoUpdate.Updater"); downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged); downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted); downloader.DownloadFileAsync(new Uri(this.updatedManifest.InstallerLocation), info.ZipFile, info); } } }