public InstallerDialog(Installer installer, InstallerUIConfiguration uiConfig) { InitializeComponent(); this.Installer = installer; this.UIConfig = uiConfig; }
public void Run(ITaskOutput output, NameValueCollection metaData) { string packageName = ResourceManager.Localize("DemoPackageName"); if (StaticSettings.IsStarterKit) { if (!string.IsNullOrEmpty(packageName) && File.Exists(AppDomain.CurrentDomain.BaseDirectory + Path.Combine(Settings.TempFolderPath, packageName))) { string res = JobContext.Confirm(ResourceManager.Localize("INSTALL_CALENDAR_DEMO_ITEMS")); if (res == "yes") { Installer installer = new Installer(); installer.InstallPackage(AppDomain.CurrentDomain.BaseDirectory + Path.Combine(Settings.TempFolderPath, packageName)); DemoItems.CreateEvents(); } } else { DemoItems.CreateDefaultCalendarsList(); } } else { if (!string.IsNullOrEmpty(packageName)) { File.Delete(Path.Combine(ApplicationContext.PackagePath, packageName)); } DemoItems.CreateDefaultCalendarsList(); } }
protected override void ProcessRecord() { string fileName = Path; PerformInstallAction( () => { if (IncludeProject.IsPresent) { Project.SaveProject = true; } if (!System.IO.Path.IsPathRooted(fileName)) { fileName = FullPackagePath(fileName); } IProcessingContext context = new SimpleProcessingContext(); IItemInstallerEvents events = new DefaultItemInstallerEvents(new BehaviourOptions(InstallMode, MergeMode)); context.AddAspect(events); IFileInstallerEvents events1 = new DefaultFileInstallerEvents(true); context.AddAspect(events1); var installer = new Installer(); installer.InstallPackage(fileName, context); }); }
public bool FileInGlobalInitializer(Installer.Definitions.GlobalInitializer initializer) { this.Initializers.Add(new KeyValuePair<XBinding, object>( this.Smalltalk.GetBinding(initializer.GlobalName.Value), this.CreateEvaluatableObject(initializer.ParseTree))); return true; }
public MainWindowViewModel(Installer installer) { this._installer = installer; this.Title = Resources.WindowTitle; this._installer .Subscribe(nameof(Installer.Status), () => this.ChangeStatus()) .AddTo(this); }
public bool FileInClass(Installer.Definitions.ClassDefinition definition) { XBinding binding = this.Smalltalk.GetOrCreateBinding(definition.Name.Value); if (binding.IsBound) throw new InvalidOperationException(String.Format("Global {0} already defined!", definition.Name.Value)); binding.Value = new XClass(definition, this.Smalltalk); binding.MakeConstant(); return true; }
static void Main(string[] args) { var dbMigrator = new DbMigrator(new Logger()); var logger = new Logger(); var installer = new Installer(logger); dbMigrator.Migrate(); installer.Install(); }
public bool FileInGlobal(Installer.Definitions.GlobalDefinition definition) { XBinding binding = this.Smalltalk.GetOrCreateBinding(definition.Name.Value); if (binding.IsBound) throw new InvalidOperationException(String.Format("Global {0} already defined!", definition.Name.Value)); binding.Value = null; // Bind it if (definition is Installer.Definitions.GlobalConstantDefinition) binding.MakeConstant(); else binding.MakeVariable(); return true; }
public MainWindowViewModel(IDispatcher dispatcher) { _dispatcher = dispatcher; _appVersion = Constants.ApplicationVersion; _installationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Constants.ApplicationTitle); _browseCommand = new DelegateCommand(DoBrowse); _installationCommand = new DelegateCommand(DoInstall, CanClickInstall); _launchCommand = new DelegateCommand(DoLaunch, CanLaunch); _installer = new Installer(); IsPreInstallation = true; }
protected void InstallSecurity(NameValueCollection metaData) { if (metaData != null) { var packageName = $"{metaData["PackageName"]}.zip"; var installer = new Installer(); var file = Installer.GetFilename(packageName); if (File.Exists(file)) { installer.InstallSecurity(PathUtils.MapPath(file)); } } }
public UpdateWindowViewModel(UiDispatcher dispatcher, string installationPath) { if (dispatcher == null) throw new ArgumentNullException("dispatcher"); if (installationPath == null) throw new ArgumentNullException("installationPath"); _dispatcher = dispatcher; _installationPath = installationPath; _installer = new Installer(); _installationTask = Task.Factory.StartNew(Installation, TaskCreationOptions.LongRunning); _installationTask.ContinueWith(OnInstallationFinished); }
public InstallerMainWindow(Installer installer) { Opacity = 0; Installer = installer; InitializeComponent(); OrganizationName.SetBinding(TextBlock.TextProperty, new Binding("Organization") { Source = Installer }); ProductName.SetBinding(TextBlock.TextProperty, new Binding("Product") { Source = Installer }); PackageIcon.SetBinding(Image.SourceProperty, new Binding("PackageIcon") { Source = Installer }); DescriptionText.SetBinding(TextBlock.TextProperty, new Binding("Description") { Source = Installer }); UpgradeToLatestVersion.SetBinding(ToggleButton.IsCheckedProperty, new Binding("AutomaticallyUpgrade") { Source = Installer }); ProductVersion.SetBinding(TextBlock.TextProperty, new Binding("ProductVersion") { Source = Installer }); InstallButton.SetBinding(UIElement.IsEnabledProperty, new Binding("ReadyToInstall") { Source = Installer }); InstallButton.SetBinding(FrameworkElement.ToolTipProperty , new Binding("InstallButtonText") { Source = Installer }); InstallText.SetBinding(TextBlock.TextProperty, new Binding("InstallButtonText") { Source = Installer }); RemoveButton.SetBinding(Button.VisibilityProperty, new Binding("RemoveButtonVisibility") { Source = Installer }); InstallationProgress.SetBinding(ProgressBar.ValueProperty, new Binding("Progress") { Source = Installer }); CancelButton.SetBinding(Button.VisibilityProperty, new Binding("CancelButtonVisibility") { Source = Installer }); try { VisibilityAnimation.SetAnimationType(RemoveButton, VisibilityAnimation.AnimationType.Fade); VisibilityAnimation.SetAnimationType(InstallButton, VisibilityAnimation.AnimationType.Fade); VisibilityAnimation.SetAnimationType(InstallationProgress, VisibilityAnimation.AnimationType.Fade); VisibilityAnimation.SetAnimationType(UpgradeToLatestVersion, VisibilityAnimation.AnimationType.Fade); VisibilityAnimation.SetAnimationType(CancelButton, VisibilityAnimation.AnimationType.Fade); } catch { } Loaded += (src, evnt) => { if (!(Opacity > 0) && Installer.ReadyToDisplay) { ((Storyboard)FindResource("showWindow")).Begin(); } }; Installer.Ready += (src, evnt) => Invoke(() => { if (!(Opacity > 0)) { ((Storyboard)FindResource("showWindow")).Begin(); } }); Installer.Finished += (src, evnt) => Invoke(() => { ((Storyboard)FindResource("hideWindow")).Completed += (ss, ee) => { Invoke(Close); }; ((Storyboard)FindResource("hideWindow")).Begin(); }); }
/// <summary> /// Creates a new toolbar. /// </summary> public override bool Do(Installer installer) { //TODO: save config before reading (to catch modifications made in current session). CuiFile cui = new CuiFile(CuiFile.MaxGetActiveCuiFile()); if (!cui.Read()) return false; if (!cui.ContainsToolbar(this.ToolbarName)) { cui.AddToolbar(this.ToolbarName, 5, 0); //TODO: Store size somewhere in action? if (!cui.Write()) return false; else cui.MaxLoadCuiFile(); } return true; }
public static int Run(Arguments args) { try { Log.InfoFormat("Starting silent installation of v{0} to {1}", Constants.ApplicationVersion, args.InstallationPath); var installer = new Installer(); installer.Run(args.InstallationPath); Log.InfoFormat("Installation finished"); return 0; } catch (Exception e) { Log.FatalFormat("Unable to complete installation: {0}", e); return -1; } }
/// <summary> /// Creates a separator on the toolbar. /// </summary> public override bool Do(Installer installer) { //TODO: save config before reading (to catch modifications made in current session). CuiFile cui = new CuiFile(CuiFile.MaxGetActiveCuiFile()); if (!cui.Read()) return false; CuiToolbar toolbar = cui.GetToolbar(this.ToolbarName); if (toolbar != null) { toolbar.AddSeparator(); if (cui.Write()) cui.MaxLoadCuiFile(); //TODO: Find way to not have to hard-reload for every action. (Post-install event?) else return false; } return true; }
public override void Execute(IEnumerable <string> args) { Installer.CleanAll(args.GetFiles("*.stuff")); }
protected void Button1_Click(object sender, EventArgs e) { Installer.ForumDetailsStarting(txtForumTitle.Text, txtDescription.Text); Response.Write("Details Saved<br/><a href=\"../Pages/beforehome.aspx\">Click Here to Move to Home</a>"); }
private void UpdateFileFacade(FileFacade file) { FileInfo fileInfo = null; try { fileInfo = new FileInfo(file.WixFile.Source); } catch (ArgumentException) { Messaging.Instance.OnMessage(WixErrors.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source)); return; } catch (PathTooLongException) { Messaging.Instance.OnMessage(WixErrors.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source)); return; } catch (NotSupportedException) { Messaging.Instance.OnMessage(WixErrors.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source)); return; } if (!fileInfo.Exists) { Messaging.Instance.OnMessage(WixErrors.CannotFindFile(file.File.SourceLineNumbers, file.File.File, file.File.FileName, file.WixFile.Source)); return; } using (FileStream fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (Int32.MaxValue < fileStream.Length) { throw new WixException(WixErrors.FileTooLarge(file.File.SourceLineNumbers, file.WixFile.Source)); } file.File.FileSize = Convert.ToInt32(fileStream.Length, CultureInfo.InvariantCulture); } string version = null; string language = null; try { Installer.GetFileVersion(fileInfo.FullName, out version, out language); } catch (Win32Exception e) { if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND { throw new WixException(WixErrors.FileNotFound(file.File.SourceLineNumbers, fileInfo.FullName)); } else { throw new WixException(WixErrors.Win32Exception(e.NativeErrorCode, e.Message)); } } // If there is no version, it is assumed there is no language because it won't matter in the versioning of the install. if (String.IsNullOrEmpty(version)) // unversioned files have their hashes added to the MsiFileHash table { if (!this.OverwriteHash) { // not overwriting hash, so don't do the rest of these options. } else if (null != file.File.Version) { // Search all of the file rows available to see if the specified version is actually a companion file. Yes, this looks // very expensive and you're probably thinking it would be better to create an index of some sort to do an O(1) look up. // That's a reasonable thought but companion file usage is usually pretty rare so we'd be doing something expensive (indexing // all the file rows) for a relatively uncommon situation. Let's not do that. // // Also, if we do not find a matching file identifier then the user provided a default version and is providing a version // for unversioned file. That's allowed but generally a dangerous thing to do so let's point that out to the user. if (!this.FileFacades.Any(r => file.File.Version.Equals(r.File.File, StringComparison.Ordinal))) { Messaging.Instance.OnMessage(WixWarnings.DefaultVersionUsedForUnversionedFile(file.File.SourceLineNumbers, file.File.Version, file.File.File)); } } else { if (null != file.File.Language) { Messaging.Instance.OnMessage(WixWarnings.DefaultLanguageUsedForUnversionedFile(file.File.SourceLineNumbers, file.File.Language, file.File.File)); } int[] hash; try { Installer.GetFileHash(fileInfo.FullName, 0, out hash); } catch (Win32Exception e) { if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND { throw new WixException(WixErrors.FileNotFound(file.File.SourceLineNumbers, fileInfo.FullName)); } else { throw new WixException(WixErrors.Win32Exception(e.NativeErrorCode, fileInfo.FullName, e.Message)); } } if (null == file.Hash) { Table msiFileHashTable = this.Output.EnsureTable(this.TableDefinitions["MsiFileHash"]); file.Hash = msiFileHashTable.CreateRow(file.File.SourceLineNumbers); } file.Hash[0] = file.File.File; file.Hash[1] = 0; file.Hash[2] = hash[0]; file.Hash[3] = hash[1]; file.Hash[4] = hash[2]; file.Hash[5] = hash[3]; } } else // update the file row with the version and language information. { // If no version was provided by the user, use the version from the file itself. // This is the most common case. if (String.IsNullOrEmpty(file.File.Version)) { file.File.Version = version; } else if (!this.FileFacades.Any(r => file.File.Version.Equals(r.File.File, StringComparison.Ordinal))) // this looks expensive, but see explanation below. { // The user provided a default version for the file row so we looked for a companion file (a file row with Id matching // the version value). We didn't find it so, we will override the default version they provided with the actual // version from the file itself. Now, I know it looks expensive to search through all the file rows trying to match // on the Id. However, the alternative is to build a big index of all file rows to do look ups. Since this case // where the file version is already present is rare (companion files are pretty uncommon), we'll do the more // CPU intensive search to save on the memory intensive index that wouldn't be used much. // // Also note this case can occur when the file is being updated using the WixBindUpdatedFiles extension mechanism. // That's typically even more rare than companion files so again, no index, just search. file.File.Version = version; } if (!String.IsNullOrEmpty(file.File.Language) && String.IsNullOrEmpty(language)) { Messaging.Instance.OnMessage(WixWarnings.DefaultLanguageUsedForVersionedFile(file.File.SourceLineNumbers, file.File.Language, file.File.File)); } else // override the default provided by the user (usually nothing) with the actual language from the file itself. { file.File.Language = language; } // Populate the binder variables for this file information if requested. if (null != this.VariableCache) { if (!String.IsNullOrEmpty(file.File.Version)) { string key = String.Format(CultureInfo.InvariantCulture, "fileversion.{0}", BindDatabaseCommand.Demodularize(this.Output.Type, this.ModularizationGuid, file.File.File)); this.VariableCache[key] = file.File.Version; } if (!String.IsNullOrEmpty(file.File.Language)) { string key = String.Format(CultureInfo.InvariantCulture, "filelanguage.{0}", BindDatabaseCommand.Demodularize(this.Output.Type, ModularizationGuid, file.File.File)); this.VariableCache[key] = file.File.Language; } } } // If this is a CLR assembly, load the assembly and get the assembly name information if (FileAssemblyType.DotNetAssembly == file.WixFile.AssemblyType) { bool targetNetfx1 = false; StringDictionary assemblyNameValues = new StringDictionary(); ClrInterop.IReferenceIdentity referenceIdentity = null; Guid referenceIdentityGuid = ClrInterop.ReferenceIdentityGuid; uint result = ClrInterop.GetAssemblyIdentityFromFile(fileInfo.FullName, ref referenceIdentityGuid, out referenceIdentity); if (0 == result && null != referenceIdentity) { string imageRuntimeVersion = referenceIdentity.GetAttribute(null, "ImageRuntimeVersion"); if (null != imageRuntimeVersion) { targetNetfx1 = imageRuntimeVersion.StartsWith("v1", StringComparison.OrdinalIgnoreCase); } string culture = referenceIdentity.GetAttribute(null, "Culture"); if (null != culture) { assemblyNameValues.Add("Culture", culture); } else { assemblyNameValues.Add("Culture", "neutral"); } string name = referenceIdentity.GetAttribute(null, "Name"); if (null != name) { assemblyNameValues.Add("Name", name); } string processorArchitecture = referenceIdentity.GetAttribute(null, "ProcessorArchitecture"); if (null != processorArchitecture) { assemblyNameValues.Add("ProcessorArchitecture", processorArchitecture); } string publicKeyToken = referenceIdentity.GetAttribute(null, "PublicKeyToken"); if (null != publicKeyToken) { bool publicKeyIsNeutral = (String.Equals(publicKeyToken, "neutral", StringComparison.OrdinalIgnoreCase)); // Managed code expects "null" instead of "neutral", and // this won't be installed to the GAC since it's not signed anyway. assemblyNameValues.Add("publicKeyToken", publicKeyIsNeutral ? "null" : publicKeyToken.ToUpperInvariant()); assemblyNameValues.Add("publicKeyTokenPreservedCase", publicKeyIsNeutral ? "null" : publicKeyToken); } else if (file.WixFile.AssemblyApplication == null) { throw new WixException(WixErrors.GacAssemblyNoStrongName(file.File.SourceLineNumbers, fileInfo.FullName, file.File.Component)); } string assemblyVersion = referenceIdentity.GetAttribute(null, "Version"); if (null != version) { assemblyNameValues.Add("Version", assemblyVersion); } } else { Messaging.Instance.OnMessage(WixErrors.InvalidAssemblyFile(file.File.SourceLineNumbers, fileInfo.FullName, String.Format(CultureInfo.InvariantCulture, "HRESULT: 0x{0:x8}", result))); return; } Table assemblyNameTable = this.Output.EnsureTable(this.TableDefinitions["MsiAssemblyName"]); if (assemblyNameValues.ContainsKey("name")) { this.SetMsiAssemblyName(assemblyNameTable, file, "name", assemblyNameValues["name"]); } if (!String.IsNullOrEmpty(version)) { this.SetMsiAssemblyName(assemblyNameTable, file, "fileVersion", version); } if (assemblyNameValues.ContainsKey("version")) { string assemblyVersion = assemblyNameValues["version"]; if (!targetNetfx1) { // There is a bug in v1 fusion that requires the assembly's "version" attribute // to be equal to or longer than the "fileVersion" in length when its present; // the workaround is to prepend zeroes to the last version number in the assembly // version. if (null != version && version.Length > assemblyVersion.Length) { string padding = new string('0', version.Length - assemblyVersion.Length); string[] assemblyVersionNumbers = assemblyVersion.Split('.'); if (assemblyVersionNumbers.Length > 0) { assemblyVersionNumbers[assemblyVersionNumbers.Length - 1] = String.Concat(padding, assemblyVersionNumbers[assemblyVersionNumbers.Length - 1]); assemblyVersion = String.Join(".", assemblyVersionNumbers); } } } this.SetMsiAssemblyName(assemblyNameTable, file, "version", assemblyVersion); } if (assemblyNameValues.ContainsKey("culture")) { this.SetMsiAssemblyName(assemblyNameTable, file, "culture", assemblyNameValues["culture"]); } if (assemblyNameValues.ContainsKey("publicKeyToken")) { this.SetMsiAssemblyName(assemblyNameTable, file, "publicKeyToken", assemblyNameValues["publicKeyToken"]); } if (!String.IsNullOrEmpty(file.WixFile.ProcessorArchitecture)) { this.SetMsiAssemblyName(assemblyNameTable, file, "processorArchitecture", file.WixFile.ProcessorArchitecture); } if (assemblyNameValues.ContainsKey("processorArchitecture")) { this.SetMsiAssemblyName(assemblyNameTable, file, "processorArchitecture", assemblyNameValues["processorArchitecture"]); } // add the assembly name to the information cache if (null != this.VariableCache) { string fileId = BindDatabaseCommand.Demodularize(this.Output.Type, this.ModularizationGuid, file.File.File); string key = String.Concat("assemblyfullname.", fileId); string assemblyName = String.Concat(assemblyNameValues["name"], ", version=", assemblyNameValues["version"], ", culture=", assemblyNameValues["culture"], ", publicKeyToken=", String.IsNullOrEmpty(assemblyNameValues["publicKeyToken"]) ? "null" : assemblyNameValues["publicKeyToken"]); if (assemblyNameValues.ContainsKey("processorArchitecture")) { assemblyName = String.Concat(assemblyName, ", processorArchitecture=", assemblyNameValues["processorArchitecture"]); } this.VariableCache[key] = assemblyName; // Add entries with the preserved case publicKeyToken string pcAssemblyNameKey = String.Concat("assemblyfullnamepreservedcase.", fileId); this.VariableCache[pcAssemblyNameKey] = (assemblyNameValues["publicKeyToken"] == assemblyNameValues["publicKeyTokenPreservedCase"]) ? assemblyName : assemblyName.Replace(assemblyNameValues["publicKeyToken"], assemblyNameValues["publicKeyTokenPreservedCase"]); string pcPublicKeyTokenKey = String.Concat("assemblypublickeytokenpreservedcase.", fileId); this.VariableCache[pcPublicKeyTokenKey] = assemblyNameValues["publicKeyTokenPreservedCase"]; } } else if (FileAssemblyType.Win32Assembly == file.WixFile.AssemblyType) { // TODO: Consider passing in the this.FileFacades as an indexed collection instead of searching through // all files like this. Even though this is a rare case it looks like we might be able to index the // file earlier. FileFacade fileManifest = this.FileFacades.SingleOrDefault(r => r.File.File.Equals(file.WixFile.AssemblyManifest, StringComparison.Ordinal)); if (null == fileManifest) { Messaging.Instance.OnMessage(WixErrors.MissingManifestForWin32Assembly(file.File.SourceLineNumbers, file.File.File, file.WixFile.AssemblyManifest)); } string win32Type = null; string win32Name = null; string win32Version = null; string win32ProcessorArchitecture = null; string win32PublicKeyToken = null; // loading the dom is expensive we want more performant APIs than the DOM // Navigator is cheaper than dom. Perhaps there is a cheaper API still. try { XPathDocument doc = new XPathDocument(fileManifest.WixFile.Source); XPathNavigator nav = doc.CreateNavigator(); nav.MoveToRoot(); // this assumes a particular schema for a win32 manifest and does not // provide error checking if the file does not conform to schema. // The fallback case here is that nothing is added to the MsiAssemblyName // table for an out of tolerance Win32 manifest. Perhaps warnings needed. if (nav.MoveToFirstChild()) { while (nav.NodeType != XPathNodeType.Element || nav.Name != "assembly") { nav.MoveToNext(); } if (nav.MoveToFirstChild()) { bool hasNextSibling = true; while (nav.NodeType != XPathNodeType.Element || nav.Name != "assemblyIdentity" && hasNextSibling) { hasNextSibling = nav.MoveToNext(); } if (!hasNextSibling) { Messaging.Instance.OnMessage(WixErrors.InvalidManifestContent(file.File.SourceLineNumbers, fileManifest.WixFile.Source)); return; } if (nav.MoveToAttribute("type", String.Empty)) { win32Type = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("name", String.Empty)) { win32Name = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("version", String.Empty)) { win32Version = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("processorArchitecture", String.Empty)) { win32ProcessorArchitecture = nav.Value; nav.MoveToParent(); } if (nav.MoveToAttribute("publicKeyToken", String.Empty)) { win32PublicKeyToken = nav.Value; nav.MoveToParent(); } } } } catch (FileNotFoundException fe) { Messaging.Instance.OnMessage(WixErrors.FileNotFound(new SourceLineNumber(fileManifest.WixFile.Source), fe.FileName, "AssemblyManifest")); } catch (XmlException xe) { Messaging.Instance.OnMessage(WixErrors.InvalidXml(new SourceLineNumber(fileManifest.WixFile.Source), "manifest", xe.Message)); } Table assemblyNameTable = this.Output.EnsureTable(this.TableDefinitions["MsiAssemblyName"]); if (!String.IsNullOrEmpty(win32Name)) { this.SetMsiAssemblyName(assemblyNameTable, file, "name", win32Name); } if (!String.IsNullOrEmpty(win32Version)) { this.SetMsiAssemblyName(assemblyNameTable, file, "version", win32Version); } if (!String.IsNullOrEmpty(win32Type)) { this.SetMsiAssemblyName(assemblyNameTable, file, "type", win32Type); } if (!String.IsNullOrEmpty(win32ProcessorArchitecture)) { this.SetMsiAssemblyName(assemblyNameTable, file, "processorArchitecture", win32ProcessorArchitecture); } if (!String.IsNullOrEmpty(win32PublicKeyToken)) { this.SetMsiAssemblyName(assemblyNameTable, file, "publicKeyToken", win32PublicKeyToken); } } }
public static void ParsePackage(string file, string installPath, Dictionary <string, PackageInfo> packages, List <string> invalidPackages) { var unzip = new ZipInputStream(new FileStream(file, FileMode.Open, FileAccess.Read)); var manifestReader = new StreamReader(unzip); try { ZipEntry entry = unzip.GetNextEntry(); while (entry != null) { entry.CheckZipEntry(); if (!entry.IsDirectory) { var fileName = entry.Name; string extension = Path.GetExtension(fileName); if (extension != null && (extension.Equals(".dnn", StringComparison.InvariantCultureIgnoreCase) || extension.Equals(".dnn5", StringComparison.InvariantCultureIgnoreCase))) { // Manifest var manifest = manifestReader.ReadToEnd(); var package = new PackageInfo { Manifest = manifest }; if (!string.IsNullOrEmpty(manifest)) { var doc = new XPathDocument(new StringReader(manifest)); XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); string packageType = string.Empty; if (rootNav.Name == "dotnetnuke") { packageType = XmlUtils.GetAttributeValue(rootNav, "type"); } else if (rootNav.Name.Equals("languagepack", StringComparison.InvariantCultureIgnoreCase)) { packageType = "LanguagePack"; } XPathNavigator nav = null; switch (packageType.ToLowerInvariant()) { case "package": nav = rootNav.SelectSingleNode("packages/package"); break; case "module": case "languagepack": case "skinobject": nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package"); break; } if (nav != null) { package.Name = XmlUtils.GetAttributeValue(nav, "name"); package.PackageType = XmlUtils.GetAttributeValue(nav, "type"); package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false); package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version")); package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName"); if (string.IsNullOrEmpty(package.FriendlyName)) { package.FriendlyName = package.Name; } package.Description = XmlUtils.GetNodeValue(nav, "description"); package.FileName = file.Replace(installPath + "\\", string.Empty); XPathNavigator foldernameNav; switch (package.PackageType) { case "Module": // In Dynamics moduels, a component:type=File can have a basePath pointing to the App_Conde folder. This is not a correct FolderName // To ensure that FolderName is DesktopModules... var folderNameValue = GetSpecificFolderName(nav, "components/component/files|components/component/resourceFiles", "basePath", "DesktopModules"); if (!string.IsNullOrEmpty(folderNameValue)) { package.FolderName = folderNameValue.Replace('\\', '/'); } break; case "Auth_System": foldernameNav = nav.SelectSingleNode("components/component/files"); if (foldernameNav != null) { package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/'); } break; case "Container": foldernameNav = nav.SelectSingleNode("components/component/containerFiles"); if (foldernameNav != null) { package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/'); } break; case "Skin": foldernameNav = nav.SelectSingleNode("components/component/skinFiles"); if (foldernameNav != null) { package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/'); } break; default: break; } XPathNavigator iconFileNav = nav.SelectSingleNode("iconFile"); if (package.FolderName != string.Empty && iconFileNav != null) { if ((iconFileNav.Value != string.Empty) && (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Auth_System", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase))) { if (iconFileNav.Value.StartsWith("~/")) { package.IconFile = iconFileNav.Value; } else if (iconFileNav.Value.StartsWith("DesktopModules", StringComparison.InvariantCultureIgnoreCase)) { package.IconFile = string.Format("~/{0}", iconFileNav.Value); } else { package.IconFile = (string.IsNullOrEmpty(package.FolderName) ? string.Empty : package.FolderName + "/") + iconFileNav.Value; package.IconFile = (!package.IconFile.StartsWith("~/")) ? "~/" + package.IconFile : package.IconFile; } } } // Parse the Dependencies foreach (XPathNavigator dependencyNav in nav.CreateNavigator().Select("dependencies/dependency")) { var dependency = DependencyFactory.GetDependency(dependencyNav); var packageDependecy = dependency as IManagedPackageDependency; if (packageDependecy != null) { package.Dependencies.Add(packageDependecy.PackageDependency); } } packages.Add(file, package); } } break; } } entry = unzip.GetNextEntry(); } } catch (Exception) { invalidPackages.Add(file); } finally { manifestReader.Dispose(); unzip.Close(); unzip.Dispose(); } }
/// <summary> /// Removes the file from the target directory. /// </summary> public override bool Undo(Installer installer) { //TODO: implement throw new NotImplementedException(); }
/// <summary> /// Reads and executes the maxscript file. /// </summary> public override bool Do(Installer installer) { using (StreamReader sr = new StreamReader(this.Source)) { String script = sr.ReadToEnd(); Boolean scriptResult = ManagedServices.MaxscriptSDK.ExecuteBooleanMaxscriptQuery(script); InstallerLog.WriteLine("RunMaxscript " + this.Source + " returned " + scriptResult.ToString()); return scriptResult; } }
/// <summary> /// Create a button on a toolbar. /// </summary> public override bool Do(Installer installer) { //TODO: save config before reading (to catch modifications made in current session). CuiFile cui = new CuiFile(CuiFile.MaxGetActiveCuiFile()); if (!cui.Read()) return false; CuiToolbar toolbar = cui.GetToolbar(this.ToolbarName); if (toolbar != null) { toolbar.AddButton(this.MacroName, this.MacroCategory, this.TooltipText, this.ButtonText); if (cui.Write()) cui.MaxLoadCuiFile(); else return false; } return true; }
static void Main(string[] args) { string version = "0.3-alpha1"; //Validate arguments passed to program Validator validator = new Validator(args); //Get the available packages if (validator.success) { PackageOverview overview = new PackageOverview(); if (overview.GenPackages(version)) { //What command are we running? switch (validator.opType) { case Validator.OP_TYPE.MAIN_HELP: Help.MainHelp(); break; case Validator.OP_TYPE.INSTALL: Installer.InstallPackages(validator, overview); break; case Validator.OP_TYPE.INSTALL_HELP: Help.InstallHelp(); break; case Validator.OP_TYPE.REMOVE: Remover.RemovePackages(validator, overview); break; case Validator.OP_TYPE.REMOVE_HELP: Help.RemoveHelp(); break; case Validator.OP_TYPE.UPDATE: Updater.UpdatePackages(validator, overview); break; case Validator.OP_TYPE.UPDATE_HELP: Help.UpdateHelp(); break; case Validator.OP_TYPE.SERVER: Server.CreateServer(validator); break; case Validator.OP_TYPE.SERVER_HELP: Help.ServerHelp(); break; case Validator.OP_TYPE.CREATEPACKAGE: Packager.PackagePlugin(); break; case Validator.OP_TYPE.CREATEPACKAGE_HELP: Help.CreatePackageHelp(); break; default: Console.WriteLine("Unknown error".Pastel("ff0000")); break; } } } //In case we need to display help else { switch (validator.opType) { case Validator.OP_TYPE.MAIN_HELP: Help.MainHelp(); break; case Validator.OP_TYPE.INSTALL_HELP: Help.InstallHelp(); break; case Validator.OP_TYPE.REMOVE_HELP: Help.RemoveHelp(); break; case Validator.OP_TYPE.UPDATE_HELP: Help.UpdateHelp(); break; case Validator.OP_TYPE.SERVER_HELP: Help.ServerHelp(); break; case Validator.OP_TYPE.CREATEPACKAGE_HELP: Help.CreatePackageHelp(); break; default: Console.WriteLine("Unknown error".Pastel("ff0000")); break; } } #if (DEBUG) Console.ReadKey(); #endif }
/// <summary> /// Removes the created toolbar. /// </summary> public override bool Undo(Installer installer) { CuiFile cui = new CuiFile(CuiFile.MaxGetActiveCuiFile()); if (!cui.Read()) return false; if (cui.RemoveToolbar(this.ToolbarName)) { if (!cui.Write()) return false; else cui.MaxLoadCuiFile(); } return true; }
/// <summary> /// Validate a database. /// </summary> /// <param name="databaseFile">The database to validate.</param> /// <returns>true if validation succeeded; false otherwise.</returns> public bool Validate(string databaseFile) { Dictionary <string, string> indexedICEs = new Dictionary <string, string>(); Dictionary <string, string> indexedSuppressedICEs = new Dictionary <string, string>(); int previousUILevel = (int)InstallUILevels.Basic; IntPtr previousHwnd = IntPtr.Zero; InstallUIHandler previousUIHandler = null; if (null == databaseFile) { throw new ArgumentNullException("databaseFile"); } // initialize the validator extension this.extension.DatabaseFile = databaseFile; this.extension.Output = this.output; this.extension.InitializeValidator(); // if we don't have the temporary files object yet, get one if (null == this.tempFiles) { this.tempFiles = new TempFileCollection(); } Directory.CreateDirectory(this.TempFilesLocation); // ensure the base path is there // index the ICEs if (null != this.ices) { foreach (string ice in this.ices) { indexedICEs[ice] = null; } } // index the suppressed ICEs if (null != this.suppressedICEs) { foreach (string suppressedICE in this.suppressedICEs) { indexedSuppressedICEs[suppressedICE] = null; } } // copy the database to a temporary location so it can be manipulated string tempDatabaseFile = Path.Combine(this.TempFilesLocation, Path.GetFileName(databaseFile)); File.Copy(databaseFile, tempDatabaseFile); // remove the read-only property from the temporary database FileAttributes attributes = File.GetAttributes(tempDatabaseFile); File.SetAttributes(tempDatabaseFile, attributes & ~FileAttributes.ReadOnly); Mutex mutex = new Mutex(false, "WixValidator"); try { if (!mutex.WaitOne(0, false)) { this.OnMessage(WixVerboses.ValidationSerialized()); mutex.WaitOne(); } using (Database database = new Database(tempDatabaseFile, OpenDatabase.Direct)) { bool propertyTableExists = database.TableExists("Property"); string productCode = null; // remove the product code from the database before opening a session to prevent opening an installed product if (propertyTableExists) { using (View view = database.OpenExecuteView("SELECT `Value` FROM `Property` WHERE Property = 'ProductCode'")) { using (Record record = view.Fetch()) { if (null != record) { productCode = record.GetString(1); using (View dropProductCodeView = database.OpenExecuteView("DELETE FROM `Property` WHERE `Property` = 'ProductCode'")) { } } } } } // merge in the cube databases foreach (string cubeFile in this.cubeFiles) { try { using (Database cubeDatabase = new Database(cubeFile, OpenDatabase.ReadOnly)) { try { database.Merge(cubeDatabase, "MergeConflicts"); } catch { // ignore merge errors since they are expected in the _Validation table } } } catch (Win32Exception e) { if (0x6E == e.NativeErrorCode) // ERROR_OPEN_FAILED { throw new WixException(WixErrors.CubeFileNotFound(cubeFile)); } throw; } } // commit the database before proceeding to ensure the streams don't get confused database.Commit(); // the property table may have been added to the database // from a cub database without the proper validation rows if (!propertyTableExists) { using (View view = database.OpenExecuteView("DROP table `Property`")) { } } // get all the action names for ICEs which have not been suppressed List <string> actions = new List <string>(); using (View view = database.OpenExecuteView("SELECT `Action` FROM `_ICESequence` ORDER BY `Sequence`")) { while (true) { using (Record record = view.Fetch()) { if (null == record) { break; } string action = record.GetString(1); if (!indexedSuppressedICEs.ContainsKey(action)) { actions.Add(action); } } } } if (0 != indexedICEs.Count) { // Walk backwards and remove those that arent in the list for (int i = actions.Count - 1; 0 <= i; i--) { if (!indexedICEs.ContainsKey(actions[i])) { actions.RemoveAt(i); } } } // disable the internal UI handler and set an external UI handler previousUILevel = Installer.SetInternalUI((int)InstallUILevels.None, ref previousHwnd); previousUIHandler = Installer.SetExternalUI(this.validationUIHandler, (int)InstallLogModes.Error | (int)InstallLogModes.Warning | (int)InstallLogModes.User, IntPtr.Zero); // create a session for running the ICEs this.validationSessionComplete = false; using (Session session = new Session(database)) { // add the product code back into the database if (null != productCode) { // some CUBs erroneously have a ProductCode property, so delete it if we just picked one up using (View dropProductCodeView = database.OpenExecuteView("DELETE FROM `Property` WHERE `Property` = 'ProductCode'")) { } using (View view = database.OpenExecuteView(String.Format(CultureInfo.InvariantCulture, "INSERT INTO `Property` (`Property`, `Value`) VALUES ('ProductCode', '{0}')", productCode))) { } } foreach (string action in actions) { this.actionName = action; try { session.DoAction(action); } catch (Win32Exception e) { if (!this.encounteredError) { throw e; } else { this.encounteredError = false; } } this.actionName = null; } // Mark the validation session complete so we ignore any messages that MSI may fire // during session clean-up. this.validationSessionComplete = true; } } } catch (Win32Exception e) { // avoid displaying errors twice since one may have already occurred in the UI handler if (!this.encounteredError) { if (0x6E == e.NativeErrorCode) // ERROR_OPEN_FAILED { // databaseFile is not passed since during light // this would be the temporary copy and there would be // no final output since the error occured; during smoke // they should know the path passed into smoke this.OnMessage(WixErrors.ValidationFailedToOpenDatabase()); } else if (0x64D == e.NativeErrorCode) { this.OnMessage(WixErrors.ValidationFailedDueToLowMsiEngine()); } else if (0x654 == e.NativeErrorCode) { this.OnMessage(WixErrors.ValidationFailedDueToInvalidPackage()); } else if (0x658 == e.NativeErrorCode) { this.OnMessage(WixErrors.ValidationFailedDueToMultilanguageMergeModule()); } else if (0x659 == e.NativeErrorCode) { this.OnMessage(WixWarnings.ValidationFailedDueToSystemPolicy()); } else { string msgTemp = e.Message; if (null != this.actionName) { msgTemp = String.Concat("Action - '", this.actionName, "' ", e.Message); } this.OnMessage(WixErrors.Win32Exception(e.NativeErrorCode, msgTemp)); } } } finally { Installer.SetExternalUI(previousUIHandler, 0, IntPtr.Zero); Installer.SetInternalUI(previousUILevel, ref previousHwnd); this.validationSessionComplete = false; // no validation session at this point, so reset the completion flag. mutex.ReleaseMutex(); this.cubeFiles.Clear(); this.extension.FinalizeValidator(); } return(!this.encounteredError); }
/// <summary> /// Merges ICE cubes into the database <paramref name="item"/> and executes selected ICEs. /// </summary> /// <param name="item">The database to validate.</param> protected override void ProcessItem(PSObject item) { // Get the item path and set the current context. string path = item.GetPropertyValue <string>("PSPath"); path = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); this.CurrentPath = path; // Copy the database to a writable location and open. string copy = this.Copy(path); using (var db = new InstallPackage(copy, DatabaseOpenMode.Direct)) { // Apply any patches or transforms before otherwise modifying. this.ApplyTransforms(db); // Copy the ProductCode and drop the Property table to avoid opening an installed product. bool hasProperty = db.IsTablePersistent("Property"); string productCode = null; if (hasProperty) { productCode = db.ExecutePropertyQuery("ProductCode"); } // Merge the ICE cubes and fix up the database if needed. this.MergeCubes(db); if (!hasProperty) { db.Execute("DROP TABLE `Property`"); } var included = new List <WildcardPattern>(); if (null != this.Include) { Array.ForEach(this.Include, pattern => included.Add(new WildcardPattern(pattern))); } var excluded = new List <WildcardPattern>(); if (null != this.Exclude) { Array.ForEach(this.Exclude, pattern => excluded.Add(new WildcardPattern(pattern))); } // Get all the ICE actions in the database that are not excluded. var actions = new List <string>(); foreach (var action in db.ExecuteStringQuery("SELECT `Action` FROM `_ICESequence` ORDER BY `Sequence`")) { if (!action.Match(excluded)) { actions.Add(action); } } // Remove any actions not explicitly included. if (0 < included.Count) { for (int i = actions.Count - 1; 0 <= i; --i) { if (!actions[i].Match(included)) { actions.RemoveAt(i); } } } // Open a session with the database. using (var session = Installer.OpenPackage(db, false)) { // Put the original ProductCode back. if (!string.IsNullOrEmpty(productCode)) { db.Execute("DELETE FROM `Property` WHERE `Property` = 'ProductCode'"); db.Execute("INSERT INTO `Property` (`Property`, `Value`) VALUES ('ProductCode', '{0}')", productCode); } // Now execute all the remaining actions in order. foreach (string action in actions) { try { session.DoAction(action); this.Flush(); } catch (InstallerException ex) { using (var pse = new PSInstallerException(ex)) { if (null != pse.ErrorRecord) { this.WriteError(pse.ErrorRecord); } } } } } } }
private void RemoveWurflProvider() { var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name =="DotNetNuke.WURFLClientCapabilityProvider"); if(package != null) { var installer = new Installer(package, Globals.ApplicationMapPath); installer.UnInstall(true); } UpdateRules(); }
public async Task CheckInstallation() { await Installer.Init(); Enabled = true; }
private void RemoveWurflProvider() { var package = PackageController.GetPackageByName("DotNetNuke.WURFLClientCapabilityProvider"); if(package != null) { var installer = new Installer(package, Globals.ApplicationMapPath); installer.UnInstall(true); } UpdateRules(); }
public void InstallerInstallProduct() { string dbFile = "InstallerInstallProduct.msi"; string productCode; using (Database db = new Database(dbFile, DatabaseOpenMode.CreateDirect)) { WindowsInstallerUtils.InitializeProductDatabase(db); WindowsInstallerUtils.CreateTestProduct(db); productCode = db.ExecuteStringQuery("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductCode'")[0]; db.Commit(); } ProductInstallation installation = new ProductInstallation(productCode); Assert.IsFalse(installation.IsInstalled, "Checking that product is not installed before starting."); Installer.SetInternalUI(InstallUIOptions.Silent); ExternalUIHandler prevHandler = Installer.SetExternalUI(WindowsInstallerTest.ExternalUILogger, InstallLogModes.FatalExit | InstallLogModes.Error | InstallLogModes.Warning | InstallLogModes.User | InstallLogModes.Info | InstallLogModes.ResolveSource | InstallLogModes.OutOfDiskSpace | InstallLogModes.ActionStart | InstallLogModes.ActionData | InstallLogModes.CommonData | InstallLogModes.Progress | InstallLogModes.Initialize | InstallLogModes.Terminate | InstallLogModes.ShowDialog); Assert.IsNull(prevHandler, "Checking that returned previous UI handler is null."); Exception caughtEx = null; try { Installer.InstallProduct(dbFile, String.Empty); } catch (Exception ex) { caughtEx = ex; } Assert.IsNull(caughtEx, "Exception thrown while installing product: " + caughtEx); prevHandler = Installer.SetExternalUI(prevHandler, InstallLogModes.None); Assert.AreEqual <ExternalUIHandler>(WindowsInstallerTest.ExternalUILogger, prevHandler, "Checking that previously-set UI handler is returned."); Assert.IsTrue(installation.IsInstalled, "Checking that product is installed."); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("==================================================================="); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); ExternalUIRecordHandler prevRecHandler = Installer.SetExternalUI(WindowsInstallerTest.ExternalUIRecordLogger, InstallLogModes.FatalExit | InstallLogModes.Error | InstallLogModes.Warning | InstallLogModes.User | InstallLogModes.Info | InstallLogModes.ResolveSource | InstallLogModes.OutOfDiskSpace | InstallLogModes.ActionStart | InstallLogModes.ActionData | InstallLogModes.CommonData | InstallLogModes.Progress | InstallLogModes.Initialize | InstallLogModes.Terminate | InstallLogModes.ShowDialog); Assert.IsNull(prevRecHandler, "Checking that returned previous UI record handler is null."); try { Installer.InstallProduct(dbFile, "REMOVE=All"); } catch (Exception ex) { caughtEx = ex; } Assert.IsNull(caughtEx, "Exception thrown while installing product: " + caughtEx); Assert.IsFalse(installation.IsInstalled, "Checking that product is not installed after removing."); prevRecHandler = Installer.SetExternalUI(prevRecHandler, InstallLogModes.None); Assert.AreEqual <ExternalUIRecordHandler>(WindowsInstallerTest.ExternalUIRecordLogger, prevRecHandler, "Checking that previously-set UI record handler is returned."); }
public void Create(Format format, string filename, DeviceConfig cmp) { var src = GetExamplesWith(filename); var engine = new Installer(format, src); var dest = engine.Config; Assert.That(engine, Is.Not.Null); Assert.That(engine.Location, Is.EqualTo(src)); Assert.That(engine.IO, Is.Not.Null); // PortMonitors Assert.That(dest.PortMonitors.Count, Is.EqualTo(cmp.PortMonitors.Count)); for (var i = 0; i < dest.PortMonitors.Count; ++i) { var x = dest.PortMonitors[i]; var y = cmp.PortMonitors[i]; var m = $"{nameof(dest.PortMonitors)}[{i}]"; Assert.That(x.Name, Is.EqualTo(y.Name), $"{m}.{nameof(x.Name)}"); Assert.That(x.FileName, Is.EqualTo(y.FileName), $"{m}.{nameof(x.FileName)}"); Assert.That(x.Config, Is.EqualTo(y.Config), $"{m}.{nameof(x.Config)}"); } // Ports Assert.That(dest.Ports.Count, Is.EqualTo(cmp.Ports.Count)); for (var i = 0; i < dest.Ports.Count; ++i) { var x = dest.Ports[i]; var y = cmp.Ports[i]; var m = $"{nameof(dest.Ports)}[{i}]"; Assert.That(x.Name, Is.EqualTo(y.Name), $"{m}.{nameof(x.Name)}"); Assert.That(x.MonitorName, Is.EqualTo(y.MonitorName), $"{m}.{nameof(x.MonitorName)}"); Assert.That(x.Application, Is.EqualTo(y.Application), $"{m}.{nameof(x.Application)}"); Assert.That(x.Arguments, Is.EqualTo(y.Arguments), $"{m}.{nameof(x.Arguments)}"); Assert.That(x.Temp, Is.EqualTo(y.Temp), $"{m}.{nameof(x.Temp)}"); Assert.That(x.WaitForExit, Is.EqualTo(y.WaitForExit), $"{m}.{nameof(x.WaitForExit)}"); } // PrinterDrivers Assert.That(dest.PrinterDrivers.Count, Is.EqualTo(cmp.PrinterDrivers.Count)); for (var i = 0; i < dest.PrinterDrivers.Count; ++i) { var x = dest.PrinterDrivers[i]; var y = cmp.PrinterDrivers[i]; var m = $"{nameof(dest.PrinterDrivers)}[{i}]"; Assert.That(x.Name, Is.EqualTo(y.Name), $"{m}.{nameof(x.Name)}"); Assert.That(x.MonitorName, Is.EqualTo(y.MonitorName), $"{m}.{nameof(x.MonitorName)}"); Assert.That(x.FileName, Is.EqualTo(y.FileName), $"{m}.{nameof(x.FileName)}"); Assert.That(x.Config, Is.EqualTo(y.Config), $"{m}.{nameof(x.Config)}"); Assert.That(x.Data, Is.EqualTo(y.Data), $"{m}.{nameof(x.Data)}"); Assert.That(x.Help, Is.EqualTo(y.Help), $"{m}.{nameof(x.Help)}"); Assert.That(x.Dependencies, Is.EqualTo(y.Dependencies), $"{m}.{nameof(x.Dependencies)}"); } // Printers Assert.That(dest.Printers.Count, Is.EqualTo(cmp.Printers.Count)); for (var i = 0; i < dest.Printers.Count; ++i) { var x = dest.Printers[i]; var y = cmp.Printers[i]; var m = $"{nameof(dest.Printers)}[{i}]"; Assert.That(x.Name, Is.EqualTo(y.Name), $"{m}.{nameof(x.Name)}"); Assert.That(x.ShareName, Is.EqualTo(y.ShareName), $"{m}.{nameof(x.ShareName)}"); Assert.That(x.DriverName, Is.EqualTo(y.DriverName), $"{m}.{nameof(x.DriverName)}"); Assert.That(x.PortName, Is.EqualTo(y.PortName), $"{m}.{nameof(x.PortName)}"); } }
static void InstallInfrastructure() { Configure.With(AllAssemblies.Except("NServiceBus.Host32.exe")); var installer = new Installer<Installation.Environments.Windows>(WindowsIdentity.GetCurrent()); installer.InstallInfrastructureInstallers(); }
public HostServiceInstaller(HostSettings settings) { _installer = CreateInstaller(settings); _transactedInstaller = CreateTransactedInstaller(_installer); }
protected override void ProcessRecord() { var fileName = Path; PerformInstallAction(() => { if (!System.IO.Path.IsPathRooted(fileName)) { var packagePath = FullPackagePath(fileName); WriteVerbose($"Path is not rooted. Updating to {packagePath}."); if (!FileUtil.Exists(packagePath)) { packagePath = System.IO.Path.GetFullPath( System.IO.Path.Combine( CurrentProviderLocation("FileSystem").ProviderPath, fileName)); WriteVerbose($"Path could not be found. Updating to {packagePath}."); if (!FileUtil.Exists(packagePath)) { WriteVerbose("Path still could not be found. Check that the file actually exists in the Sitecore package directory."); } } fileName = packagePath; } if (ShouldProcess(fileName, "Install package")) { var obsoleter = TypeResolver.Resolve <IObsoleter>(); var indexSetting = obsoleter.IndexingEnabled; if (DisableIndexing.IsPresent) { obsoleter.IndexingEnabled = false; } try { IProcessingContext context = new SimpleProcessingContext(); IItemInstallerEvents instance1 = new DefaultItemInstallerEvents(new BehaviourOptions(InstallMode, MergeMode)); context.AddAspect(instance1); IFileInstallerEvents instance2 = new DefaultFileInstallerEvents(true); context.AddAspect(instance2); var installer = new Installer(); installer.InstallPackage(fileName, context); ISource <PackageEntry> source = new PackageReader(fileName); var previewContext = Installer.CreatePreviewContext(); var view = new MetadataView(previewContext); var metadataSink = new MetadataSink(view); metadataSink.Initialize(previewContext); source.Populate(metadataSink); installer.ExecutePostStep(view.PostStep, previewContext); } finally { if (DisableIndexing.IsPresent) { obsoleter.IndexingEnabled = indexSetting; } } } }); }
public static bool AllFunctioning() { const uint TIMEOUT = 300; // 5 minutes DriverFunctioning[] drivers = new DriverFunctioning[] { new DriverFunctioning("xenbus", Installer.States.XenBusInstalled, XenBus.IsFunctioning ), new DriverFunctioning("xeniface", Installer.States.XenIfaceInstalled, XenIface.IsFunctioning ), new DriverFunctioning("xenvif", Installer.States.XenVifInstalled, XenVif.IsFunctioning ), new DriverFunctioning("xenvbd", Installer.States.XenVbdInstalled, XenVbd.IsFunctioning ) }; bool busEnumerated = false; bool result = true; Trace.WriteLine( "Checking if all PV Devices are functioning properly" ); bool bNeedReInstall = false; for (int i = 0; i < drivers.Length; ++i) { if (!drivers[i].pvDevIsFunctioning(out bNeedReInstall)) { if (!busEnumerated) { string xenBusHwId = XenBus.hwIDs[ Helpers.BitIdxFromFlag( (uint)XenBus.preferredXenBus) ]; Device.Enumerate(xenBusHwId, true); Helpers.BlockUntilNoDriversInstalling(TIMEOUT); busEnumerated = true; --i; } else { result = false; if (bNeedReInstall) { Installer.UnsetFlag(drivers[i].installState); Trace.WriteLine("driver: " + drivers[i].name + " does not work after enumerte, will try reinstall"); } } } } return(result); }
/// <summary> /// Copies the directory and all subdirectories. /// </summary> public override bool Do(Installer installer) { String sourcePath = installer.ResourcesDirectory + this.Source; String targetPath = AppPaths.GetApplicationPaths().GetPath(this.Target).AbsolutePath; if (this.UseScriptId) targetPath += "/" + installer.Manifest.Id; String[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories); foreach (String file in files) { String targetFile = targetPath + "/" + file.Substring(sourcePath.Length); FileInfo fileInfo = new FileInfo(targetFile); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } File.Copy(file, targetFile, true); if (this.Target == AppPaths.Directory.MacroScripts) ManagedServices.MaxscriptSDK.ExecuteMaxscriptCommand("fileIn " + targetFile); } InstallerLog.WriteLine("Copied directory " + targetPath); return true; }
internal static void Postfix(ref MenuInstaller __instance) { Installer.InstallFromBase(__instance, Installer.gameCoreSceneSetupInstallers, Installer.gameCoreSiraInstallers); }
/// <summary> /// Method: dsAddEngine /// Description: This method is used to update a new file as a datastream into the msi file /// </summary> /// <param name="iFile"></param> /// <param name="iDSFile"></param> static void dsAddEngine(string iFile, string iDSFile) { try { copyrightBanner(); string dbRecords = String.Empty; //variable to hold the record values being read Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("-: The Windows Installer Database provided is: " + iFile); Console.WriteLine("-: The Data Stream File to embedd is: " + iDSFile); if (disableBackup == 0) { Console.WriteLine("-: Back up Windows Installer Database file : " + iFile + " to " + iFile + ".bac"); Random rSeed = new Random(); int rSeedValue = rSeed.Next(0, 100); File.Copy(iFile, iFile + rSeedValue + ".bac"); Console.WriteLine("-: Backup Completed..."); } Console.WriteLine("-: Processing Data Streams, please wait..."); Console.WriteLine("-: Opening the Windows Installer Database File...\n"); //Get the Type for Windows Installer Type winInstallerType = Type.GetTypeFromProgID("WindowsInstaller.Installer"); //Create the windows installer object Installer winInstallerObj = (Installer)Activator.CreateInstance(winInstallerType); //Open the Database Database winInstallerDB = winInstallerObj.OpenDatabase(iFile, MsiOpenDatabaseMode.msiOpenDatabaseModeTransact); try { //Create a View and Execute it View winInstallerView = winInstallerDB.OpenView("SELECT `Name`, `Data` FROM _Streams"); Record winInstallerRecord = winInstallerObj.CreateRecord(2); winInstallerRecord.set_StringData(1, iDSFile); winInstallerView.Execute(winInstallerRecord); winInstallerRecord.SetStream(2, iDSFile); winInstallerView.Modify(MsiViewModify.msiViewModifyAssign, winInstallerRecord); winInstallerDB.Commit(); Console.WriteLine("-: The file " + iDSFile + " is now embedded into the MSI Data Streams."); } catch (System.Runtime.InteropServices.COMException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: There was an error opening the file : " + iDSFile, ex.Message); Console.ResetColor(); } } catch (System.IndexOutOfRangeException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: There was an error opening the file: " + iFile, ex.Message); Console.ResetColor(); } catch (System.Runtime.InteropServices.COMException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: There was an error opening the file: " + iFile, ex.Message); Console.ResetColor(); } }
public void GivenFilesWillBeInstalled() { Installer .Install(Arg.Any <PackageReference>(), Arg.Any <PackageType>(), Arg.Any <DirectoryPath>()) .Returns(info => new[] { FileSystem.CreateFile("/Working/Bin/Temp.dll") }); }
/// <summary> /// Sets up the user interface handlers. /// </summary> protected override void BeginProcessing() { // Set up the UI handlers. this.previousInternalUI = Installer.SetInternalUI(InstallUIOptions.Silent); base.BeginProcessing(); }
/// <summary> /// Removes the directory from the target directory. /// </summary> public override bool Undo(Installer installer) { String scriptPath = AppPaths.GetApplicationPaths().GetPath(AppPaths.Directory.Scripts).AbsolutePath; //TODO add check for UseScriptId String targetPath = scriptPath + "/" + installer.Manifest.Id; if (Directory.Exists(targetPath)) { Directory.Delete(targetPath, true); InstallerLog.WriteLine("Deleted directory " + targetPath); } return true; }
/// <summary> /// Restores the previous user interface handlers. /// </summary> protected override void EndProcessing() { Installer.SetInternalUI(this.previousInternalUI); base.EndProcessing(); }
public void CustomActionTest1() { InstallLogModes logEverything = InstallLogModes.FatalExit | InstallLogModes.Error | InstallLogModes.Warning | InstallLogModes.User | InstallLogModes.Info | InstallLogModes.ResolveSource | InstallLogModes.OutOfDiskSpace | InstallLogModes.ActionStart | InstallLogModes.ActionData | InstallLogModes.CommonData | InstallLogModes.Progress | InstallLogModes.Initialize | InstallLogModes.Terminate | InstallLogModes.ShowDialog; Installer.SetInternalUI(InstallUIOptions.Silent); ExternalUIHandler prevHandler = Installer.SetExternalUI( WindowsInstallerTest.ExternalUILogger, logEverything); try { string[] customActions = new string[] { "SampleCA1", "SampleCA2" }; #if DEBUG string caDir = @"..\..\..\..\..\build\debug\x86\"; #else string caDir = @"..\..\..\..\..\build\ship\x86\"; #endif caDir = Path.GetFullPath(caDir); string caFile = "WixToolset.Dtf.Samples.ManagedCA.dll"; string caProduct = "CustomActionTest.msi"; this.CreateCustomActionProduct(caProduct, caDir + caFile, customActions, false); Exception caughtEx = null; try { Installer.InstallProduct(caProduct, String.Empty); } catch (Exception ex) { caughtEx = ex; } Assert.IsInstanceOfType(caughtEx, typeof(InstallCanceledException), "Exception thrown while installing product: " + caughtEx); string arch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); string arch2 = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"); if (arch == "AMD64" || arch2 == "AMD64") { caDir = caDir.Replace("x86", "x64"); this.CreateCustomActionProduct(caProduct, caDir + caFile, customActions, true); caughtEx = null; try { Installer.InstallProduct(caProduct, String.Empty); } catch (Exception ex) { caughtEx = ex; } Assert.IsInstanceOfType(caughtEx, typeof(InstallCanceledException), "Exception thrown while installing 64bit product: " + caughtEx); } } finally { Installer.SetExternalUI(prevHandler, InstallLogModes.None); } }
/// <summary> /// Removes the specified package. /// </summary> /// <param name="package"> The package. </param> /// <remarks> /// </remarks> public void Remove(Package package) { lock (typeof(MSIBase)) { int currentTotalTicks = -1; int currentProgress = 0; int progressDirection = 1; int actualPercent = 0; Installer.SetExternalUI(((messageType, message, buttons, icon, defaultButton) => { switch (messageType) { case InstallMessage.Progress: if (message.Length >= 2) { var msg = message.Split(": ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(m => m.ToInt32(0)).ToArray(); switch (msg[1]) { // http://msdn.microsoft.com/en-us/library/aa370354(v=VS.85).aspx case 0: //Resets progress bar and sets the expected total number of ticks in the bar. currentTotalTicks = msg[3]; currentProgress = 0; if (msg.Length >= 6) { progressDirection = msg[5] == 0 ? 1 : -1; } break; case 1: //Provides information related to progress messages to be sent by the current action. break; case 2: //Increments the progress bar. if (currentTotalTicks == -1) { break; } currentProgress += msg[3] * progressDirection; break; case 3: //Enables an action (such as CustomAction) to add ticks to the expected total number of progress of the progress bar. break; } if (currentTotalTicks > 0) { var newPercent = (currentProgress * 100 / currentTotalTicks); if (actualPercent < newPercent) { actualPercent = newPercent; Event <IndividualProgress> .RaiseFirst(actualPercent); } } } break; } // capture installer messages to play back to status listener return(MessageResult.OK); }), InstallLogModes.Progress); try { Installer.InstallProduct(package.PackageSessionData.LocalValidatedLocation, @"REMOVE=ALL COAPP=1 ALLUSERS=1 REBOOT=REALLYSUPPRESS"); var cachedInstaller = Path.Combine(PackageManagerSettings.CoAppPackageCache, package.CanonicalName.PackageName + ".msi"); if (File.Exists(cachedInstaller)) { cachedInstaller.TryHardToDelete(); } } finally { SetUIHandlersToSilent(); } } }
/// <summary> /// Validate a database. /// </summary> /// <param name="databaseFile">The database to validate.</param> /// <returns>true if validation succeeded; false otherwise.</returns> public bool Validate(string databaseFile) { InstallUIHandler currentUIHandler = null; Hashtable indexedSuppressedICEs = new Hashtable(); int previousUILevel = (int)InstallUILevels.Basic; IntPtr previousHwnd = IntPtr.Zero; InstallUIHandler previousUIHandler = null; if (null == databaseFile) { throw new ArgumentNullException("databaseFile"); } // initialize the validator extension this.extension.DatabaseFile = databaseFile; this.extension.Output = this.output; this.extension.InitializeValidator(); // if we don't have the temporary files object yet, get one if (null == this.tempFiles) { this.tempFiles = new TempFileCollection(); } Directory.CreateDirectory(this.TempFilesLocation); // ensure the base path is there // index the suppressed ICEs if (null != this.suppressedICEs) { foreach (string suppressedICE in this.suppressedICEs) { indexedSuppressedICEs[suppressedICE] = null; } } // copy the database to a temporary location so it can be manipulated string tempDatabaseFile = Path.Combine(this.TempFilesLocation, Path.GetFileName(databaseFile)); File.Copy(databaseFile, tempDatabaseFile); // remove the read-only property from the temporary database FileAttributes attributes = File.GetAttributes(tempDatabaseFile); File.SetAttributes(tempDatabaseFile, attributes & ~FileAttributes.ReadOnly); try { using (Database database = new Database(tempDatabaseFile, OpenDatabase.Direct)) { bool propertyTableExists = database.TableExists("Property"); string productCode = null; // remove the product code from the database before opening a session to prevent opening an installed product if (propertyTableExists) { using (View view = database.OpenExecuteView("SELECT `Value` FROM `Property` WHERE Property = 'ProductCode'")) { Record record = null; try { if (null != (record = view.Fetch())) { productCode = record.GetString(1); using (View dropProductCodeView = database.OpenExecuteView("DELETE FROM `Property` WHERE `Property` = 'ProductCode'")) { } } } finally { if (null != record) { record.Close(); } } } } // merge in the cube databases foreach (string cubeFile in this.cubeFiles) { try { using (Database cubeDatabase = new Database(cubeFile, OpenDatabase.ReadOnly)) { try { database.Merge(cubeDatabase, "MergeConflicts"); } catch { // ignore merge errors since they are expected in the _Validation table } } } catch (Win32Exception e) { if (0x6E == e.NativeErrorCode) // ERROR_OPEN_FAILED { throw new WixException(WixErrors.CubeFileNotFound(cubeFile)); } throw; } } // commit the database before proceeding to ensure the streams don't get confused database.Commit(); // the property table may have been added to the database // from a cub database without the proper validation rows if (!propertyTableExists) { using (View view = database.OpenExecuteView("DROP table `Property`")) { } } // get all the action names for ICEs which have not been suppressed ArrayList actions = new ArrayList(); using (View view = database.OpenExecuteView("SELECT `Action` FROM `_ICESequence` ORDER BY `Sequence`")) { Record record; while (null != (record = view.Fetch())) { string action = record.GetString(1); if (!indexedSuppressedICEs.Contains(action)) { actions.Add(action); } record.Close(); } } // disable the internal UI handler and set an external UI handler previousUILevel = Installer.SetInternalUI((int)InstallUILevels.None, ref previousHwnd); currentUIHandler = new InstallUIHandler(this.ValidationUIHandler); previousUIHandler = Installer.SetExternalUI(currentUIHandler, (int)InstallLogModes.Error | (int)InstallLogModes.Warning | (int)InstallLogModes.User, IntPtr.Zero); // create a session for running the ICEs using (Session session = new Session(database)) { // add the product code back into the database if (null != productCode) { using (View view = database.OpenExecuteView(String.Format(CultureInfo.InvariantCulture, "INSERT INTO `Property` (`Property`, `Value`) VALUES ('ProductCode', '{0}')", productCode))) { } } foreach (string action in actions) { session.DoAction(action); } } } } catch (Win32Exception e) { // avoid displaying errors twice since one may have already occurred in the UI handler if (!this.encounteredError) { this.OnMessage(WixErrors.Win32Exception(e.NativeErrorCode, e.Message)); } } finally { Installer.SetExternalUI(previousUIHandler, 0, IntPtr.Zero); Installer.SetInternalUI(previousUILevel, ref previousHwnd); // very important - this prevents the external UI delegate from being garbage collected too early GC.KeepAlive(currentUIHandler); this.cubeFiles.Clear(); this.extension.FinalizeValidator(); } return(!this.encounteredError); }
public Inscriber() { this.tableDefinitions = Installer.GetTableDefinitions(); }
/// <summary> /// This action cannot be undone. /// </summary> public override bool Undo(Installer installer) { return true; }
protected void btnInstall_Click(object sender, EventArgs e) { ExecuteWithErrorHandling(Installer.Upgrade); status = null; Installer.UpdateStatus(Status.Level); }
static void Perform(bool install, string executable) { ArrayList order = new ArrayList(); Hashtable states = new Hashtable(); try { Assembly a; if (assembly != null) { a = Assembly.Load(assembly); } else { a = Assembly.LoadFrom(executable); } Type [] types = a.GetTypes(); // todo: pass arguments, they are kind of useless though. InstallContext ctx = new InstallContext(); foreach (Type t in types) { if (!t.IsSubclassOf(typeof(Installer))) { continue; } object [] attrs = t.GetCustomAttributes(typeof(RunInstallerAttribute), false); if (attrs == null || attrs.Length == 0) { continue; } RunInstallerAttribute ria = attrs [0] as RunInstallerAttribute; if (ria == null || !ria.RunInstaller) { continue; } try { Installer installer = (Installer)Activator.CreateInstance(t); Hashtable state = new Hashtable(); order.Add(installer); states [installer] = state; if (install) { Call(installer, "OnBeforeInstall", state); } else { Call(installer, "OnBeforeUninstall", state); } installer.Install(state); if (install) { Call(installer, "OnAfterInstall", state); } else { Call(installer, "OnAfterUninstall", state); } } catch (Exception e) { Error(String.Format("Can not create installer of type {0}", t)); // // According to the docs uninstall should not do rollback // if (install) { foreach (Installer installer in order) { Hashtable state = (Hashtable)states [installer]; Call(installer, "OnBeforeRollback", state); installer.Rollback(state); Call(installer, "OnAfterRollback", state); } } } } // // Got it, now commit them // if (install) { foreach (Installer inst in order) { Hashtable state = (Hashtable)states [inst]; Call(inst, "OnCommitting", state); inst.Commit(state); Call(inst, "OnCommitted", state); } } } catch { Error(String.Format("Unable to load assembly {0}", assembly)); } }
public override void InstallBindings() { Installer.Install(Container); }
private void Install() { backToSettingsButton.Enabled = false; finishButton.Enabled = false; var installer = new Installer(); var installActions = installer.GetInstallActions(); try { foreach (var installAction in installActions) { switch (installAction) { case InstallAction.StopAuditingService: UpdateInstallStatus("Stopping Auditing Service..."); break; case InstallAction.StartAuditingService: UpdateInstallStatus("Starting Auditing Service..."); break; case InstallAction.CopyApplicationFiles: UpdateInstallStatus("Copying Application Files..."); break; case InstallAction.CreateAdminServicesInstance: UpdateInstallStatus("Creating Admin Services Instance..."); break; case InstallAction.TestAdminServicesInstance: UpdateInstallStatus("Testing Admin Services Instance..."); break; case InstallAction.InstallAuditingService: UpdateInstallStatus("Installing Auditing Service..."); break; case InstallAction.CreateDefaultServicesInstance: UpdateInstallStatus("Creating Default Services Instance..."); break; case InstallAction.UpgradeServicesInstances: UpdateInstallStatus("Upgrading Services Instances..."); break; case InstallAction.TestDefaultServicesInstance: UpdateInstallStatus("Testing Default Services Instance..."); break; } Application.DoEvents(); installer.ExecuteInstallAction(installAction); installStatusTextBox.Text += "Done"; } UpdateInstallStatus(""); UpdateInstallStatus("Installation Completed Successfully!"); finishButton.Enabled = true; } catch (Exception ex) { UpdateInstallStatus(string.Empty); UpdateInstallStatus("ERROR: " + ex.Message); UpdateInstallStatus("Please check the logs for more information"); } finally { backToSettingsButton.Enabled = true; } }
public InstallerForm() { Icon = Icon.FromResource("icon"); KeyDown += (sender, e) => { Console.WriteLine($"XXX {e.Key}"); if (e.Key.HasFlag(Keys.Enter) && e.Modifiers.HasFlag(Keys.Control)) { Options.Visible = true; } }; AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((sender, e) => { var ex = (Exception)e.ExceptionObject; Log.WriteLine("\nUnhandled error!"); Log.WriteLine(ex.Message); }); Downloader = new Downloader(); Installer = new Installer(Downloader, null); Title = $"Mod the Gungeon Installer {Version} (core {Installer.Version})"; ClientSize = new Size(640, 400); MainLayout = new DynamicLayout(); MainLayout.BeginHorizontal(); MainLayout.BeginVertical(); MainLayout.Add(new Label { Text = "Output log" }); MainLayout.Add(Log = new Log()); MainLayout.Add(new ImageView { Image = Bitmap.FromResource("icon") }, false, false); MainLayout.EndVertical(); MainLayout.BeginVertical(); MainLayout.Add(new Label { Text = "Path to the Gungeon executable" }); MainLayout.Add(ExeSelector = new ExeSelector()); Installer.ChangeExePath(ExeSelector.Path); ExeSelector.PathChanged += (sender, e) => { Installer.ChangeExePath(ExeSelector.Path); UpdateInstallButton(); }; MainLayout.Add(CheckboxesLayout = new StackLayout { Orientation = Orientation.Horizontal, }); ComponentList = new ComponentList(Downloader.Components.Values); Options = new Options { Visible = false }; ComponentList.SelectedVersionsChanged += (sender, e) => UpdateInstallButton(); ShowCheckboxes(); MainLayout.Add(null, false, true); VersionDisplay = new VersionDisplay(); VersionDisplay.ConnectTo(ComponentList); MainLayout.Add(InstallButton = new Button { Text = "Install", Enabled = false, Size = new Size(100, -1) }, true, false); MainLayout.Add(UninstallButton = new Button { Text = "Uninstall", Size = new Size(100, -1) }, true, false); InstallButton.Click += (sender, e) => Install(); UninstallButton.Click += (sender, e) => Uninstall(); MainLayout.EndVertical(); Content = MainLayout; Log.WriteLine("Welcome!"); var subscriber = new Logger.Subscriber((logger, loglevel, indent, str) => { var formatted = logger.String(loglevel, str, indent); Application.AsyncInvoke(() => Log.WriteLine(formatted)); }); Logger.Subscribe(subscriber); }
/// <summary> /// Remove a button from a toolbar. /// </summary> public override bool Undo(Installer installer) { CuiFile cui = new CuiFile(CuiFile.MaxGetActiveCuiFile()); if (!cui.Read()) return false; Int32 numRemoved = 0; foreach (CuiToolbar toolbar in cui.Toolbars) { numRemoved += toolbar.RemoveButton(this.MacroName, this.MacroCategory); } if (numRemoved > 0) { if (!cui.Write()) return false; else cui.MaxLoadCuiFile(); } return true; }
private void CheckVMulti(object sender, RoutedEventArgs e) => Log($"VMulti is {(Installer.Detect() ? null : "not ")}installed.");
public ActionResult Index(InstallModel model) { var installer = new Installer(Server.MapPath("~")); if (ModelState.IsValid) { var ret = installer.SetRepository(model.WikiRepository, model.GitUser, model.GitPassword, false); var allIsWell = true; switch(ret) { case InstallerMessage.ExceptionThrown : ModelState.AddModelError("WikiRepository", installer.LastException.Message); allIsWell = false; break; case InstallerMessage.UnkownFailure : ModelState.AddModelError("WikiRepository", "We couldn't clone the wiki repository. Unfortunately, we don't know why :("); allIsWell = false; break; } var conf = WebConfigurationManager.OpenWebConfiguration("~"); ret = installer.SetDbConnection(model.ConnectionString, model.DatabaseProvider); switch (ret) { case InstallerMessage.CouldNotConnectToDb : ModelState.AddModelError("ConnectionString", "Could not connect to the database."); allIsWell = false; break; case InstallerMessage.InvalidConnectionString : ModelState.AddModelError("ConnectionString", "The connection string is invalid."); allIsWell = false; break; case InstallerMessage.InvalidDbProvider: ModelState.AddModelError("DatabaseProvider", "This provider could not be found."); allIsWell = false; break; } if (!allIsWell) return View(); WG.Settings.Repository = model.WikiRepository; WG.Settings.GitUser = model.GitUser; WG.Settings.GitPassword = model.GitPassword; WG.Settings.AdminUsername = model.AdminUsername; WG.Settings.AllowRegistration = model.AllowRegistration; WG.Settings.UseSameGitAccountForAllUsers = model.UseSameGitAccountForAllUsers; WG.Settings.Auth.EnableGoogleLogin = model.EnableGoogleLogin; WG.Settings.Auth.GoogleAppsDomain = model.GoogleAppsDomain; WG.Settings.Save(); conf.Save(ConfigurationSaveMode.Full); // creating or update admin user var admin = _usrRepo.FindByUsername(model.AdminUsername); if (WebSecurity.UserExists(model.AdminUsername)) WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(model.AdminUsername), model.AdminPassword); else WebSecurity.CreateUserAndAccount(model.AdminUsername, model.AdminPassword); WebSecurity.Login(model.AdminUsername, model.AdminPassword); installer.SetAdmin(model.AdminUsername); return RedirectToAction("Index", "Home"); } return View(); }
private void button1_Click_1(object sender, EventArgs e) { Installer.InstallPromDate(fileBox.Text, releaseNumbers[urlDropdown.SelectedIndex]); status.Text = "Installed!"; }
/// <summary> /// Runs the Do method so it can be used as an uninstall action. /// </summary> public override bool Undo(Installer installer) { return Do(installer); }
private void button2_Click(object sender, EventArgs e) { Installer.UninstallPromDate(fileBox.Text); status.Text = "Uninstalled!"; }
private void InstallSitecorePackage([NotNull] string fileName) { Context.SetActiveSite("shell"); using (new SecurityDisabler()) { using (new ProxyDisabler()) { using (new SyncOperationContext()) { var context = new SimpleProcessingContext(); var defaultItemInstallerEvents = new DefaultItemInstallerEvents(new BehaviourOptions(InstallMode.Overwrite, MergeMode.Clear)); context.AddAspect(defaultItemInstallerEvents); var defaultFileInstallerEvents = new DefaultFileInstallerEvents(true); context.AddAspect(defaultFileInstallerEvents); var installer = new Installer(); installer.InstallPackage(FileUtil.MapPath(fileName), context); var packageReader = new PackageReader(FileUtil.MapPath(fileName)); var previewContext = Installer.CreatePreviewContext(); var view = new MetadataView(previewContext); var sink = new MetadataSink(view); sink.Initialize(previewContext); packageReader.Populate(sink); installer.ExecutePostStep(view.PostStep, previewContext); } } } }
public void Uninstall(string filename) => Invoke(() => { var src = new Installer(Format.Json, GetExamplesWith(filename)); src.Uninstall(); });