Inheritance: IPackageManager
Beispiel #1
0
        public async Task LoadApps()
        {
            Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();
            IEnumerable<Windows.ApplicationModel.Package> packages;

            if (LoadLegacyAppsToo)
                packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUserWithPackageTypes("", PackageTypes.Bundle | PackageTypes.Framework | PackageTypes.Main | PackageTypes.None | PackageTypes.Resource | PackageTypes.Xap);
            else
                packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser("");

            int count = packages.Count();
            int progress = 0;


            StorageFolder localCacheFolder = ApplicationData.Current.LocalCacheFolder;

            if ((await localCacheFolder.TryGetItemAsync("Logos")) == null)
                await localCacheFolder.CreateFolderAsync("Logos");

            StorageFolder logosFolder = await localCacheFolder.GetFolderAsync("Logos");

            HashSet<string> existingAppFamilyNames = new HashSet<string>();
            foreach (var item in packages)
            {
                System.Diagnostics.Debug.WriteLine(progress);

                AppData appD = await LoadModernAndLegacyAppData(item, logosFolder);
                if ((appD != null) && (appD.PackageId != ""))
                {
                    appsData.AddSorted(appD, new AppDataNameComparer());
                    familyNameAppData.Add(appD.FamilyName, appD);
                    existingAppFamilyNames.Add(appD.FamilyName);
                }
                else if (appD != null)
                {
                    existingAppFamilyNames.Add(appD.FamilyName);
                }

                progress++;
                OnLoadingProgress(new LoadingEventArgs(progress, count));
            }

            //Remove apps that are no longer installed on device from cache.
            List<AppData> removedApps = new List<AppData>();
            foreach (var item in appsData)
            {
                if (!existingAppFamilyNames.Contains(item.FamilyName))
                    removedApps.Add(item);
            }

            foreach (var item in removedApps)
            {
                familyNameAppData.Remove(item.FamilyName);
                appsData.Remove(item);
            }


            SaveAppList();
            OnLoadCompleted();
        }
Beispiel #2
0
        private async static Task FindPackages() {
            PackageManager packageManager = new PackageManager();

            IEnumerable<Windows.ApplicationModel.Package> packages =
                (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackages();

            int packageCount = 0;
            foreach (var package in packages) {
                if (
                        (package.Id.Publisher.Contains("CN=Ron") || 
                        package.Id.Publisher.Contains("CN=Bob") || 
                        package.Id.FullName.StartsWith("Ron.")) 
                        && 
                        (!package.Id.FullName.StartsWith("Keep."))
                    )
                {
                    DisplayPackageInfo(package);
                    await packageManager.RemovePackageAsync(package.Id.FullName);
                    Console.WriteLine("=========================================================");
                }
                packageCount += 1;
            }

            if (packageCount < 1) {
                Console.WriteLine("No packages were found.");
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }
Beispiel #3
0
        /// <summary>
        /// Gets the metro applications.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<MetroApplication> GetApplications()
        {
            var packages = new PackageManager()
                .FindPackagesForUser(WindowsIdentity.GetCurrent().User.Value);

            var metroPackages = new List<MetroPackage>();

            foreach (var package in packages)
            {
                var metroPackage = new MetroPackage(package);

                if (metroPackage.Applications.Any())
                {
                    metroPackages.Add(new MetroPackage(package));
                }
            }

            var metroApplications = metroPackages
                .SelectMany(package => package.Applications)
                .Where(
                    application =>
                        !string.IsNullOrEmpty(application.AppUserModelId) &&
                        !string.IsNullOrEmpty(application.Name));

            return metroApplications;
        }
        public static bool CheckIsNpeMetroInstalled()
        {
            var user = WindowsIdentity.GetCurrent();
            var userSecurityId = user.Owner.Value;

            var pm = new PackageManager();
            var packages = pm.FindPackagesForUser(userSecurityId, "50582LuanNguyen.NuGetPackageExplorer_w6y2tyx5bpzwa");
            return packages.Any();
        }
        private async void RemoveUWP_Click(object sender, RoutedEventArgs e)
        {
            PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

            string inputPackageFullName = "015eefc1-86d1-4560-9488-c276a3c4b7cf_4.0.0.0_x64__2dhr6hz02r3tt";
            await packageManager.RemovePackageAsync(inputPackageFullName).AsTask().ConfigureAwait(true);

            MessageDialog md = new MessageDialog("Completed");
            await md.ShowAsync();
        }
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("FindPackagesByNameAndPublisher sample");
        Console.WriteLine();

        if (args.Length < 2)
        {
            Console.WriteLine("Usage: FindPackagesByNameAndPublisherSample.exe packageName publisherName");
            Console.WriteLine();

            return 1;
        }

        string inputPackageName = args[0];
        string inputPublisherName = args[1];

        Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

        try
        {
            IEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackages(inputPackageName, inputPublisherName);

            int packageCount = 0;
            foreach (var package in packages)
            {
                DisplayPackageInfo(package);
                DisplayPackageUsers(packageManager, package);

                Console.WriteLine();
                packageCount += 1;
            }

            if (packageCount < 1)
            {
                Console.WriteLine("No packages were found.");
            }

        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("packageManager.FindPackages() failed because access was denied. This program must be run from an elevated command prompt.");

            return 1;
        }
        catch (Exception ex)
        {
            Console.WriteLine("packageManager.FindPackages() failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return 1;
        }

        return 0;
    }
        private bool checkChannel5Installed()
        {
            PackageManager packageManager = new PackageManager();
            IEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser(WindowsIdentity.GetCurrent().User.ToString(), "Channel5.Demand5", "CN=D6547641-0EAB-4A6C-9559-B516C20C4050");

            if (packages.Count() > 0)
            {
                return true;
            }
            return false;
        }
        private bool checkChannel4Installed()
        {
            PackageManager packageManager = new PackageManager();
            IEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser(WindowsIdentity.GetCurrent().User.ToString(), "4onDemand.4oD", "CN=EB70642C-18B1-46B6-9902-87C95DC9F493");

            if (packages.Count() > 0)
            {
                return true;
            }
            return false;
        }
        private bool checkTVCatchupInstalled()
        {
            PackageManager packageManager = new PackageManager();
            IEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser(WindowsIdentity.GetCurrent().User.ToString(), "GZero.TVCatchupUK", "CN=3ED8ED7A-1E5C-4EAF-B5E5-F23FC7542213");

            if (packages.Count() > 0)
            {
                return true;
            }
            return false;
        }
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("FindPackagesByNameAndPublisher sample");
        Console.WriteLine();

        if (args.Length < 2)
        {
            Console.WriteLine("Usage: FindPackagesByNameAndPublisherSample.exe packageName publisherName");
            Console.WriteLine();

            return(1);
        }

        string inputPackageName   = args[0];
        string inputPublisherName = args[1];

        Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

        try
        {
            IEnumerable <Windows.ApplicationModel.Package> packages = (IEnumerable <Windows.ApplicationModel.Package>)packageManager.FindPackages(inputPackageName, inputPublisherName);

            int packageCount = 0;
            foreach (var package in packages)
            {
                DisplayPackageInfo(package);
                DisplayPackageUsers(packageManager, package);

                Console.WriteLine();
                packageCount += 1;
            }

            if (packageCount < 1)
            {
                Console.WriteLine("No packages were found.");
            }
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("packageManager.FindPackages() failed because access was denied. This program must be run from an elevated command prompt.");

            return(1);
        }
        catch (Exception ex)
        {
            Console.WriteLine("packageManager.FindPackages() failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return(1);
        }

        return(0);
    }
        private bool checkNetflixInstalled()
        {
            PackageManager packageManager = new PackageManager();

            IEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser(WindowsIdentity.GetCurrent().User.ToString(), "4DF9E0F8.Netflix", "CN=52120C15-ACFA-47FC-A7E3-4974DBA79445");

            if (packages.Count() > 0)
            {
                return true;
            }
            return false;
        }
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("FindPackagesByUserSecurityId sample");
        Console.WriteLine();

        if (args.Length < 1)
        {
            Console.WriteLine("Usage: FindPackagesByUserSecurityIdSample.exe userSID");
            Console.WriteLine();

            return 1;
        }

        string inputUserSecurityId = args[0];

        Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

        try
        {
            IEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser(inputUserSecurityId);

            int packageCount = 0;
            foreach (var package in packages)
            {
                DisplayPackageInfo(package);

                Console.WriteLine();
                packageCount += 1;
            }

            if (packageCount < 1)
            {
                Console.WriteLine("No packages were found.");
            }

        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("packageManager.FindPackagesForUser() failed because access was denied.");
            
            return 1;
        }
        catch (Exception ex)
        {
            Console.WriteLine("packageManager.FindPackagesForUser() failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return 1;
        }

        return 0;
    }
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("FindPackagesByUserSecurityId sample");
        Console.WriteLine();

        if (args.Length < 1)
        {
            Console.WriteLine("Usage: FindPackagesByUserSecurityIdSample.exe userSID");
            Console.WriteLine();

            return(1);
        }

        string inputUserSecurityId = args[0];

        Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

        try
        {
            IEnumerable <Windows.ApplicationModel.Package> packages = (IEnumerable <Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser(inputUserSecurityId);

            int packageCount = 0;
            foreach (var package in packages)
            {
                DisplayPackageInfo(package);

                Console.WriteLine();
                packageCount += 1;
            }

            if (packageCount < 1)
            {
                Console.WriteLine("No packages were found.");
            }
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("packageManager.FindPackagesForUser() failed because access was denied.");

            return(1);
        }
        catch (Exception ex)
        {
            Console.WriteLine("packageManager.FindPackagesForUser() failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return(1);
        }

        return(0);
    }
    private static void DisplayPackageUsers(Windows.Management.Deployment.PackageManager packageManager, Windows.ApplicationModel.Package package)
    {
        IEnumerable <Windows.Management.Deployment.PackageUserInformation> packageUsers = packageManager.FindUsers(package.Id.FullName);

        Console.Write("Users: ");

        foreach (var packageUser in packageUsers)
        {
            Console.Write("{0} ", SidToAccountName(packageUser.UserSecurityId));
        }

        Console.WriteLine();
    }
Beispiel #15
0
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("FindProvisionedPackages sample");
        Console.WriteLine();

        Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

        try
        {
            var packages = packageManager.FindProvisionedPackages();

            if (packages.Count == 0)
            {
                Console.WriteLine("No packages were found.");
            }
            else
            {
                foreach (var package in packages)
                {
                    DisplayPackageInfo(package);
                    Console.WriteLine();
                }
            }
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("packageManager.FindProvisionedPackages() failed because access was denied. This program must be run from an elevated command prompt.");

            return(1);
        }
        catch (Exception ex)
        {
            Console.WriteLine("packageManager.FindProvisionedPackages() failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return(1);
        }

        return(0);
    }
Beispiel #16
0
    public AppManager()
    {
        packageManager = new Windows.Management.Deployment.PackageManager();

        LoadApps();
    }
        static public void GetPackagesForCurrentUser(ref List<PackageInfo> packageInfos)
        {
            string currentUserSID = WindowsIdentity.GetCurrent().User.ToString();

            //---------------------------------------------------------------------------------------
            // Get iterator over all packages installed for this user

            // First, we need the PackageManager
    
            IAppxFactory appxFactory = (IAppxFactory) new AppxFactory();

            PackageManager packageManager = new PackageManager();

            IEnumerable<Package> packages = packageManager.FindPackagesForUser(currentUserSID);
            int cPackages = packages.Count();
            if (cPackages == 0)
                return;

            packageInfos = new List<PackageInfo>(cPackages);
            foreach (Package package in packages)
            {
                try
                {
                    // Find and load manifest
                    string manifestPath = package.InstalledLocation.Path + "\\AppxManifest.xml";

                    AppxPackaging.IStream manifestStream;
                    if (SHCreateStreamOnFileEx(
                        manifestPath,
                        0x00000040,     // STGM_READ | STGM_SHARE_DENY_NONE
                        0,              // file creation attributes
                        false,          // fCreate
                        null,           // reserved
                        out manifestStream) < 0)
                    {
                        // If we can't open the manifest for this package, skip it
                        continue;
                    }

                    IAppxManifestReader manifestReader;
                    manifestReader = appxFactory.CreateManifestReader(manifestStream);
                
                    IAppxManifestApplicationsEnumerator appsEnum = manifestReader.GetApplications();
                    if (appsEnum.GetHasCurrent() == 0)
                    {
                        // Packages with no apps exist, and are uninteresting.  Skip.
                        continue;
                    }

                    // Grab info from Package
                    PackageInfo packageInfo = new PackageInfo();
                    packageInfo.installedLocation = package.InstalledLocation.Path;

                    // Grab info from PackageID
                    PackageId packageId = package.Id;
                    packageInfo.architecture = packageId.Architecture.ToString();
                    packageInfo.fullName = packageId.FullName;
                    packageInfo.name = packageId.Name;
                    packageInfo.version = String.Format(
                        "{0}.{1}.{2}.{3}",
                        packageId.Version.Major,
                        packageId.Version.Minor,
                        packageId.Version.Build,
                        packageId.Version.Revision);

                    IAppxManifestProperties props = manifestReader.GetProperties();
                    packageInfo.publisher = props.GetStringValue("PublisherDisplayName");

                    // Figure out temp folder path

                    if (!GetACInfo(packageId.FamilyName, out packageInfo.acSid, out packageInfo.tempDir))
                        continue;

                    // Check to see if CLRHost.dll is listed as an InProcessServer extension.  If so,
                    // it may be a JS/CLR hybrid package, in which case we'll include all the
                    // AppUserModelIds we find later on.
                    bool usesClrHostExtension = false;
                    try
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(manifestPath);
                        XPathNavigator docNavigator = xmlDoc.CreateNavigator();
                        XmlNamespaceManager mgr = new XmlNamespaceManager(docNavigator.NameTable);
                        mgr.AddNamespace("pm", "http://schemas.microsoft.com/appx/2010/manifest");
                        XPathNodeIterator iterator = docNavigator.Select("/pm:Package/pm:Extensions/pm:Extension/pm:InProcessServer/pm:Path", mgr);
                        foreach (XPathNavigator selectedNodeNavigator in iterator)
                        {
                            if (selectedNodeNavigator.Value.IndexOf("clrhost.dll", StringComparison.CurrentCultureIgnoreCase) != -1)
                            {
                                usesClrHostExtension = true;
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // Intentionally fall through. Any error encountered determining
                        // whether this is a hybrid package should just result in us
                        // assuming it isn't one.
                        Debug.Assert(!usesClrHostExtension);
                    }

                    // For each app in the package, get its App User Model ID
                    packageInfo.appInfoList = new List<AppInfo>(5);
                    while (appsEnum.GetHasCurrent() != 0)
                    {
                        IAppxManifestApplication app = appsEnum.GetCurrent();
                        AppInfo appInfo = new AppInfo();
                        appInfo.userModelId = app.GetAppUserModelId();
                        appInfo.exeName = app.GetStringValue("Executable");
                        IAppxManifestResourcesEnumerator resourcesEnum = manifestReader.GetResources();
                        if ((appInfo.userModelId != null) && 
                            ((appInfo.exeName != null) || usesClrHostExtension))
                        {
                            // Only care about apps with an app user model ID
                            // (which we need for activation) and either an exe name (to display to user) or
                            // evidence that a CLR extension is used
                            if (appInfo.exeName == null)
                            {
                                appInfo.exeName = "(no executable)";
                            }
                            packageInfo.appInfoList.Add(appInfo);
                        }
                        appsEnum.MoveNext();
                    }

                    if (packageInfo.appInfoList.Count > 0)
                    {
                        // Only care about packages that contain apps we care about
                        packageInfos.Add(packageInfo);
                    }
                }
                catch (Exception)
                {
                    // If there are any problems with the package we're currently
                    // iterating over, just skip it and continue with the next package
                    // in the enumeration. For example, can't open the manifest
                    // or can't find installed location for the package (b/c the
                    // developer manually moved files around), skip it
                }
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            PackageManager        packageManager = new Windows.Management.Deployment.PackageManager();
            IEnumerable <Package> packages       =
                packageManager.FindPackagesForUser(WindowsIdentity.GetCurrent().User.Value);

            int key     = 1;
            var applist = new List <App> {
            };

            foreach (Package package in packages)
            {
                try
                {
                    if (!package.IsFramework && package.InstalledLocation.Path.StartsWith("C:\\Program Files\\WindowsApps"))
                    {
                        // ---- Package Family Name
                        //package.Id.FamilyName

                        // ---- AppManifest(AppId)
                        XmlDocument doc         = new XmlDocument();
                        string      AppManifest = System.IO.Path.Combine(package.InstalledLocation.Path, "AppxManifest.xml");
                        doc.Load(AppManifest);
                        XmlNodeList Application = doc.GetElementsByTagName("Application");
                        string      AppId       = Application[0].Attributes["Id"].Value;
                        //AppId

                        // ---- Get DisplayName
                        XmlNodeList VisualElements   = doc.GetElementsByTagName("uap:VisualElements");
                        string      DisplayName      = VisualElements[0].Attributes["DisplayName"].Value;
                        string      FinalDisplayName = GetDisplayName(DisplayName, package.Id.Name, package.InstalledLocation.Path);
                        //FinalDisplayName

                        // ---- Get IconPath
                        int    max_Icon_Size                = 0;
                        int    max_Unplated_Icon_Size       = 0;
                        int    max_Light_Unplated_Icon_Size = 0;
                        string iconPath                 = "";
                        string unplated_Icon_Path       = null;
                        string light_Unplated_Icon_Path = null;
                        string icon44x44                = VisualElements[0].Attributes["Square44x44Logo"].Value;
                        string baseIcon44x44            = Path.GetDirectoryName(icon44x44);
                        string finalIcon44x44Dir        = Path.Combine(package.InstalledLocation.Path, baseIcon44x44);
                        string icon44x44BaseName        = Path.GetFileNameWithoutExtension(icon44x44);
                        var    dirFileList              = Directory.GetFiles(finalIcon44x44Dir);

                        foreach (string file in dirFileList)
                        {
                            string fileBaseName = Path.GetFileNameWithoutExtension(file);
                            if (fileBaseName.Contains(icon44x44BaseName))
                            {
                                // Light Unplated Images
                                if (fileBaseName.Contains("altform-lightunplated") && !fileBaseName.Contains("contrast-black") && !fileBaseName.Contains("contrast-white"))
                                {
                                    string props = fileBaseName.Split('.')[1];
                                    int    size  = Convert.ToInt32(props.Split('_')[0].Split('-')[1]);
                                    if (size > max_Light_Unplated_Icon_Size)
                                    {
                                        max_Light_Unplated_Icon_Size = size;
                                        light_Unplated_Icon_Path     = file;
                                    }
                                }
                                // Unplated Images
                                else if (fileBaseName.Contains("altform-unplated") && !fileBaseName.Contains("contrast-black") && !fileBaseName.Contains("contrast-white"))
                                {
                                    string props = fileBaseName.Split('.')[1];
                                    int    size  = Convert.ToInt32(props.Split('_')[0].Split('-')[1]);
                                    if (size > max_Unplated_Icon_Size)
                                    {
                                        max_Unplated_Icon_Size = size;
                                        unplated_Icon_Path     = file;
                                    }
                                }
                                // Normal Images
                                else if (!fileBaseName.Contains("contrast-black") && !fileBaseName.Contains("contrast-white"))
                                {
                                    string props = fileBaseName.Split('.')[1];
                                    int    size  = Convert.ToInt32(props.Split('_')[0].Split('-')[1]);
                                    if (size > max_Icon_Size)
                                    {
                                        max_Icon_Size = size;
                                        iconPath      = file;
                                    }
                                }
                            }
                        }
                        //iconPath && lightModeIconPath

                        // ---- DateCreated
                        DateTime baseDate        = new DateTime(1970, 01, 01);
                        var      toDate          = package.InstalledLocation.DateCreated;
                        double   numberOfSeconds = toDate.Subtract(baseDate).TotalSeconds;
                        //numberOfSeconds

                        if (FinalDisplayName != "")
                        {
                            applist.Add(new App {
                                id                = key,
                                Name              = FinalDisplayName,
                                AppId             = AppId,
                                PFN               = package.Id.FamilyName,
                                Icon              = iconPath,
                                unplatedIcon      = unplated_Icon_Path,
                                lightUnplatedIcon = light_Unplated_Icon_Path,
                                DateCreated       = (int)numberOfSeconds
                            });
                            key = key + 1;
                        }
                    }
                }
                catch (Exception e)
                {
                    //Console.WriteLine(e);
                }
            }

            string DataPath = args[0];

            if (DataPath == "/test")
            {
                string JsonAppList = JsonConvert.SerializeObject(applist);
                Console.Write(JsonAppList);
            }
            else
            {
                string JsonAppList = JsonConvert.SerializeObject(applist);
                using (StreamWriter JsonFile = File.CreateText(DataPath))
                {
                    JsonFile.Write(JsonAppList);
                }
                Console.WriteLine("Processing StoreApps Data Success");
            }
        }
Beispiel #19
0
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("RemovePackage sample");
        Console.WriteLine();

        if (args.Length < 1)
        {
            Console.WriteLine("Usage: RemovePackageSample.exe packageFullname");
            return(1);
        }

        string inputPackageFullName = args[0];
        int    returnValue          = 0;

        try
        {
            Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

            Windows.Foundation.IAsyncOperationWithProgress <DeploymentResult, DeploymentProgress> deploymentOperation = packageManager.RemovePackageAsync(inputPackageFullName);

            ManualResetEvent opCompletedEvent = new ManualResetEvent(false); // this event will be signaled when the deployment operation has completed.

            deploymentOperation.Completed = (depProgress, status) => { opCompletedEvent.Set(); };

            Console.WriteLine("Removing package {0}", inputPackageFullName);

            Console.WriteLine("Waiting for removal to complete...");

            opCompletedEvent.WaitOne();

            if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Error)
            {
                Windows.Management.Deployment.DeploymentResult deploymentResult = deploymentOperation.GetResults();
                Console.WriteLine("Removal Error: {0}", deploymentOperation.ErrorCode);
                Console.WriteLine("Detailed Error Text: {0}", deploymentResult.ErrorText);
                returnValue = 1;
            }
            else if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Canceled)
            {
                Console.WriteLine("Removal Canceled");
            }
            else if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Completed)
            {
                Console.WriteLine("Removal succeeded!");
            }
            else
            {
                returnValue = 1;
                Console.WriteLine("Removal status unknown");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("RemovePackageSample failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return(1);
        }

        return(returnValue);
    }
    public static int Main(string[] args)
    {
        Console.WriteLine("Copyright (c) Microsoft Corporation. All rights reserved.");
        Console.WriteLine("AddPackage sample");
        Console.WriteLine();

        if (args.Length < 1)
        {
            Console.WriteLine("Usage: AddPackageSample.exe packageUri");
            return 1;
        }

        string inputPackageUri = args[0];        
        int returnValue = 0;

        try
        {
            Uri packageUri = new Uri(inputPackageUri);            
            
            Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();

            Windows.Foundation.IAsyncOperationWithProgress<DeploymentResult, DeploymentProgress> deploymentOperation = packageManager.AddPackageAsync(packageUri, null, Windows.Management.Deployment.DeploymentOptions.None);

            ManualResetEvent opCompletedEvent = new ManualResetEvent(false); // this event will be signaled when the deployment operation has completed.

            deploymentOperation.Completed = (depProgress, status) => { opCompletedEvent.Set(); };

            Console.WriteLine("Installing package {0}", inputPackageUri);

            Console.WriteLine("Waiting for installation to complete...");

            opCompletedEvent.WaitOne();

            if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Error)
            {
                Windows.Management.Deployment.DeploymentResult deploymentResult = deploymentOperation.GetResults();
                Console.WriteLine("Installation Error: {0}", deploymentOperation.ErrorCode);
                Console.WriteLine("Detailed Error Text: {0}", deploymentResult.ErrorText);
                returnValue = 1;
            }
            else if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Canceled)
            {
                Console.WriteLine("Installation Canceled");
            }
            else if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Completed)
            {
                Console.WriteLine("Installation succeeded!");
            }
            else
            {
                returnValue = 1;
                Console.WriteLine("Installation status unknown");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("AddPackageSample failed, error message: {0}", ex.Message);
            Console.WriteLine("Full Stacktrace: {0}", ex.ToString());

            return 1;
        }

        return returnValue;
    }
Beispiel #21
0
 public void Cleanup()
 {
     var packageManager = new PackageManager();
     var result = packageManager.RemovePackageAsync(packageFullName, RemovalOptions.PreserveApplicationData);
     var completed = new AutoResetEvent(false);
     result.Completed = (waitResult, status) => completed.Set();
     completed.WaitOne();
 }
Beispiel #22
0
 private static void RegisterAppx(Uri manifestUri)
 {
     var packageManager = new PackageManager();
     var result = packageManager.RegisterPackageAsync(manifestUri, null, DeploymentOptions.DevelopmentMode);
     var completed = new AutoResetEvent(false);
     result.Completed = (waitResult, status) => completed.Set();
     completed.WaitOne();
 }
        private void comboBox_Loaded(object sender, RoutedEventArgs e)
        {
            var apps = new List<Model>(10);

            var getAppsTask = Task.Run(() =>
            {
                if (comboBox.ItemsSource != null) return;

                var currentUser = WindowsIdentity.GetCurrent();
                if (currentUser?.User == null) return;
                var sid = currentUser.User.ToString();

                var packageManager = new PackageManager();
                var packages = packageManager.FindPackagesForUser(sid);

                if (Environment.OSVersion.Version.Major == 10)
                {
                    var appXInfos = GetAppXInfosFromReg();
                    if (appXInfos == null || appXInfos.Count == 0) return;

                    foreach (var package in packages.Where(package => !package.IsFramework))
                    {
                        using (
                            var key =
                                Registry.ClassesRoot.OpenSubKey(
                                    $@"Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\SystemAppData\{
                                        package.Id.FamilyName}\SplashScreen\"))
                        {
                            var appUserModelIds =
                                key?.GetSubKeyNames().Where(k => k.StartsWith(package.Id.FamilyName));
                            if (appUserModelIds == null) continue;

                            foreach (string appUserModelId in appUserModelIds)
                            {
                                Model model = new Model();
                                string backgroundColor, displayName, logo;
                                if (!ReadAppxInfoFromXml(package.InstalledLocation.Path, out displayName, out logo, out backgroundColor))
                                    continue;

                                var convertFromString = ColorConverter.ConvertFromString(backgroundColor);
                                if (convertFromString != null)
                                {
                                    model.BackgroundColor = new SolidColorBrush((Color)convertFromString);
                                    model.BackgroundColor.Freeze();
                                }

                                if (appXInfos.ContainsKey(appUserModelId))
                                {
                                    var appXInfo = appXInfos[appUserModelId];

                                    displayName = ExtractDisplayName(package, appXInfo.ApplicationName);
                                    if (string.IsNullOrEmpty(displayName)) continue;

                                    logo = GetDisplayIconPath(package.InstalledLocation.Path, appXInfo.ApplicationIcon);

                                    model.Logo = logo;
                                    model.AppInfo = new KeyValuePair<string, string>(appUserModelId, displayName);
                                }
                                else
                                {
                                    using (var subKey = key.OpenSubKey(appUserModelId))
                                    {
                                        var appName = subKey?.GetValue("AppName");
                                        if (appName == null) continue;
                                        displayName = ExtractDisplayName(package, appName.ToString());
                                        if (string.IsNullOrEmpty(displayName)) continue;
                                        model.AppInfo = new KeyValuePair<string, string>(appUserModelId, displayName);

                                        logo = ExtractDisplayIcon(package.InstalledLocation.Path, logo);
                                        model.Logo = logo;
                                    }
                                }
                                apps.Add(model);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var package in packages.Where(package => !package.IsFramework))
                    {
                        string displayName, logo, backgroundColor;
                        if (
                            !ReadAppxInfoFromXml(package.InstalledLocation.Path, out displayName, out logo,
                                out backgroundColor))
                            continue;

                        displayName = ExtractDisplayName(package.InstalledLocation.Path, package.Id.Name, displayName);
                        logo = ExtractDisplayIcon(package.InstalledLocation.Path, logo);

                        var convertFromString = ColorConverter.ConvertFromString(backgroundColor);
                        if (convertFromString == null) continue;
                        var model = new Model
                        {
                            AppInfo = new KeyValuePair<string, string>(GetAppUserModelId(package.Id.FullName), displayName),
                            BackgroundColor = new SolidColorBrush((Color)convertFromString),
                            Logo = logo
                        };
                        model.BackgroundColor.Freeze();
                        apps.Add(model);
                    }
                }
            });
            getAppsTask.ContinueWith(task =>
            {
                string message = null;
                if (task.Exception != null)
                {
                    foreach (var item in task.Exception.InnerExceptions)
                    {
                        Logging.LogException(item);
                        message = item.Message;
                    }
                }

                comboBox.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (message != null)
                        {
                            TipTextBlock.Text = message;
                            return;
                        }
                        if (apps.Count != 0)
                            comboBox.ItemsSource = apps.OrderBy(app => app.AppInfo.Value).ToList();

                        var launchApp = DataContext as LaunchApp;
                        if (launchApp != null)
                        {
                            comboBox.SelectedItem = (comboBox.ItemsSource as List<Model>)?.Find(m => m.AppInfo.Equals(launchApp.AppInfo));
                        }
                        TipTextBlock.Text = LocalizationProvider.Instance.GetTextValue("CorePlugins.LaunchApp.Tip");
                        comboBox.Visibility = Visibility.Visible;
                    }));
            });
        }
Beispiel #24
0
 private AppRegistrationService()
 {
     _packageManager = new Windows.Management.Deployment.PackageManager();
 }
Beispiel #25
0
        private static IEnumerable<Package> CurrentUserPackages()
        {
            var user = WindowsIdentity.GetCurrent().User;

            if (user != null)
            {
                var userSecurityId = user.Value;
                var packageManager = new PackageManager();
                var packages = packageManager.FindPackagesForUser(userSecurityId);
                packages =
                    packages.Where(
                        p => !p.IsFramework && !p.IsDevelopmentMode && !string.IsNullOrEmpty(p.InstalledLocation.Path));
                return packages;
            }
            else
            {
                return new Package[] { };
            }
        }
 /// <summary>
 /// Installs the App
 /// </summary>
 /// <returns>bool Installation status</returns>
 public static bool InstallAppBundle(string appBundleUri)
 {
     bool returnValue = true;
     try
     {
         Uri packageUri = new Uri(appBundleUri);
         Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();
         Windows.Foundation.IAsyncOperationWithProgress<DeploymentResult, DeploymentProgress> deploymentOperation = packageManager.AddPackageAsync(packageUri, null, Windows.Management.Deployment.DeploymentOptions.None);
         ManualResetEvent opCompletedEvent = new ManualResetEvent(false); // this event will be signaled when the deployment operation has completed.
         deploymentOperation.Completed = (depProgress, status) => { opCompletedEvent.Set(); };
         Logger.InsertLogLine(string.Format("Installing package {0}", appBundleUri));
         Logger.InsertLogLine("Waiting for installation to complete...");
         opCompletedEvent.WaitOne();
         if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Error)
         {
             Windows.Management.Deployment.DeploymentResult deploymentResult = deploymentOperation.GetResults();
             Logger.InsertLogLine(string.Format("Installation Error: {0}", deploymentOperation.ErrorCode));
             Logger.InsertLogLine(string.Format("Detailed Error Text: {0}", deploymentResult.ErrorText));
             returnValue = false;
         }
         else if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Canceled)
         {
             Logger.InsertLogLine("Installation Canceled");
             returnValue = false;
         }
         else if (deploymentOperation.Status == Windows.Foundation.AsyncStatus.Completed)
         {
             Logger.InsertLogLine("Installation succeeded!");
         }
         else
         {
             returnValue = false;
             Logger.InsertLogLine("Installation status unknown");
         }
     }
     catch (Exception ex)
     {
         Logger.InsertLogLine(string.Format("AddPackageSample failed, error message: {0}", ex.Message));
         Logger.InsertLogLine(string.Format("Full Stacktrace: {0}", ex.ToString()));
         return false;
     }
     return returnValue;
 }