Beispiel #1
0
        public static async Task <DismFeatureInfo> EnableWindowsFeatures(string featureName,
                                                                         DismProgressCallback dismProgressCallback)
        {
            if (string.IsNullOrWhiteSpace(featureName))
            {
                throw new ArgumentException();
            }

            DismApi.Initialize(DismLogLevel.LogErrors);

            DismFeatureInfo retVal;

            try
            {
                using (var session = DismApi.OpenOnlineSession())
                {
                    DismApi.EnableFeatureByPackageName(session, featureName, null, false, true, new List <string>(),
                                                       dismProgressCallback);

                    retVal = DismApi.GetFeatureInfo(session, featureName);
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            await Task.Delay(200).ConfigureAwait(false);

            return(retVal);
        }
Beispiel #2
0
        public static async Task <IEnumerable <KeyValuePair <string, DismFeatureInfo> > > GetWindowsFeatureInfo(
            IEnumerable <string> featureNames)
        {
            var enumerable = featureNames as string[] ?? featureNames.ToArray();

            if (!enumerable.Any())
            {
                throw new ArgumentException();
            }

            DismApi.Initialize(DismLogLevel.LogErrors);

            var retVal = new List <KeyValuePair <string, DismFeatureInfo> >();

            try
            {
                using (var session = DismApi.OpenOnlineSession())
                {
                    retVal.AddRange(enumerable.Where(key => !string.IsNullOrWhiteSpace(key))
                                    .Select(featureName => new KeyValuePair <string, DismFeatureInfo>(featureName,
                                                                                                      DismApi.GetFeatureInfo(session, featureName))));
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            await Task.Delay(200).ConfigureAwait(false);

            return(retVal);
        }
Beispiel #3
0
        public override bool ShouldPerformTreatment()
        {
            int packageCount = 0;

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismAppxPackageCollection dismAppxPackages = DismApi.GetProvisionedAppxPackages(session);
                    foreach (var package in dismAppxPackages)
                    {
                        if (StoreApps.ShouldRemove(package.DisplayName))
                        {
                            Logger.Log("Would deprovision {0}", package.DisplayName);
                            packageCount += 1;
                        }
                        else
                        {
                            Logger.Log("Not deprovisioning {0}", package.DisplayName);
                        }
                    }
                }
            }
            catch
            {
                return(false);
            }

            if (packageCount > 0)
            {
                return(true);
            }

            return(false);
        }
Beispiel #4
0
        private Status DoInstall(string argument)
        {
            Status = Status.Working;
            //var result = Processes.Open("pnputil.exe", argument);

            ////http://www.hiteksoftware.com/knowledge/articles/049.htm

            using (var session = DismApi.OpenOnlineSession())
            {
                try
                {
                    DismApi.AddDriver(session, Location, false);
                    return(Status.Success);
                }
                catch (Exception Ex)
                {
                    _tooltip = Ex.Message;
                    return(Status.Failed);
                }


                //if (!string.IsNullOrWhiteSpace(err))
                //{
                //    MessageBox.Show(err, "Error");
                //    //}
                //    return Status.Failed;
                //}
            }

            //if (result == 0)
            //{
            return(Status.Success);
            //}
            /// return Status.Failed;
        }
        public static List <string> DISMlist()
        {
            List <string> result = new List <string>(220);

            try
            {
                DismApi.Initialize(DismLogLevel.LogErrors);
                var dismsession = DismApi.OpenOnlineSession();
                var listupdate  = DismApi.GetPackages(dismsession);

                int ab = listupdate.Count;
                //Console.WriteLine("Количество обновлений через DISM: " + ab);
                string sw = "Количество обновлений через DISM: " + ab;
                result.Add(sw);

                foreach (DismPackage feature in listupdate)
                {
                    result.Add(feature.PackageName);
                    //result.Add($"[Имя пакета] {feature.PackageName}");
                    //result.Add($"[Дата установки] {feature.InstallTime}");
                    //result.Add($"[Тип обновления] {feature.ReleaseType}");
                }
            }

            catch (Exception ex)
            {
                result.Add("Что-то пошло не так: " + ex.Message);
            }

            return(result);
        }
        public void PerformTreatment()
        {
            int packageCount = 0;

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismAppxPackageCollection dismAppxPackages = DismApi.GetProvisionedAppxPackages(session);
                    foreach (var package in dismAppxPackages)
                    {
                        try
                        {
                            DismApi.RemoveProvisionedAppxPackage(session, package.PackageName);
                            logger.Log("Successfully deprovisioned {0}", package.DisplayName);
                        }
                        catch (DismRebootRequiredException ex)
                        {
                            logger.Log("Successfully deprovisioned {0}: {1}", package.DisplayName, ex.Message);
                        }

                        packageCount += 1;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Log("An error occurred while deprovisioning packages: {0}", ex.Message);
            }

            if (packageCount <= 0)
            {
                logger.Log("No Windows Store packages were deprovisioned.");
            }
        }
Beispiel #7
0
        public override bool PerformTreatment()
        {
            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    try
                    {
                        DismApi.DisableFeature(session, resolvedFeatureName, null, true);
                    }
                    catch (DismRebootRequiredException ex)
                    {
                        Logger.Log("Successfully disabled Internet Explorer 11. {0}", ex.Message);
                        return(true);
                    }

                    Logger.Log("Successfully disabled Internet Explorer 11.");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Log("An error occurred while disabling Internet Explorer: {0}", ex.Message);
            }

            return(false);
        }
Beispiel #8
0
        public void CheckImageHealthOnlineSession()
        {
            using (DismSession session = DismApi.OpenOnlineSession())
            {
                DismImageHealthState imageHealthState = DismApi.CheckImageHealth(session, scanImage: false, progressCallback: null, userData: null);

                imageHealthState.ShouldBe(DismImageHealthState.Healthy);
            }
        }
Beispiel #9
0
        public void PerformTreatment()
        {
            string featureName;

            if (Environment.Is64BitOperatingSystem)
            {
                featureName = IE64BitName;
            }
            else
            {
                featureName = IE32BitName;
            }

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismFeatureInfo info = DismApi.GetFeatureInfo(session, featureName);
                    if (
                        info.FeatureState == DismPackageFeatureState.NotPresent ||
                        info.FeatureState == DismPackageFeatureState.Removed ||
                        info.FeatureState == DismPackageFeatureState.Staged)
                    {
                        logger.Log("Internet Explorer 11 is not present on the system.");
                        return;
                    }

                    if (info.FeatureState == DismPackageFeatureState.UninstallPending)
                    {
                        logger.Log("Internet Explorer 11 is already pending uninstall.");
                        return;
                    }

                    try
                    {
                        logger.Log("Disabling Internet Explorer 11...");
                        DismApi.DisableFeature(session, featureName, null, true);
                    }
                    catch (DismRebootRequiredException ex)
                    {
                        logger.Log("Successfully disabled Internet Explorer 11. {0}", ex.Message);
                        return;
                    }

                    logger.Log("Successfully disabled Internet Explorer 11.");
                }
            }
            catch (Exception ex)
            {
                logger.Log("An error occurred while disabling Internet Explorer: {0}", ex.Message);
            }
        }
        public void GetPackageInfoExSimple()
        {
            using (DismSession session = DismApi.OpenOnlineSession())
            {
                DismPackage package = DismApi.GetPackages(session).FirstOrDefault(i => i.PackageState == DismPackageFeatureState.Installed);

                package.ShouldNotBeNull();

                DismPackageInfoEx packageInfoEx = DismApi.GetPackageInfoExByName(session, package.PackageName);

                packageInfoEx.CapabilityId.ShouldNotBeNullOrWhiteSpace();
            }
        }
        private DismSession GetSession()
        {
            switch (this.Type)
            {
            case DriverStoreType.Online:
                return(DismApi.OpenOnlineSession());

            case DriverStoreType.Offline:
                return(DismApi.OpenOfflineSession(this.OfflineStoreLocation));

            default:
                throw new NotSupportedException();
            }
        }
Beispiel #12
0
        /// <summary>
        /// Execute example.
        /// </summary>
        public void Run()
        {
            DismApi.Initialize(DismLogLevel.LogErrors);
            using (var session = DismApi.OpenOnlineSession())
            {
                foreach (DismFeature feature in DismApi.GetFeatures(session))
                {
                    Console.WriteLine($"[Feature Name] {feature.FeatureName}");
                    Console.WriteLine($"[State] {feature.State}");
                    Console.WriteLine();
                }
            }

            DismApi.Shutdown();
        }
Beispiel #13
0
        public void GetCapabilitiesOnlineSession()
        {
            using (DismSession session = DismApi.OpenOnlineSession())
            {
                DismCapabilityCollection capabilities = DismApi.GetCapabilities(session);

                capabilities.Count.ShouldBeGreaterThan(0);

                foreach (DismCapability capability in capabilities)
                {
                    capability.Name.ShouldNotBeNullOrWhiteSpace();

                    capability.State.ShouldBeOneOf(DismPackageFeatureState.Installed, DismPackageFeatureState.NotPresent);
                }
            }
        }
Beispiel #14
0
        public override bool PerformTreatment()
        {
            int removedPackageCount = 0;

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismAppxPackageCollection dismAppxPackages = DismApi.GetProvisionedAppxPackages(session);
                    foreach (var package in dismAppxPackages)
                    {
                        try
                        {
                            if (StoreApps.ShouldRemove(package.DisplayName))
                            {
                                DismApi.RemoveProvisionedAppxPackage(session, package.PackageName);
                                Logger.Log("Successfully deprovisioned {0}", package.DisplayName);
                                removedPackageCount += 1;
                            }
                            else
                            {
                                Logger.Log("Not deprovisioning {0}", package.DisplayName);
                            }
                        }
                        catch (DismRebootRequiredException ex)
                        {
                            Logger.Log("Successfully deprovisioned {0}: {1}", package.DisplayName, ex.Message);
                            removedPackageCount += 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("An error occurred while deprovisioning packages: {0}", ex.Message);
                return(false);
            }

            if (removedPackageCount <= 0)
            {
                Logger.Log("No Windows Store packages were deprovisioned.");
            }

            return(true);
        }
        public bool DeleteDriver(DriverStoreEntry dse, bool forceDelete)
        {
            DismApi.Initialize(DismLogLevel.LogErrors);

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismApi.RemoveDriver(session, dse.DriverFolderLocation);
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            return(true);
        }
        public bool AddDriver(string infFullPath, bool install)
        {
            DismApi.Initialize(DismLogLevel.LogErrors);

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismApi.AddDriver(session, infFullPath, false);
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            return(true);
        }
        public void GetProvisionedAppxPackagesSimple()
        {
            using (DismSession onlineSession = DismApi.OpenOnlineSession())
            {
                DismAppxPackageCollection packages = DismApi.GetProvisionedAppxPackages(onlineSession);

                packages.ShouldNotBeNull();

                foreach (DismAppxPackage package in packages)
                {
                    package.Architecture.ShouldBeOneOf(Enum.GetValues(typeof(DismProcessorArchitecture)).Cast <DismProcessorArchitecture>().ToArray());
                    package.DisplayName.ShouldNotBeNullOrWhiteSpace();
                    package.InstallLocation.ShouldNotBeNullOrWhiteSpace();
                    package.PackageName.ShouldNotBeNullOrWhiteSpace();
                    package.PublisherId.ShouldNotBeNullOrWhiteSpace();
                    package.ResourceId.ShouldNotBeNullOrWhiteSpace();
                    package.Version.ShouldBeGreaterThan(Version.Parse("0.0.0.0"));
                }
            }
        }
Beispiel #18
0
        public static async Task <DismFeatureInfo> GetWindowsFeatureInfo(string featureName)
        {
            DismApi.Initialize(DismLogLevel.LogErrors);

            DismFeatureInfo retVal;

            try
            {
                using (var session = DismApi.OpenOnlineSession())
                {
                    retVal = DismApi.GetFeatureInfo(session, featureName);
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            await Task.Delay(200).ConfigureAwait(false);

            return(retVal);
        }
Beispiel #19
0
        public override bool ShouldPerformTreatment()
        {
            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    DismFeatureInfo info = DismApi.GetFeatureInfo(session, resolvedFeatureName);
                    if (
                        info.FeatureState == DismPackageFeatureState.NotPresent ||
                        info.FeatureState == DismPackageFeatureState.Removed ||
                        info.FeatureState == DismPackageFeatureState.Staged ||
                        info.FeatureState == DismPackageFeatureState.UninstallPending)
                    {
                        return(false);
                    }
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Beispiel #20
0
        public void CheckImageHealthOnlineSessionWithCallback()
        {
            const string expectedUserData = "257E41FC307248608E28C3B1F8D5CF09";

            string userData = null;

            int current = -1;
            int total   = -1;

            using (DismSession session = DismApi.OpenOnlineSession())
            {
                try
                {
                    DismApi.CheckImageHealth(
                        session: session,
                        scanImage: true, // Setting scanImage to true seems to trigger the callback being called
                        progressCallback: progress =>
                    {
                        userData = progress.UserData as string;
                        current  = progress.Current;
                        total    = progress.Total;

                        // Cancel the operation, otherwise it takes ~1 min
                        progress.Cancel = true;
                    },
                        userData: expectedUserData);
                }
                catch (OperationCanceledException)
                {
                }

                userData.ShouldBe(expectedUserData);
                current.ShouldBe(50);
                total.ShouldBe(1000);
            }
        }
        public List <DriverStoreEntry> EnumeratePackages()
        {
            List <DriverStoreEntry> driverStoreEntries = new List <DriverStoreEntry>();

            DismApi.Initialize(DismLogLevel.LogErrors);

            try
            {
                using (DismSession session = DismApi.OpenOnlineSession())
                {
                    foreach (var driverPackage in DismApi.GetDrivers(session, false))
                    {
                        driverStoreEntries.Add(new DriverStoreEntry
                        {
                            DriverClass          = driverPackage.ClassDescription,
                            DriverInfName        = Path.GetFileName(driverPackage.OriginalFileName),
                            DriverPublishedName  = driverPackage.PublishedName,
                            DriverPkgProvider    = driverPackage.ProviderName,
                            DriverSignerName     = driverPackage.DriverSignature.ToString(),
                            DriverDate           = driverPackage.Date,
                            DriverVersion        = driverPackage.Version,
                            DriverFolderLocation = Path.GetDirectoryName(driverPackage.OriginalFileName),
                            DriverSize           = DriverStoreRepository.GetFolderSize(new DirectoryInfo(Path.GetDirectoryName(driverPackage.OriginalFileName))),
                            BootCritical         = driverPackage.BootCritical,
                            Inbox = driverPackage.InBox,
                        });
                    }
                }
            }
            finally
            {
                DismApi.Shutdown();
            }

            return(driverStoreEntries);
        }
Beispiel #22
0
        private void cleanupOnlineImageButton_Click(object sender, EventArgs e)
        {
            DismApi.Initialize(DismLogLevel.LogErrors);
            Task.Factory.StartNew(() =>
            {
                Task.Run(() =>
                {
                    if (this.InvokeRequired)
                    {
                        this.Invoke((MethodInvoker)(() =>
                        {
                            loadingPanel.Visible = true;
                            mainPanel.Enabled = false;
                            mainPanel.Visible = false;
                        }));
                    }
                    else
                    {
                        loadingPanel.Visible = true;
                        mainPanel.Enabled    = false;
                        mainPanel.Visible    = false;
                    }
                });


                // Initialize the DismApi



                try
                {
                    List <string> sourcePath = new List <string> {
                        @"C:\"
                    };
                    using (DismSession session = DismApi.OpenOnlineSession())
                    {
                        // Get the features of the image
                        Task.Run(() =>
                        {
                            if (this.InvokeRequired)
                            {
                                this.Invoke((MethodInvoker)(() =>
                                {
                                    label1.Text = "Checking Health";
                                }));
                            }
                        });
                        var health = DismApi.CheckImageHealth(session, false, dismProgress_action);
                        Task.Run(() =>
                        {
                            if (this.InvokeRequired)
                            {
                                this.Invoke((MethodInvoker)(() =>
                                {
                                    label1.Text = "Restoring Health";
                                }));
                            }
                        });
                        DismApi.RestoreImageHealth(session, true, null, dismProgress_action);
                    }
                }
                finally
                {
                    if (this.InvokeRequired)
                    {
                        this.Invoke((MethodInvoker)(() =>
                        {
                            loadingPanel.Visible = false;
                            mainPanel.Enabled = true;
                            mainPanel.Visible = true;
                        }));
                    }
                    else
                    {
                        loadingPanel.Visible = false;
                        mainPanel.Enabled    = true;
                        mainPanel.Visible    = true;
                    }
                    DismApi.Shutdown();
                }
            });
        }
Beispiel #23
0
        /// <summary>
        ///     Either installs or integrate the update to the live OS or image.
        /// </summary>
        /// <param name="LDR">Install LDR or GDR.</param>
        /// <returns></returns>
        private Status DoWork(Task task, string mountPath, bool LDR)
        {
            if (_progressBar == null)
            {
                _progressBar = new ProgressBar();
            }

            _progressBar.Value = 0;

            Status = Status.Working;

            // if (CheckIntegration(mountPath, LDR)) { return Status.Success; }

            if (task == Task.Install)
            {
                using (var session = DismApi.OpenOnlineSession())
                {
                    DismApi.AddPackage(session, Location, true, false,
                                       delegate(DismProgress progress) { _progressBar.Value = progress.Current; });
                }
                // Processes.Run("pkgmgr.exe", "/ip /m:\"" + Location + "\" /quiet /norestart");
            }
            else
            {
                Processes.Run(DISM.Default.Location,
                              "/Image:\"" + mountPath + "\" /Add-Package /Packagepath:\"" + Location + "\"");
            }

            if (LDR && (_updateType == UpdateType.Unknown || _updateType == UpdateType.LDR))
            {
                if (CheckIntegration(mountPath))
                {
                    return(Status.Failed);
                }
                Extraction.Expand(Location, _tempLocation);

                _updateType = UpdateType.GDR;
                if (File.Exists(_tempLocation + "\\update-bf.mum"))
                {
                    _updateType = UpdateType.LDR;

                    if (task == Task.Install)
                    {
                        Processes.Run("pkgmgr.exe",
                                      "/ip /m:\"" + _tempLocation + "\\update-bf.mum" + "\" /quiet /norestart");
                    }
                    else
                    {
                        var s = Processes.Run("DISM",
                                              "/Image:\"" + mountPath + "\" /Add-Package /Packagepath:\"" + _tempLocation +
                                              "\\update-bf.mum" + "\"");
                        MessageBox.Show(s);
                    }
                }

                FileHandling.DeleteDirectory(_tempLocation);
            }

            UpdateCache.Add(this);

            if (_updateType != UpdateType.LDR)
            {
                LDR = false;
            }

            if (CheckIntegration(mountPath, LDR))
            {
                return(Status.Success);
            }
            return(Status.Failed);
        }