Esempio n. 1
0
        public new static PackageInstance Random()
        {
            var e = new PackageInstance();

            e.SetRandomValues();
            return(e);
        }
Esempio n. 2
0
        protected void deleteFileFromPackage(object sender, EventArgs e)
        {
            TextBox filePathControl = (TextBox)((Control)sender).Parent.FindControl("packageFilePath");

            filePathControl.Text = "";

            string tmpFilePathString = "";

            foreach (RepeaterItem rItem in packageFilesRepeater.Items)
            {
                string tmpFFFF = ((TextBox)rItem.FindControl("packageFilePath")).Text;
                if (tmpFFFF.Trim() != "")
                {
                    tmpFilePathString += tmpFFFF + "�";
                }
            }

            CreatedPackage  createdPackage = CreatedPackage.GetById(int.Parse(Request.QueryString["id"]));
            PackageInstance pack           = createdPackage.Data;

            pack.Files = new List <string>(tmpFilePathString.Trim('�').Split('�'));
            pack.Files.TrimExcess();

            createdPackage.Save();

            packageFilesRepeater.DataSource = pack.Files;
            packageFilesRepeater.DataBind();
        }
Esempio n. 3
0
        public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc) {

            string packageName = package.Name;
            string packageGuid = package.PackageGuid;
            string description = package.Readme;
            string packageFile = package.PackagePath;


            System.IO.FileStream fs1 = null;

            try {

                byte[] pack = new byte[0];
                fs1 = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read);
                pack = new byte[fs1.Length];
                fs1.Read(pack, 0, (int)fs1.Length);
                fs1.Close();
                fs1 = null;

                byte[] thumb = new byte[0]; //todo upload thumbnail... 

                return Webservice.SubmitPackage(m_guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description);
            } catch (Exception ex) {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, -1, ex.ToString());

                return SubmitStatus.Error;
            }
        }
Esempio n. 4
0
        public static async Task <IList <PackageInstance> > GetPackageInstancesAsync(string WuCategoryID)
        {
            IList <PackageInstance> PackageInstances = new List <PackageInstance>();
            HttpContent             httpContent      = new StringContent(String.Format(GetResourceTextFile("WUIDRequest.xml"), await GetCookieAsync(), WuCategoryID), Encoding.UTF8, "application/soap+xml"); //Load in the Xml for this FE3 request and format it a cookie and the provided WuCategoryID.
            HttpRequestMessage      httpRequest      = new HttpRequestMessage();

            httpRequest.RequestUri = Endpoints.FE3Delivery;
            httpRequest.Content    = httpContent;
            httpRequest.Method     = HttpMethod.Post;
            HttpResponseMessage httpResponse = await _httpClient.SendAsync(httpRequest, new System.Threading.CancellationToken());

            string content = await httpResponse.Content.ReadAsStringAsync();

            content = HttpUtility.HtmlDecode(content);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(content);
            XmlNodeList nodes = doc.GetElementsByTagName("AppxMetadata");

            foreach (XmlNode node in nodes)
            {
                if (node.Attributes.Count >= 3)
                {
                    PackageInstance package = new PackageInstance(node.Attributes.GetNamedItem("PackageMoniker").Value, new Uri("http://test.com"), Utilities.TypeHelpers.StringToPackageType(node.Attributes.GetNamedItem("PackageType").Value));
                    PackageInstances.Add(package);
                }
            }
            return(PackageInstances);
        }
Esempio n. 5
0
        public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc)
        {

            string packageName = package.Name;
            string packageGuid = package.PackageGuid;
            string description = package.Readme;
            string packageFile = package.PackagePath;


            System.IO.FileStream fs1 = null;

            try
            {

                byte[] pack = new byte[0];
                fs1 = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read);
                pack = new byte[fs1.Length];
                fs1.Read(pack, 0, (int) fs1.Length);
                fs1.Close();
                fs1 = null;

                byte[] thumb = new byte[0]; //todo upload thumbnail... 

                return Webservice.SubmitPackage(Guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description);
            }
            catch (Exception ex)
            {
                LogHelper.Error<Repository>("An error occurred in SubmitPackage", ex);

                return SubmitStatus.Error;
            }
        }
Esempio n. 6
0
        public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc)
        {
            string packageName = package.Name;
            string packageGuid = package.PackageGuid;
            string description = package.Readme;
            string packageFile = package.PackagePath;


            System.IO.FileStream fs1 = null;

            try {
                byte[] pack = new byte[0];
                fs1  = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read);
                pack = new byte[fs1.Length];
                fs1.Read(pack, 0, (int)fs1.Length);
                fs1.Close();
                fs1 = null;

                byte[] thumb = new byte[0]; //todo upload thumbnail...

                return(Webservice.SubmitPackage(m_guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description));
            } catch (Exception ex) {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, -1, ex.ToString());

                return(SubmitStatus.Error);
            }
        }
        public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc)
        {
            string packageName = package.Name;
            string packageGuid = package.PackageGuid;
            string description = package.Readme;
            string packageFile = package.PackagePath;


            System.IO.FileStream fs1 = null;

            try
            {
                byte[] pack = new byte[0];
                fs1  = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read);
                pack = new byte[fs1.Length];
                fs1.Read(pack, 0, (int)fs1.Length);
                fs1.Close();
                fs1 = null;

                byte[] thumb = new byte[0]; //todo upload thumbnail...

                return(Webservice.SubmitPackage(Guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description));
            }
            catch (Exception ex)
            {
                LogHelper.Error <Repository>("An error occurred in SubmitPackage", ex);

                return(SubmitStatus.Error);
            }
        }
Esempio n. 8
0
        public static ToastNotification GenerateProgressToast(PackageInstance package, ProductDetails product)
        {
            var content = new ToastContent()
            {
                Visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = new BindableString("progressTitle")
                            },
                            new AdaptiveProgressBar()
                            {
                                Value  = new BindableProgressBarValue("progressValue"),
                                Title  = new BindableString("progressVersion"),
                                Status = new BindableString("progressStatus")
                            }
                        },
                        AppLogoOverride = new ToastGenericAppLogo()
                        {
                            Source = product.Images.FindLast(i => i.ImageType == MicrosoftStore.Enums.ImageType.Logo).Url
                        }
                    }
                },
                // TODO: Add cancel and pause functionality
                //Actions = new ToastActionsCustom()
                //{
                //    Buttons =
                //    {
                //        new ToastButton("Pause", $"action=pauseDownload&packageName={package.PackageMoniker}")
                //        {
                //            ActivationType = ToastActivationType.Background
                //        },
                //        new ToastButton("Cancel", $"action=cancelDownload&packageName={package.PackageMoniker}")
                //        {
                //            ActivationType = ToastActivationType.Background
                //        }
                //    }
                //},
                Launch = $"action=viewDownload&packageName={package.PackageMoniker}",
            };

            var notif = new ToastNotification(content.GetXml());

            notif.Data = new NotificationData(new Dictionary <string, string>()
            {
                { "progressTitle", product.Title },
                { "progressVersion", package.Version.ToString() },
                { "progressStatus", "Downloading..." }
            });
            notif.Tag = package.PackageFamily;
            //notif.Group = "App Downloads";
            return(notif);
        }
Esempio n. 9
0
        public static ToastNotification GenerateInstallSuccessToast(PackageInstance package, ProductDetails product)
        {
            var content = new ToastContentBuilder().SetToastScenario(ToastScenario.Reminder)
                          .AddToastActivationInfo($"action=viewEvent&eventId={package.PackageMoniker}", ToastActivationType.Foreground)
                          .AddText(product.ShortTitle)
                          .AddText(product.Title + " just got installed.")
                          .AddAppLogoOverride(product.Images.FindLast(i => i.ImageType == MicrosoftStore.Enums.ImageType.Logo).Uri, addImageQuery: false)
                          .Content;

            return(new ToastNotification(content.GetXml()));
        }
Esempio n. 10
0
        public ProblemSpaceTree InstantiateSolutionElements(ModelEntityRepository repo)
        {
            var instantiations = from instantiation in ElementInstantiations
                                 select PackageInstance.Fold(
                (solutionPackage) =>
                instantiation.CreateInstanceIfMissing(repo, solutionPackage),
                () => instantiation);

            var children = Children.Select(c => c.InstantiateSolutionElements(repo));

            return(new ProblemSpaceTree(Package, PackageInstance, instantiations, Diagrams, children));
        }
Esempio n. 11
0
        private void CreateSolutionDiagrams(ModelEntityRepository repo, IEnumerable <ElementInstantiation> instantiations)
        {
            PackageInstance.Do(solutionPackage =>
            {
                Diagrams.ForEach(problemDiagram =>
                {
                    var solutionDiagram = repo.Create(problemDiagram.Name, DiagramTypes.SolutionOverview, solutionPackage, ADTechnology.Technologies.AD.ID);
                    CopyDiagramObjects(problemDiagram, solutionDiagram, instantiations);
                });
            });

            Children.ForEach(c => c.CreateSolutionDiagrams(repo, instantiations));
        }
Esempio n. 12
0
        public void activeSP([FromBody] ClientPackage forSP) //remember
        {
            db.Configuration.ProxyCreationEnabled = false;

            // string sp = "Activate Service Package";
            DateTime Now = DateTime.Now;

            //refiloeknowsbest
            Sale sales = new Sale();

            sales.ClientID = forSP.Sale.ClientID;
            //sales.Decription = activeSP;     // this is where the sale type is specific
            sales.Payment = forSP.Sale.Payment;

            //sales.SaleType = type id of activate

            sales.PaymentTypeID = forSP.Sale.PaymentTypeID;
            sales.StatusID      = 2;
            sales.Date          = Now;
            //sales.Description = sp;
            db.Sales.Add(sales);
            db.SaveChanges();

            int SaleID = db.Sales.Where(zz => zz.ClientID == forSP.Sale.ClientID && zz.SaleTypeID == forSP.Sale.SaleTypeID).Select(zz => zz.SaleID).LastOrDefault();

            //ading to client sdjfnjvn thingy
            ClientPackage CP = new ClientPackage();

            CP.SaleID     = SaleID;
            CP.PackageID  = forSP.ServicePackage.PackageID;
            CP.Date       = Now;
            CP.ExpiryDate = Now.AddMonths(forSP.ServicePackage.Duration);
            db.ClientPackages.Add(CP);
            db.SaveChanges();

            //**********instance for the service package*****************
            int loop = forSP.ServicePackage.Quantity;

            for (int j = 0; j <= loop; j++)
            {
                PackageInstance addInstance = new PackageInstance();
                addInstance.PackageID = CP.PackageID;
                addInstance.SaleID    = SaleID;
                addInstance.StatusID  = 1;
                db.PackageInstances.Add(addInstance);
                db.SaveChanges();
            }
        }
Esempio n. 13
0
        protected void addFileToPackage(object sender, EventArgs e)
        {
            string newPath = packageFilePathNew.Text;

            if (newPath.Trim() != "")
            {
                CreatedPackage  createdPackage = CreatedPackage.GetById(int.Parse(Request.QueryString["id"]));
                PackageInstance pack           = createdPackage.Data;

                pack.Files.Add(newPath);

                createdPackage.Save();

                packageFilePathNew.Text = "";

                packageFilesRepeater.DataSource = pack.Files;
                packageFilesRepeater.DataBind();
            }
        }
Esempio n. 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                createdPackage = CreatedPackage.GetById(int.Parse(Request.QueryString["id"]));
                pack           = createdPackage.Data;

                /* CONTENT */

                cp = new ContentPicker();
                content.Controls.Add(cp);

                if (string.IsNullOrEmpty(pack.PackagePath) == false)
                {
                    packageUmbFile.Text = " &nbsp; <a href='" + Page.ResolveClientUrl(pack.PackagePath) + "'>Download</a>";
                }
                else
                {
                    packageUmbFile.Text = "<em>This package is not published</em>";
                }

                if (Page.IsPostBack == false)
                {
                    ClientTools
                    .SyncTree("-1,created," + createdPackage.Data.Id, false);

                    packageAuthorName.Text  = pack.Author;
                    packageAuthorUrl.Text   = pack.AuthorUrl;
                    packageLicenseName.Text = pack.License;
                    packageLicenseUrl.Text  = pack.LicenseUrl;
                    packageName.Text        = pack.Name;
                    packageReadme.Text      = pack.Readme;
                    packageVersion.Text     = pack.Version;
                    packageUrl.Text         = pack.Url;
                    iconUrl.Text            = pack.IconUrl;
                    umbracoVersion.Text     = pack.UmbracoVersion != null?pack.UmbracoVersion.ToString(3) : string.Empty;

                    /*ACTIONS XML*/
                    tb_actions.Text = pack.Actions;

                    cp.Value = pack.ContentNodeId.ToString();

                    //startNode.Value = pack.ContentNodeId.ToString();

                    packageContentSubdirs.Checked = pack.ContentLoadChildNodes;


                    /*TEMPLATES */
                    var nTemplates = Services.FileService.GetTemplates();
                    //Template[] umbTemplates = Template.GetAllAsList().ToArray();
                    foreach (var tmp in nTemplates)
                    {
                        ListItem li = new ListItem(tmp.Name, tmp.Id.ToString());

                        if (pack.Templates.Contains(tmp.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        templates.Items.Add(li);
                    }

                    /* DOC TYPES */
                    // fixme - media types? member types?
                    var nContentTypes = Services.ContentTypeService.GetAll();
                    //DocumentType[] docs = DocumentType.GetAllAsList().ToArray();
                    foreach (var dc in nContentTypes)
                    {
                        ListItem li = new ListItem(dc.Name, dc.Id.ToString());
                        if (pack.Documenttypes.Contains(dc.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        documentTypes.Items.Add(li);
                    }

                    /*Stylesheets */
                    var sheets = Services.FileService.GetStylesheets();
                    foreach (var st in sheets)
                    {
                        if (string.IsNullOrEmpty(st.Name) == false)
                        {
                            var li = new ListItem(st.Alias, st.Name);
                            if (pack.Stylesheets.Contains(st.Name))
                            {
                                li.Selected = true;
                            }
                            stylesheets.Items.Add(li);
                        }
                    }

                    /* MACROS */
                    var nMacros = Services.MacroService.GetAll();
                    //Macro[] umbMacros = Macro.GetAll();
                    foreach (var m in nMacros)
                    {
                        ListItem li = new ListItem(m.Name, m.Id.ToString());
                        if (pack.Macros.Contains(m.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        macros.Items.Add(li);
                    }

                    /*Langauges */
                    var nLanguages = Services.LocalizationService.GetAllLanguages();
                    //Language[] umbLanguages = Language.getAll;
                    foreach (var l in nLanguages)
                    {
                        ListItem li = new ListItem(l.CultureName, l.Id.ToString());
                        if (pack.Languages.Contains(l.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        languages.Items.Add(li);
                    }

                    /*Dictionary Items*/
                    var umbDictionary = Services.LocalizationService.GetRootDictionaryItems();
                    foreach (var d in umbDictionary)
                    {
                        string liName   = d.ItemKey;
                        var    children = Services.LocalizationService.GetDictionaryItemChildren(d.Key);
                        if (children.Any())
                        {
                            liName += " <small>(Including all child items)</small>";
                        }

                        var li = new ListItem(liName, d.Id.ToString());

                        if (pack.DictionaryItems.Contains(d.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        dictionary.Items.Add(li);
                    }

                    //TODO: Fix this with the new services and apis! and then remove since this should all be in angular

                    ///*Data types */
                    //cms.businesslogic.datatype.DataTypeDefinition[] umbDataType = cms.businesslogic.datatype.DataTypeDefinition.GetAll();

                    // sort array by name
                    //Array.Sort(umbDataType, delegate(cms.businesslogic.datatype.DataTypeDefinition umbDataType1, cms.businesslogic.datatype.DataTypeDefinition umbDataType2)
                    //{
                    //    return umbDataType1.Text.CompareTo(umbDataType2.Text);
                    //});

                    //foreach (cms.businesslogic.datatype.DataTypeDefinition umbDtd in umbDataType)
                    //{

                    //    ListItem li = new ListItem(umbDtd.Text, umbDtd.Id.ToString());

                    //    if (pack.DataTypes.Contains(umbDtd.Id.ToString()))
                    //        li.Selected = true;

                    //    cbl_datatypes.Items.Add(li);
                    //}

                    /* FILES */
                    packageFilesRepeater.DataSource = pack.Files;
                    packageFilesRepeater.DataBind();

                    packageControlPath.Text = pack.LoadControl;
                }
                else
                {
                    ClientTools
                    .SyncTree("-1,created," + createdPackage.Data.Id, true);
                }
            }
        }
Esempio n. 15
0
        public static async Task <bool> InstallPackage(PackageInstance package, ProductDetails product, bool?useAppInstaller = null)
        {
            ToastNotification finalNotif = GenerateInstallSuccessToast(package, product);
            bool isSuccess = true;

            try
            {
                (await DownloadPackage(package, product, false)).Deconstruct(out var installer, out var progressToast);

                PackageManager pkgManager = new PackageManager();
                Progress <DeploymentProgress> progressCallback = new Progress <DeploymentProgress>(prog =>
                {
                    ToastNotificationManager.GetDefault().CreateToastNotifier().Update(
                        new NotificationData(new Dictionary <string, string>()
                    {
                        { "progressValue", (prog.percentage / 100).ToString() },
                        { "progressStatus", "Installing..." }
                    }),
                        progressToast.Tag
                        );
                });

                if (Settings.Default.UseAppInstaller || (useAppInstaller.HasValue && useAppInstaller.Value))
                {
                    // Pass the file to App Installer to install it
                    Uri launchUri = new Uri("ms-appinstaller:?source=" + installer.Path);
                    switch (await Launcher.QueryUriSupportAsync(launchUri, LaunchQuerySupportType.Uri))
                    {
                    case LaunchQuerySupportStatus.Available:
                        isSuccess = await Launcher.LaunchUriAsync(launchUri);

                        if (!isSuccess)
                        {
                            finalNotif = GenerateInstallFailureToast(package, product, new Exception("Failed to launch App Installer."));
                        }
                        break;

                    case LaunchQuerySupportStatus.AppNotInstalled:
                        finalNotif = GenerateInstallFailureToast(package, product, new Exception("App Installer is not available on this device."));
                        isSuccess  = false;
                        break;

                    case LaunchQuerySupportStatus.AppUnavailable:
                        finalNotif = GenerateInstallFailureToast(package, product, new Exception("App Installer is not available right now, try again later."));
                        isSuccess  = false;
                        break;

                    case LaunchQuerySupportStatus.Unknown:
                    default:
                        finalNotif = GenerateInstallFailureToast(package, product, new Exception("An unknown error occured."));
                        isSuccess  = false;
                        break;
                    }
                }
                else
                {
                    // Attempt to install the downloaded package
                    var result = await pkgManager.AddPackageByUriAsync(
                        new Uri(installer.Path),
                        new AddPackageOptions()
                    {
                        ForceAppShutdown = true
                    }
                        ).AsTask(progressCallback);

                    if (result.IsRegistered)
                    {
                        finalNotif = GenerateInstallSuccessToast(package, product);
                    }
                    else
                    {
                        finalNotif = GenerateInstallFailureToast(package, product, result.ExtendedErrorCode);
                    }
                    isSuccess = result.IsRegistered;
                    await installer.DeleteAsync();
                }

                // Hide progress notification
                ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast);
                // Show the final notification
                ToastNotificationManager.GetDefault().CreateToastNotifier().Show(finalNotif);

                return(true);
            }
            catch (Exception ex)
            {
                ToastNotificationManager.GetDefault().CreateToastNotifier().Show(GenerateInstallFailureToast(package, product, ex));
                return(false);
            }
        }
Esempio n. 16
0
        public static async Task <Tuple <StorageFile, ToastNotification> > DownloadPackage(PackageInstance package, ProductDetails product, bool hideProgressToastWhenDone = true, string filepath = null)
        {
            // Download the file to the app's temp directory
            if (filepath == null)
            {
                filepath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, package.PackageMoniker);
            }
            Debug.WriteLine(filepath);

            StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(
                package.PackageMoniker, CreationCollisionOption.ReplaceExisting);

            BackgroundDownloader downloader = new BackgroundDownloader();

            downloader.FailureToastNotification = GenerateDownloadFailureToast(package, product);
            var progressToast = GenerateProgressToast(package, product);

            Debug.WriteLine(package.PackageUri.AbsoluteUri);
            DownloadOperation download = downloader.CreateDownload(package.PackageUri, destinationFile);

            download.RangesDownloaded += (op, args) =>
            {
                ToastNotificationManager.GetDefault().CreateToastNotifier().Update(
                    new NotificationData(new Dictionary <string, string>()
                {
                    { "progressValue", ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive).ToString() },
                    { "progressStatus", "Downloading..." }
                }),
                    progressToast.Tag
                    );
            };
            ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast);
            await download.StartAsync();

            if (hideProgressToastWhenDone)
            {
                ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast);
            }

            string extension           = "";
            string contentTypeFilepath = filepath + "_[Content_Types].xml";

            using (var stream = await destinationFile.OpenStreamForReadAsync())
            {
                var bytes = new byte[4];
                stream.Read(bytes, 0, 4);
                uint magicNumber = (uint)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);

                switch (magicNumber)
                {
                // ZIP
                /// Typical [not empty or spanned] ZIP archive
                case 0x504B0304:
                    using (var archive = ZipFile.OpenRead(filepath))
                    {
                        var entry = archive.GetEntry("[Content_Types].xml");
                        entry.ExtractToFile(contentTypeFilepath, true);
                        var ctypesXml = XDocument.Load(contentTypeFilepath);
                        var defaults  = ctypesXml.Root.Elements().Where(e => e.Name.LocalName == "Default");
                        if (defaults.Any(d => d.Attribute("Extension").Value == "msix"))
                        {
                            // Package contains one or more MSIX packages
                            extension += ".msix";
                        }
                        else if (defaults.Any(d => d.Attribute("Extension").Value == "appx"))
                        {
                            // Package contains one or more MSIX packages
                            extension += ".appx";
                        }
                        if (defaults.Any(defaults => defaults.Attribute("ContentType").Value == "application/vnd.ms-appx.bundlemanifest+xml"))
                        {
                            // Package is a bundle
                            extension += "bundle";
                        }

                        if (extension == string.Empty)
                        {
                            // We're not sure exactly what kind of package it is, but it's definitely
                            // a package archive. Even if it's not actually an appxbundle, it will
                            // likely still work.
                            extension = ".appxbundle";
                        }
                    }
                    break;

                // EMSIX, EAAPX, EMSIXBUNDLE, EAPPXBUNDLE
                /// An encrypted installer [bundle]?
                case 0x45584248:
                    // This means the downloaded file wasn't a zip archive.
                    // Some inspection of a hex dump of the file leads me to believe that this means
                    // the installer is encrypted. There's probably nothing that can be done about this,
                    // but since it's a known case, let's leave this here.
                    extension = ".eappxbundle";
                    break;
                }
            }

            if (File.Exists(contentTypeFilepath))
            {
                File.Delete(contentTypeFilepath);
            }

            if (extension != string.Empty)
            {
                await destinationFile.RenameAsync(destinationFile.Name + extension, NameCollisionOption.ReplaceExisting);
            }

            return((destinationFile, progressToast).ToTuple());
        }
Esempio n. 17
0
        public static async Task <Tuple <StorageFile, ToastNotification> > DownloadPackage(PackageInstance package, ProductDetails product, bool hideProgressToastWhenDone = true)
        {
            // Download the file to the app's temp directory
            //var client = new System.Net.WebClient();
            string filepath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, package.PackageMoniker);

            Debug.WriteLine(filepath);
            //client.DownloadFile(package.Uri, filepath);

            StorageFile destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(
                package.PackageMoniker, CreationCollisionOption.ReplaceExisting);

            BackgroundDownloader downloader = new BackgroundDownloader();

            downloader.FailureToastNotification = GenerateDownloadFailureToast(package, product);
            var progressToast = GenerateProgressToast(package, product);

            Debug.WriteLine(package.PackageUri.AbsoluteUri);
            DownloadOperation download = downloader.CreateDownload(package.PackageUri, destinationFile);

            download.RangesDownloaded += (op, args) =>
            {
                ToastNotificationManager.GetDefault().CreateToastNotifier().Update(
                    new NotificationData(new Dictionary <string, string>()
                {
                    { "progressValue", ((double)op.Progress.BytesReceived / op.Progress.TotalBytesToReceive).ToString() },
                    { "progressStatus", "Downloading..." }
                }),
                    progressToast.Tag
                    );
            };
            ToastNotificationManager.GetDefault().CreateToastNotifier().Show(progressToast);
            await download.StartAsync();

            if (hideProgressToastWhenDone)
            {
                ToastNotificationManager.GetDefault().CreateToastNotifier().Hide(progressToast);
            }

            string extension           = "";
            string contentTypeFilepath = filepath + "_[Content_Types].xml";

            using (var archive = ZipFile.OpenRead(filepath))
            {
                var entry = archive.GetEntry("[Content_Types].xml");
                entry.ExtractToFile(contentTypeFilepath, true);
                var ctypesXml = XDocument.Load(contentTypeFilepath);
                var defaults  = ctypesXml.Root.Elements().Where(e => e.Name.LocalName == "Default");
                if (defaults.Any(d => d.Attribute("Extension").Value == "msix"))
                {
                    // Package contains one or more MSIX packages
                    extension += ".msix";
                }
                else if (defaults.Any(d => d.Attribute("Extension").Value == "appx"))
                {
                    // Package contains one or more MSIX packages
                    extension += ".appx";
                }
                if (defaults.Any(defaults => defaults.Attribute("ContentType").Value == "application/vnd.ms-appx.bundlemanifest+xml"))
                {
                    // Package is a bundle
                    extension += "bundle";
                }
            }
            if (File.Exists(contentTypeFilepath))
            {
                File.Delete(contentTypeFilepath);
            }

            if (extension != "")
            {
                await destinationFile.RenameAsync(destinationFile.Name + extension, NameCollisionOption.ReplaceExisting);
            }

            return((destinationFile, progressToast).ToTuple());
        }