Пример #1
0
        private void LoadUninstallableItems()
        {
            var products      = ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All).ToArray();
            var installations = products
                                .Where(ins => ins.ProductName != null)
                                .Select(ins => new InstalledItem(ins.ProductName,
                                                                 ins.ProductCode,
                                                                 ins.InstallDate,
                                                                 ins.InstallLocation,
                                                                 ins.UrlInfoAbout,
                                                                 ins.ProductVersion,
                                                                 ins.Publisher))
                                .OrderBy(ins => ins.Product);

            _logger.Info("Found {0} installed items", installations.Count());
            Items                = new ObservableCollection <InstalledItem>(installations);
            FilteredItems        = CollectionViewSource.GetDefaultView(Items);
            FilteredItems.Filter = ItemFilter();
            FilteredItems.Refresh();

            Cancelling          = false;
            UninstallInProgress = false;
            UninstallCurrent    = 0;
            UninstallTotal      = 0;
            UninstallProgress   = 0;
        }
Пример #2
0
        /// <summary>
        /// Installs a product given the provided <paramref name="data"/>.
        /// </summary>
        /// <param name="data">An <see cref="InstallProductActionData"/> with information about the package to install.</param>
        protected override void ExecuteAction(InstallProductActionData data)
        {
            if (!string.IsNullOrEmpty(data.TargetDirectory))
            {
                data.CommandLine += string.Format(CultureInfo.InvariantCulture, @" TARGETDIR=""{0}""", data.TargetDirectory);
            }

            if (!string.IsNullOrEmpty(data.Path))
            {
                Installer.InstallProduct(data.Path, data.CommandLine);
            }
            else if (!string.IsNullOrEmpty(data.ProductCode))
            {
                Installer.ConfigureProduct(data.ProductCode, INSTALLLEVEL_DEFAULT, InstallState.Default, data.CommandLine);
            }

            if (this.PassThru)
            {
                var product = ProductInstallation.GetProducts(data.ProductCode, null, UserContexts.All).FirstOrDefault();
                if (null != product && product.IsInstalled)
                {
                    this.WriteObject(product.ToPSObject(this.SessionState.Path));
                }
            }
        }
Пример #3
0
 /// <summary>
 /// Enumerates related products and writes them to the pipeline.
 /// </summary>
 /// <param name="upgradeCode"></param>
 private void WriteProducts(string upgradeCode)
 {
     foreach (ProductInstallation product in ProductInstallation.GetRelatedProducts(upgradeCode))
     {
         this.WriteProduct(product);
     }
 }
Пример #4
0
        private Session OpenProduct(ProductInstallation product)
        {
            // Open the product taking machine state into account.
            var path = product.LocalPackage;

            if (!string.IsNullOrEmpty(path))
            {
                return(Installer.OpenPackage(path, this.IgnoreMachineState));
            }
            else if (product.IsAdvertised && !string.IsNullOrEmpty(product.AdvertisedPackageName))
            {
                // Product is advertised and has no locally installed package.
                var message = string.Format(Properties.Resources.Error_Advertised, product.ProductCode);
                this.WriteWarning(message);
            }
            else
            {
                // Product registration is corrupt.
                var message = string.Format(Properties.Resources.Error_Corrupt, product.ProductCode);
                var ex      = new Exception(message, new Win32Exception(NativeMethods.ERROR_BAD_CONFIGURATION));
                var error   = new ErrorRecord(ex, "Error_Corrupt", ErrorCategory.NotInstalled, product);

                this.WriteError(error);
            }

            return(null);
        }
Пример #5
0
        public static OrphanComponent IsOrphanComponent(RegistryKey componentKey)
        {
            string[] productCodes = componentKey.GetValueNames();

            string          compName = Path.GetFileName(componentKey.Name);
            OrphanComponent orphan   = new OrphanComponent(compName);

            foreach (string p in productCodes)
            {
                // Ignore default value
                if (string.IsNullOrWhiteSpace(p) || p.Equals("@") || p.Equals("00000000000000000000000000000000"))
                {
                    continue;
                }

                Guid productCode   = p.MsiObfuscate();
                Guid componentGuid = compName.MsiObfuscate();

                IEnumerable <ProductInstallation> pis = ProductInstallation.GetProducts(productCode.ToString("B"), null, UserContexts.All);
                if ((pis == null) || (pis.Count() <= 0))
                {
                    string keyPath = componentKey.GetValue(p) as string;
                    Console.WriteLine($"Component '{componentGuid.ToString("B")}' in registry key '{componentKey.Name}' is registered to product '{productCode.ToString("B")} which is not installed with KeyPath='{keyPath}'");
                    orphan.NonExistingClients.Add(productCode.ToString("B"));
                }
            }

            return(orphan.NonExistingClients.Count > 0 ? orphan : null);
        }
Пример #6
0
        public static string GetProductInfo(string productode, MsiProductSearchType type)
        {
            string productInfo = string.Empty;

            ProductInstallation product = new ProductInstallation(productode, "s-1-1-0", UserContexts.All);

            switch (type)
            {
            case MsiProductSearchType.assignment:
                productInfo = product.Context.ToString();     //TODO
                break;

            case MsiProductSearchType.language:
                productInfo = product["ProductLanguage"].ToString();
                break;

            case MsiProductSearchType.state:
                productInfo = product.Context.ToString();
                break;

            case MsiProductSearchType.version:
                productInfo = product.ProductVersion.ToString();
                break;
            }

            return(productInfo);
        }
        private static string GetPreviousVersionInstallPath()
        {
            var retVal = String.Empty;

            var products = ProductInstallation.GetProducts("{944871E7-9F8D-47B7-BE04-103E4C8F2254}", null, UserContexts.All);
            var product  = products?.FirstOrDefault();
            var location = product?.LocalPackage;

            if (location != null)
            {
                var package     = new InstallPackage(location, DatabaseOpenMode.ReadOnly);
                var componentId = package.Files.FirstOrDefault(kvp => kvp.Value.SourceName == "UO Bulk Order Deeds.exe").Key;

                if (componentId != null)
                {
                    var results = package.ExecuteQuery($"SELECT `ComponentId` FROM `Component` WHERE `Component` = 'C_{componentId}'");
                    var result  = results?.Count > 0 ? results[0].ToString() : null;

                    if (result != null)
                    {
                        var componentInstallation = new ComponentInstallation(result);
                        var componentPath         = componentInstallation.Path;

                        retVal = Path.GetDirectoryName(componentPath);
                    }
                }
            }

            return(retVal);
        }
Пример #8
0
        /// <summary>
        /// Gets the <see cref="Installation"/> class given the <see cref="Parameters"/>.
        /// </summary>
        /// <param name="param">The <see cref="Parameters"/> of the <see cref="Installation"/> to get.</param>
        /// <returns>An <see cref="Installation"/> given the <see cref="Parameters"/>.</returns>
        protected Installation GetInstallation(Parameters param)
        {
            Installation installation = null;

            try
            {
                if (string.IsNullOrEmpty(param.PatchCode))
                {
                    installation = ProductInstallation.GetProducts(param.ProductCode, param.UserSid, param.UserContext).FirstOrDefault();
                }
                else
                {
                    installation = PatchInstallation.GetPatches(param.PatchCode, param.ProductCode, param.UserSid, param.UserContext, PatchStates.All).FirstOrDefault();
                }
            }
            catch (InstallerException ex)
            {
                var pse = new PSInstallerException(ex);
                if (null != pse.ErrorRecord)
                {
                    base.WriteError(pse.ErrorRecord);
                }
            }

            return(installation);
        }
Пример #9
0
        private DataView GetProductData(string productCode)
        {
            DataTable table = new DataTable("ProductProperties");

            table.Locale = CultureInfo.InvariantCulture;
            table.Columns.Add("ProductPropertiesProperty", typeof(string));
            table.Columns.Add("ProductPropertiesValue", typeof(string));

            // Add a fake "ProductCode" install property, just for display convenience.
            table.Rows.Add(new object[] { "ProductCode", productCode });

            ProductInstallation product = new ProductInstallation(productCode);

            foreach (string property in new string[]
            {
                "AssignmentType",
                "DiskPrompt",
                "HelpLink",
                "HelpTelephone",
                "InstalledProductName",
                "InstallDate",
                "InstallLocation",
                "InstallSource",
                "Language",
                "LastUsedSource",
                "LastUsedType",
                "LocalPackage",
                "MediaPackagePath",
                "PackageCode",
                "PackageName",
                "ProductIcon",
                "ProductID",
                "ProductName",
                "Publisher",
                "RegCompany",
                "RegOwner",
                "State",
                "transforms",
                "Uninstallable",
                "UrlInfoAbout",
                "UrlUpdateInfo",
                "Version",
                "VersionMinor",
                "VersionMajor",
                "VersionString"
            })
            {
                try
                {
                    string value = product[property];
                    table.Rows.Add(new object[] { property, (value != null ? value : "") });
                }
                catch (InstallerException iex)
                {
                    table.Rows.Add(new object[] { property, iex.Message });
                }
                catch (ArgumentException) { }
            }
            return(new DataView(table, "", "ProductPropertiesProperty ASC", DataViewRowState.CurrentRows));
        }
Пример #10
0
        public static string GetProductName(string productCode)
        {
            string productName = (string)productCodesToNames[productCode];

            if (productName == null)
            {
                productName = new ProductInstallation(productCode).ProductName;
                productName = productName.Replace('\\', ' ');
                if (productNamesToCodes.Contains(productName))
                {
                    string modifiedProductName = null;
                    for (int i = 2; i < Int32.MaxValue; i++)
                    {
                        modifiedProductName = productName + " [" + i + "]";
                        if (!productNamesToCodes.Contains(modifiedProductName))
                        {
                            break;
                        }
                    }
                    productName = modifiedProductName;
                }
                productCodesToNames[productCode] = productName;
                productNamesToCodes[productName] = productCode;
            }
            return(productName);
        }
Пример #11
0
        private void OnDetectRelatedMsiPackage(object sender, DetectRelatedMsiPackageEventArgs e)
        {
            if (e.PackageId == "PicoTorrentPackage" &&
                e.Operation == RelatedOperation.MajorUpgrade)
            {
                var existingProduct = new ProductInstallation(e.ProductCode);

                if (!existingProduct.IsInstalled)
                {
                    _bootstrapper.Engine.Log(LogLevel.Standard, $"Product not installed ({e.ProductCode})");
                    return;
                }

                try
                {
                    var firewallFeature    = existingProduct.GetFeatureState("F_Firewall");
                    var associationFeature = existingProduct.GetFeatureState("F_Handlers");

                    InstallModel.InstallWaitingModel.AddWindowsFirewallException  = firewallFeature == Microsoft.Deployment.WindowsInstaller.InstallState.Local;
                    InstallModel.InstallWaitingModel.RegisterFileProtocolHandlers = associationFeature == Microsoft.Deployment.WindowsInstaller.InstallState.Local;
                }
                catch (ArgumentException argException)
                {
                    _bootstrapper.Engine.Log(LogLevel.Error, $"Failed to get previous feature state: {argException}");
                }

                InstallModel.IsUpgrade = true;
            }
        }
Пример #12
0
 /// <summary>
 /// Enumerates products for the given ProductCode and writes them to the pipeline.
 /// </summary>
 /// <param name="productCode">The ProductCode of products to enumerate.</param>
 /// <param name="userSid">The user's SID for products to enumerate.</param>
 /// <param name="context">The installation context for products to enumerate.</param>
 /// <param name="patterns">Optional list of <see cref="WildcardPattern"/> to match product names.</param>
 private void WriteProducts(string productCode, string userSid, UserContexts context, IList <WildcardPattern> patterns = null)
 {
     foreach (ProductInstallation product in ProductInstallation.GetProducts(productCode, userSid, context))
     {
         if (0 == patterns.Count() || product.ProductName.Match(patterns))
         {
             this.WriteProduct(product);
         }
     }
 }
Пример #13
0
        /// <summary>
        ///     Uninstalls a package
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with
        ///     the CORE and HOST
        /// </param>
        public void UninstallPackage(string fastPackageReference, Request request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrWhiteSpace(fastPackageReference))
            {
                throw new ArgumentNullException("fastPackageReference");
            }
            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::UninstallPackage' '{1}'", ProviderName, fastPackageReference);

            try {
                Guid guid;
                if (!Guid.TryParse(fastPackageReference, out guid))
                {
                    request.Error(Microsoft.PackageManagement.Internal.ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference);
                    return;
                }
                var product = ProductInstallation.GetProducts(fastPackageReference, null, UserContexts.All).FirstOrDefault();
                if (product == null)
                {
                    request.Error(Microsoft.PackageManagement.Internal.ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference);
                    return;
                }
                var productVersion = product.ProductVersion.ToString();
                var productName    = product.ProductName;
                var summary        = product["Summary"];

                Installer.SetInternalUI(InstallUIOptions.UacOnly | InstallUIOptions.Silent);
                _progressId = request.StartProgress(0, Resources.Messages.UninstallingMSIPackage, productName);
                var handler = CreateProgressHandler(request, Resources.Messages.UnInstalling);

                Installer.SetExternalUI(handler, InstallLogModes.Progress | InstallLogModes.Info);
                Installer.InstallProduct(product.LocalPackage, "REMOVE=ALL REBOOT=REALLYSUPPRESS");
                Installer.SetInternalUI(InstallUIOptions.Default);

                Installer.SetExternalUI(handler, InstallLogModes.None);

                // YieldPackage(product,fastPackageReference, request);
                if (request.YieldSoftwareIdentity(fastPackageReference, productName, productVersion, "multipartnumeric", summary, "", fastPackageReference, "", "") != null)
                {
                    request.AddMetadata(fastPackageReference, "ProductCode", fastPackageReference);
                    request.AddTagId(fastPackageReference.Trim(new char[] { '{', '}' }));
                }


                request.Warning(Resources.Messages.UninstallRequireReboot);
            } catch (Exception e) {
                e.Dump();
            }
            request.CompleteProgress(_progressId, true);
            _progressId = 0;
        }
Пример #14
0
        /// <summary>
        ///     Uninstalls a package
        /// </summary>
        /// <param name="fastPackageReference"></param>
        /// <param name="requestImpl">
        ///     An object passed in from the CORE that contains functions that can be used to interact with
        ///     the CORE and HOST
        /// </param>
        public void UninstallPackage(string fastPackageReference, RequestImpl requestImpl)
        {
            try {
                // create a strongly-typed request object.
                using (var request = requestImpl.As <Request>()) {
                    // Nice-to-have put a debug message in that tells what's going on.
                    request.Debug("Calling '{0}::UninstallPackage' '{1}'", ProviderName, fastPackageReference);

                    try {
                        Guid guid;
                        if (!Guid.TryParse(fastPackageReference, out guid))
                        {
                            request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference);
                            return;
                        }
                        var product = ProductInstallation.GetProducts(fastPackageReference, null, UserContexts.All).FirstOrDefault();
                        if (product == null)
                        {
                            request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference);
                            return;
                        }
                        var productVersion = product.ProductVersion.ToString();
                        var productName    = product.ProductName;
                        var summary        = product["Summary"];

                        Installer.SetInternalUI(InstallUIOptions.UacOnly | InstallUIOptions.Silent);
                        _progressId = request.StartProgress(0, "Uninstalling MSI '{0}'", productName);
                        var handler = CreateProgressHandler(request);

                        Installer.SetExternalUI(handler, InstallLogModes.Progress | InstallLogModes.Info);
                        Installer.InstallProduct(product.LocalPackage, "REMOVE=ALL REBOOT=REALLYSUPPRESS");
                        Installer.SetInternalUI(InstallUIOptions.Default);

                        Installer.SetExternalUI(handler, InstallLogModes.None);

                        // YieldPackage(product,fastPackageReference, request);
                        if (request.YieldSoftwareIdentity(fastPackageReference, productName, productVersion, "multipartnumeric", summary, "", fastPackageReference, "", ""))
                        {
                            request.YieldSoftwareMetadata(fastPackageReference, "ProductCode", fastPackageReference);
                        }

                        request.Warning("Reboot is required to complete uninstallation.");
                    } catch (Exception e) {
                        e.Dump();
                    }
                    request.CompleteProgress(_progressId, true);
                    _progressId = 0;
                }
            } catch (Exception e) {
                // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
                // Really this is just here as a precautionary to behave correctly.
                // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
                Debug.WriteLine("Unexpected Exception thrown in '{0}::UninstallPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace);
            }
        }
Пример #15
0
 /// <summary>
 /// Return true if it finds the given productcode in system otherwise it returns false
 /// </summary>
 /// <param name="prodCode"></param>
 /// <returns></returns>
 public static bool IsProductInstalled(string prodCode)
 {
     //look in all user's products (both per-machine and per-user)
     foreach (ProductInstallation product in ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All))
     {
         if (product.ProductCode == prodCode)
         {
             return(true);
         }
     }
     return(false);
 }
Пример #16
0
 private Version GetProductVersion(ProductInstallation ins)
 {
     try
     {
         return(ins.ProductVersion);
     }
     catch (Exception)
     {
         _logger.Warn("Count not determine product version for '{0}'", ins.ProductName);
         return(new Version(0, 0, 0, 0));
     }
 }
Пример #17
0
        /// <summary>
        /// Writes a source information to the pipeline.
        /// </summary>
        /// <param name="installation">The <see cref="Installation"/> to which the source is registered.</param>
        protected void WriteSourceList(Installation installation)
        {
            ProductInstallation product = null;
            PatchInstallation   patch   = null;
            var order = 0;

            if (installation is ProductInstallation)
            {
                product = (ProductInstallation)installation;
            }
            else if (installation is PatchInstallation)
            {
                patch = (PatchInstallation)installation;
            }

            try
            {
                foreach (var source in installation.SourceList)
                {
                    SourceInfo info = null;
                    if (null != product)
                    {
                        info = new SourceInfo(product.ProductCode, product.UserSid, product.Context, source, order++);
                    }
                    else if (null != patch)
                    {
                        info = new PatchSourceInfo(patch.ProductCode, patch.PatchCode, patch.UserSid, patch.Context, source, order++);
                    }

                    if (null != info)
                    {
                        this.WriteObject(info);
                    }
                }
            }
            catch (InstallerException ex)
            {
                if (NativeMethods.ERROR_BAD_CONFIGURATION == ex.ErrorCode)
                {
                    var code      = null != product ? product.ProductCode : null != patch ? patch.PatchCode : string.Empty;
                    var message   = string.Format(Properties.Resources.Error_Corrupt, code);
                    var exception = new Exception(message, ex);

                    var error = new ErrorRecord(exception, "Error_Corrupt", ErrorCategory.NotInstalled, installation);
                    base.WriteError(error);
                }
                else
                {
                    throw;
                }
            }
        }
Пример #18
0
        /// <summary>
        /// Installs a patch given the provided <paramref name="data"/>.
        /// </summary>
        /// <param name="data">An <see cref="InstallProductActionData"/> with information about the package to install.</param>
        protected override void ExecuteAction(InstallPatchActionData data)
        {
            Installer.ApplyMultiplePatches(data.Patches, data.ProductCode, data.CommandLine);

            if (this.PassThru)
            {
                var product = ProductInstallation.GetProducts(data.ProductCode, null, UserContexts.All).FirstOrDefault();
                if (null != product && product.IsInstalled)
                {
                    this.WriteObject(product.ToPSObject(this.SessionState.Path));
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Return a list of ProductInstallation objects.
        /// For per-machine installs, the list will only contain 1 object.
        /// For per-user installs, the list will contain an object for each user that installed it.
        /// </summary>
        /// <param name="prodCode"></param>
        /// <returns></returns>
        public static List <ProductInstallation> GetProducts(string prodCode)
        {
            List <ProductInstallation> products = new List <ProductInstallation>();

            //look in all user's products (both per-machine and per-user)
            foreach (ProductInstallation product in ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All))
            {
                if (product.ProductCode == prodCode)
                {
                    products.Add(product);
                }
            }
            return(products);
        }
Пример #20
0
        /// <summary>
        /// Gets the weight of a package given its ProductCode.
        /// </summary>
        /// <param name="productCode">The ProductCode of the product to query.</param>
        /// <param name="userSid">The optional user SID of the product to query. The default is null.</param>
        /// <param name="context">The optional context of the product ot query. The default is <see cref="UserContexts.All"/>.</param>
        /// <returns>The weight of a package given its ProductCode or 0 if the product is not installed or the package missing.</returns>
        internal static long GetWeightFromProductCode(string productCode, string userSid = null, UserContexts context = UserContexts.All)
        {
            var product = new ProductInstallation(productCode, userSid, context);

            if (null != product && product.IsInstalled)
            {
                var path = product.LocalPackage;
                if (!string.IsNullOrEmpty(path))
                {
                    return(PackageInfo.GetWeightFromPath(path));
                }
            }

            return(0);
        }
Пример #21
0
        private static void FindProductInstalledFeatures(Session session, string previousProductCode)
        {
            var previousProduct = ProductInstallation.GetProducts(
                previousProductCode,
                null,
                UserContexts.Machine).FirstOrDefault();

            if (null == previousProduct)
            {
                return;
            }

            foreach (var feature in previousProduct.Features)
            {
                InitializeFeatureProperty(session, feature);
            }
        }
Пример #22
0
        private bool YieldPackage(ProductInstallation package, string searchKey, Request request)
        {
            if (request.YieldSoftwareIdentity(package.ProductCode, package.ProductName, package.ProductVersion.ToString(), "multipartnumeric", package["Summary"], package.InstallSource, searchKey, package.InstallLocation, "?"))
            {
                if (!request.YieldSoftwareMetadata(package.ProductCode, "ProductCode", package.ProductCode))
                {
                    return(false);
                }

                if (!request.YieldSoftwareMetadata(package.ProductCode, "UpgradeCode", package["UpgradeCode"]))
                {
                    return(false);
                }
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Returns the product version of the currently installed
        ///     Microsoft.AccessibilityInsights application
        /// Returns null if the version could not be found
        ///     - could occur if the application has not been installed at all
        ///     - could occur if Windows Installer's cached MSI file is corrupted or deleted
        /// </summary>
        /// <returns></returns>
        public static string GetInstalledProductVersion(IExceptionReporter exceptionReporter)
        {
            if (exceptionReporter == null)
            {
                throw new ArgumentNullException(nameof(exceptionReporter));
            }

            string targetUpgradeCode = UpdateGuid.ToUpperInvariant();

            // Check whether application with target upgrade code is installed on this machine
            IEnumerable <ProductInstallation> installations = ProductInstallation.GetRelatedProducts(targetUpgradeCode);
            bool existingApp;

            try
            {
                existingApp = installations.Any();
            }
            catch (ArgumentException e)
            {
                exceptionReporter.ReportException(e);
                // occurs when the upgrade code is formatted incorrectly
                // exception text: "Parameter is incorrect"
                return(null);
            }
            if (!existingApp)
            {
                // occurs when the upgrade code does not match any existing application
                return(null);
            }
            ProductInstallation existingInstall = installations.FirstOrDefault <ProductInstallation>(i => i.ProductVersion != null);

            if (existingInstall == null)
            {
                return(null);
            }
            string msiFilePath = existingInstall.LocalPackage;

            if (msiFilePath != null)
            {
                return(GetMSIProductVersion(msiFilePath));
            }

            // Should only get here if LocalPackage not set
            return(null);
        }
Пример #24
0
        private bool YieldPackage(ProductInstallation package, string searchKey, Request request) {
            if (request.YieldSoftwareIdentity(package.ProductCode, package.ProductName, package.ProductVersion.ToString(), "multipartnumeric", package["Summary"], package.InstallSource, searchKey, package.InstallLocation, "?") != null) {
                if (request.AddMetadata(package.ProductCode, "ProductCode", package.ProductCode) == null) {
                    return false;
                }

                if (request.AddTagId(package.ProductCode.Trim(new char[] {'{','}'})) == null)
                {
                    return false;
                }

                if (request.AddMetadata(package.ProductCode, "UpgradeCode", package["UpgradeCode"]) == null) {
                    return false;
                }
                return true;
            }
            return false;
        }
Пример #25
0
        /// <summary>
        /// Returns a <see cref="PSObject"/> wrapper for a <see cref="ProductInstallation"/> object and attaches special properties.
        /// </summary>
        /// <param name="source">The <see cref="ProductInstallation"/> object to convert.</param>
        /// <param name="provider">A <see cref="PathIntrinsics"/> provider used to convert paths.</param>
        /// <returns>A <see cref="PSObject"/> wrapper with attached special properties.</returns>
        internal static PSObject ToPSObject(this ProductInstallation source, PathIntrinsics provider = null)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }

            var obj = PSObject.AsPSObject(source);

            // Add path information if possible.
            if (null != provider)
            {
                var path = provider.GetUnresolvedPSPathFromProviderPath(source.LocalPackage);
                obj.SetPropertyValue<string>("PSPath", path);
            }

            return obj;
        }
        private void LoadUninstallableItems()
        {
            var installations = ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All)
                                .Where(ins => ins.ProductName != null)
                                .Select(ins => new InstalledItem(ins.ProductName,
                                                                 ins.ProductCode,
                                                                 ins.InstallDate,
                                                                 ins.InstallLocation,
                                                                 ins.UrlInfoAbout,
                                                                 ins.ProductVersion))
                                .OrderBy(ins => ins.Product);

            Items = new ObservableCollection <InstalledItem>(installations);

            Cancelling          = false;
            UninstallInProgress = false;
            UninstallCurrent    = 0;
            UninstallTotal      = 0;
            UninstallProgress   = 0;
        }
Пример #27
0
        public void Cleanup()
        {
            var products = ProductInstallation.GetProducts(ExampleProductCode, null, UserContexts.All);

            if (products.Any(p => p.IsAdvertised || p.IsInstalled))
            {
                var previous = Installer.SetInternalUI(InstallUIOptions.Silent);
                try
                {
                    foreach (var product in products)
                    {
                        Installer.ConfigureProduct(product.ProductCode, 0, InstallState.Absent, null);
                    }
                }
                finally
                {
                    Installer.SetInternalUI(previous);
                }
            }
        }
Пример #28
0
        private static string ExtractInnerVersion(ProductInstallation installedProduct)
        {
            if (null == installedProduct)
            {
                return(string.Empty);
            }

            var localPackage = installedProduct.LocalPackage;

            if (string.IsNullOrEmpty(localPackage))
            {
                return(string.Empty);
            }

            string innerVersion;

            using (var msiBase = new InstallPackage(localPackage, DatabaseOpenMode.ReadOnly))
            {
                innerVersion = msiBase.Property["InnerVersion"];
            }

            return(string.IsNullOrEmpty(innerVersion) ? string.Empty : innerVersion);
        }
Пример #29
0
        /// <summary>
        /// GetInstalledItems lists all items that are installed on this machine.
        /// </summary>
        /// <returns></returns>
        public ICollection <Package> GetAllInstalledItems()
        {
            Logger.Log(String.Format(CultureInfo.InvariantCulture, "Getting all installed items", AppName), Logger.MessageLevel.Information, AppName);
            ICollection <Package> installations = new List <Package>();

            try
            {
                Logger.Log(String.Format(CultureInfo.InvariantCulture, "Do we already have an object in memory?", AppName), Logger.MessageLevel.Verbose, AppName);
                if (installedmsis.FirstOrDefault() == null)
                {
                    Logger.Log(String.Format(CultureInfo.InvariantCulture, "No installpackages object found - creating", AppName), Logger.MessageLevel.Verbose, AppName);

                    installations = ProductInstallation.GetProducts(null, null, UserContexts.All)
                                    .Select(ins => new Package(
                                                this.GetUpgradeCode(ins.LocalPackage),
                                                ins.ProductCode,
                                                ins.ProductVersion == null ? "0.0.0" : ins.ProductVersion.ToString(),
                                                ApplyFilter(string.IsNullOrEmpty(ins.ProductName) ? "(NOTDEFINED)" : ins.ProductName),
                                                null
                                                )
                                            )
                                    .OrderBy(ins => ins.ProductName).ToList();
                    Logger.Log(String.Format(CultureInfo.InvariantCulture, "Packages installed: {0}", installations.Count().ToString(CultureInfo.InvariantCulture)));
                }
                else
                {
                    Logger.Log("installedpackages is populated.");
                    installations = (List <Package>)installedmsis;
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message, Logger.MessageLevel.Error, AppName);
            }
            installedmsis = installations;
            return(installations);
        }
Пример #30
0
        public void Burn_ValidateMultipleSourcePaths()
        {
            // Build the package.
            string packageA             = this.GetPackageA().Output;
            string packageA_Directory   = Path.GetDirectoryName(packageA);
            string packageA_ProductCode = MsiUtils.GetMSIProductCode(packageA);

            // Build the bundle.
            string bundleA = this.GetBundleA().Output;

            // Install the bundle.
            BundleInstaller installerA = new BundleInstaller(this, bundleA).Install();

            Assert.True(MsiVerifier.IsPackageInstalled(packageA));

            // Copy the package using the bundle package name.
            ProductInstallation product = new ProductInstallation(packageA_ProductCode, null, UserContexts.Machine);
            string packageA_Copy        = Path.Combine(packageA_Directory, product.AdvertisedPackageName);

            File.Copy(packageA, packageA_Copy);
            this.TestArtifacts.Add(new FileInfo(packageA_Copy));

            // Repair and recache the MSI.
            MSIExec.InstallProduct(packageA_Copy, MSIExec.MSIExecReturnCode.SUCCESS, "REINSTALL=ALL REINSTALLMODE=vomus");
            Assert.True(MsiVerifier.IsPackageInstalled(packageA));

            // Check that the source contains both the original and burn cached paths.
            SourceList sources = product.SourceList;

            Assert.Equal(2, sources.Count);

            // Attempt to uninstall bundleA.
            installerA.Uninstall();
            Assert.False(MsiVerifier.IsPackageInstalled(packageA));

            this.Complete();
        }
Пример #31
0
        private bool YieldPackage(ProductInstallation package, string searchKey, Request request) {
            if (request.YieldSoftwareIdentity(package.ProductCode, package.ProductName, package.ProductVersion.ToString(), "multipartnumeric", package["Summary"], package.InstallSource, searchKey, package.InstallLocation, "?") != null) {
                if (request.AddMetadata(package.ProductCode, "ProductCode", package.ProductCode) == null) {
                    return false;
                }

                if (request.AddMetadata(package.ProductCode, "UpgradeCode", package["UpgradeCode"]) == null) {
                    return false;
                }
                return true;
            }
            return false;
        }