Example #1
0
        private static PackageProject ExtractPackageProject(string fileName)
        {
            PackageProject packageProject = null;

            using (var packageReader = new ZipReader(fileName))
            {
                var packageEntry = packageReader.GetEntry("package.zip");
                using (var memoryStream = new MemoryStream())
                {
                    StreamUtils.CopyStream(packageEntry.GetStream(), memoryStream, 0x4000);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new ZipReader(memoryStream))
                    {
                        foreach (var entry in reader.Entries)
                        {
                            if (!entry.Name.Is("installer/project"))
                            {
                                continue;
                            }

                            packageProject = IOUtils.LoadSolution(StreamUtil.LoadString(entry.GetStream()));
                            break;
                        }
                    }
                }
            }

            return(packageProject);
        }
Example #2
0
        protected override void ProcessRecord()
        {
            PerformInstallAction(() =>
            {
                PackageProject packageProject = null;
                if (Path != null)
                {
                    var fileName = Path;

                    if (!System.IO.Path.IsPathRooted(Path))
                    {
                        fileName = FullPackageProjectPath(Path);
                    }

                    if (File.Exists(fileName))
                    {
                        var isZip = false;
                        using (var stream = FileUtil.OpenRead(fileName))
                        {
                            if (ZipUtils.IsZipContent(stream))
                            {
                                isZip = true;
                            }
                        }

                        packageProject = !isZip ? IOUtils.LoadSolution(FileUtil.ReadFromFile(fileName)) : ExtractPackageProject(fileName);
                    }

                    WriteObject(packageProject, false);
                }
            });
        }
Example #3
0
        private static PackageProject ExtractPackageProject(string fileName)
        {
            PackageProject packageProject = null;

            using (var packageReader = ZipFile.Open(fileName, ZipArchiveMode.Read))
            {
                var packageEntry = packageReader.GetEntry("package.zip");
                if (packageEntry == null)
                {
                    return(null);
                }

                using (var memoryStream = new MemoryStream())
                {
                    StreamUtils.CopyStream(packageEntry.Open(), memoryStream, 0x4000);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new ZipArchive(memoryStream))
                    {
                        foreach (var entry in reader.Entries)
                        {
                            if (!entry.FullName.Is(Constants.ProjectKey))
                            {
                                continue;
                            }

                            packageProject = IOUtils.LoadSolution(StreamUtil.LoadString(entry.Open()));
                            break;
                        }
                    }
                }
            }

            return(packageProject);
        }
 /// <summary>
 /// Writes the package.
 /// </summary>
 /// <param name="project">The project.</param>
 /// <param name="filePath">The file path.</param>
 private static void WritePackage(PackageProject project, string filePath)
 {
     using (var writer = new PackageWriter(filePath))
     {
         writer.Initialize(Installer.CreateInstallationContext());
         PackageGenerator.GeneratePackage(project, writer);
     }
 }
Example #5
0
 protected override void ProcessRecord()
 {
     PerformInstallAction(
         () =>
             {
                 var project = new PackageProject {Name = Name, Metadata = {PackageName = Name}};
                 WriteObject(project, false);
             });
 }
 public static PackageProject SetMetaData(PackageProject project, string packageName)
 {
     //make this a tested method.  Test for existnace ofauthor, publisher, etc.
     project.Metadata.PackageName = packageName;
     project.Metadata.Version     = DateTime.Now.ToString(SortableTimeFormat);
     project.Metadata.Author      = Sitecore.Context.User.Name;
     project.Metadata.Comment     = String.Format("Pachaged from: {0}, {1}", Sitecore.Configuration.Settings.InstanceName, Sitecore.Context.Site.SiteInfo.Name);
     return(project);
 }
        private void PushPackage(PackageProject metadata, string packageFormat, byte[] data)
        {
            var directory = Path.Combine(configuration.DataPath, metadata.Name, metadata.Version.Name);

            Directory.CreateDirectory(directory);

            var file = Path.Combine(directory, GetPackageName(packageFormat, metadata.Name, metadata.Version.Name));

            File.WriteAllBytes(file, data);
        }
Example #8
0
 protected override void ProcessRecord()
 {
     PerformInstallAction(
         () =>
     {
         var project = new PackageProject {
             Name = Name, Metadata = { PackageName = Name }
         };
         WriteObject(project, false);
     });
 }
        private void SynchronizePermissions(Caller caller, string company, PackageProject packageProject)
        {
            var permission = GetProjectPermission(caller, company, packageProject);

            if (permission.HasValue)
            {
                var configuration = configurationFactory.Create(company);

                if (string.IsNullOrEmpty(configuration.GatewayLogin) || string.IsNullOrEmpty(configuration.GatewayPassword))
                {
                    throw new Exception("Missing gateway configuration");
                }

                using (var session = backendFactory.Create(new Caller {
                    Company = company, Name = configuration.GatewayLogin, KeyType = "API", KeyValue = configuration.GatewayPassword
                }))
                {
                    var project = new Project {
                        Company = company, Repository = packageProject.Repository, Name = packageProject.Name
                    };

                    if (permission.Value)
                    {
                        try
                        {
                            session.CreateProject(project);
                        }
                        catch (Exception)
                        {
                            //ignore if exists
                        }
                    }

                    try
                    {
                        session.SetProjectPermissions(new User {
                            Company = caller.Company, Name = caller.Name
                        }, project, new Permission {
                            Grant = false, Read = false, Write = permission.Value
                        });
                    }
                    catch (Exception)
                    {
                        //ignore if not exists
                    }

                    if (!permission.Value)
                    {
                        throw new Exception("External permission source denied publish access");
                    }
                }
            }
        }
Example #10
0
        protected void btnExportUsersInList_Click(object sender, EventArgs e)
        {
            this.BuildUserList();
            Sitecore.Data.Database          db       = Sitecore.Configuration.Factory.GetDatabase("master");
            Sitecore.Install.PackageProject document = new PackageProject();
            document.Metadata.PackageName = "SitecoreUserExport-" + DateTime.Now.ToString("yyyy-MM-dd-hhmmss");
            document.Metadata.Author      = "Autogenerated by SitecoreExtension.SitecoreUserImporter";

            Sitecore.Install.Security.SecuritySource securitySource = new SecuritySource();
            securitySource.Name = "Users To Export";

            int count        = 1;
            int packageCount = 0;

            foreach (string key in usersByEmail.Keys)
            {
                UserData userData = usersByEmail[key];

                string userName = GetFullName(userData.Login);

                if (Sitecore.Security.Accounts.User.Exists(userName))
                {
                    securitySource.AddAccount(new AccountString(userName, AccountType.User));
                    packageCount++;
                }

                count++;
            }

            document.Sources.Add(securitySource);
            document.SaveProject = true;

            if (packageCount > 0)
            {
                //path where the zip file package is saved
                using (Sitecore.Install.Zip.PackageWriter writer = new Sitecore.Install.Zip.PackageWriter(this.userExportFilePath))
                {
                    Sitecore.Context.SetActiveSite("shell");
                    writer.Initialize(Sitecore.Install.Installer.CreateInstallationContext());
                    Sitecore.Install.PackageGenerator.GeneratePackage(document, writer);
                    Sitecore.Context.SetActiveSite("website");
                }

                divDebug.InnerHtml = string.Format("<h1>{0} Users packaged, file location: </h1>{1}", packageCount, this.userExportFilePath);
            }
            else
            {
                divDebug.InnerHtml = string.Format("<h1>Could not find any users</h1>");
            }
        }
 public void Save(PackageProject Project, string FileName)
 {
     var xDoc = new XDocument(
         new XElement("Project",
                      Project.Components.Select(component =>
                                                new XElement("Component",
                                                             component.Targets.Select(target =>
                                                                                      new XElement("Target",
                                                                                                   new XAttribute("Cell", target.Cell),
                                                                                                   new XAttribute("Modification", target.Modification),
                                                                                                   new XAttribute("Module", target.Module),
                                                                                                   new XAttribute("Channel", target.Channel))),
                                                             new XElement("Files")))));
     throw new NotImplementedException("На самом деле не написал я :(");
     xDoc.Save(FileName);
 }
        public UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
        {
            if (packageData == null && symbolPackageData == null)
                throw new ArgumentNullException();

            if (packageData != null)
                PushPackage(package, packageFormat, packageData);

            if (symbolPackageData != null)
                CreateJob(package, symbolPackageData);

            return new UploadReport
                       {
                           Summary = "OK",
                       };
        }
        private void PerformUpload(Caller caller, PackageProject packageProject, string path)
        {
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Uploading package");
            }

            var packagePath       = GetFilePath(path);
            var symbolPackagePath = GetSymbolPackagePath(path);

            var package       = File.Exists(packagePath) ? File.ReadAllBytes(packagePath) : null;
            var symbolPackage = File.Exists(symbolPackagePath) ? File.ReadAllBytes(symbolPackagePath) : null;

            using (var session = backendFactory.Create(caller))
            {
                var report = session.UploadPackage(packageProject, GetPackageFormat(), package, symbolPackage);

                if (report.Summary != "OK")
                {
                    var builder = new StringBuilder();
                    builder.AppendLine(report.Summary);
                    builder.AppendLine();

                    if (!string.IsNullOrEmpty(report.Exception))
                    {
                        builder.AppendLine("Exception:");
                        builder.AppendLine(report.Exception);
                        builder.AppendLine();
                    }

                    if (!string.IsNullOrEmpty(report.Exception))
                    {
                        builder.AppendLine("Log:");
                        builder.AppendLine(report.Log);
                        builder.AppendLine();
                    }

                    throw new Exception(builder.ToString());
                }
            }

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Uploaded upload package");
            }
        }
        public UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
        {
            if (packageData == null && symbolPackageData == null)
                throw new ArgumentNullException();

            if (packageData != null)
                PushPackage(package, packageFormat, packageData);

            if (symbolPackageData != null)
                CreateJob(package, symbolPackageData);

            NuGetTranslator.ExpirePackageHash(package.Version.Project, package.Version.Name);

            return new UploadReport
                       {
                           Summary = "OK",
                       };
        }
        protected override void GetMetadata(string path, string repository, out PackageProject project, out IList<MetadataEntry> metadata, out ILookup<ContentType, string> contents)
        {
            var assemblyExporter = new DefaultAssemblyExporter();
            var packageInfo = new FolderRepository(LocalFileSystem.Instance.GetDirectory(path)).PackagesByName.Single().Single();
            var package = packageInfo.Load();
            var descriptor = package.Descriptor;

            var exports = assemblyExporter
                .Items<Exports.IAssembly>(package, ExecutionEnvironment.Any)
                .SelectMany(group => group)
                .GroupBy(assembly => new { assembly.Profile, assembly.Platform });

            project =
                new PackageProject
                    {
                        Name = descriptor.Name,
                        Repository = repository,
                        Version =
                            new PackageVersion
                                {
                                    Name = descriptor.Version.ToString(),
                                    Compilations = exports
                                        .Select(group =>
                                                new PackageCompilation
                                                    {
                                                        Mode = "Release",
                                                        Platform = group.Key.Profile + "-" + group.Key.Platform,
                                                        ImageFiles = group
                                                            .Select(assembly =>
                                                                new PackageImageFile
                                                                    {
                                                                        Name = GetAssemblyPath(assembly.File.Path, path)
                                                                    }).ToArray(),
                                                    }).ToArray(),
                                },
                    };

            using (var zip = new ZipFile(GetFilePath(path)))
                contents = zip.EntryFileNames.ToLookup(GetContentType);

            metadata = new List<MetadataEntry>();
        }
        protected override void GetMetadata(string path, string repository, out PackageProject project, out IList <MetadataEntry> metadata, out ILookup <ContentType, string> contents)
        {
            var assemblyExporter = new DefaultAssemblyExporter();
            var packageInfo      = new FolderRepository(LocalFileSystem.Instance.GetDirectory(path)).PackagesByName.Single().Single();
            var package          = packageInfo.Load();
            var descriptor       = package.Descriptor;

            var exports = assemblyExporter
                          .Items <Exports.IAssembly>(package, ExecutionEnvironment.Any)
                          .SelectMany(group => group)
                          .GroupBy(assembly => new { assembly.Profile, assembly.Platform });

            project =
                new PackageProject
            {
                Name       = descriptor.Name,
                Repository = repository,
                Version    =
                    new PackageVersion
                {
                    Name         = descriptor.Version.ToString(),
                    Compilations = exports
                                   .Select(group =>
                                           new PackageCompilation
                    {
                        Mode       = "Release",
                        Platform   = group.Key.Profile + "-" + group.Key.Platform,
                        ImageFiles = group
                                     .Select(assembly =>
                                             new PackageImageFile
                        {
                            Name = GetAssemblyPath(assembly.File.Path, path)
                        }).ToArray(),
                    }).ToArray(),
                },
            };

            using (var zip = new ZipFile(GetFilePath(path)))
                contents = zip.EntryFileNames.ToLookup(GetContentType);

            metadata = new List <MetadataEntry>();
        }
        /// <summary>
        /// Takes in a list of items and generates a PackageProject object for those items.
        /// </summary>
        /// <param name="itemKeys">The items.</param>
        /// <returns></returns>
        public static PackageProject GetPackageFromItems(IEnumerable <IItemKey> itemKeys)
        {
            PackageProject project = new PackageProject();

            ExplicitItemSource.Builder explicitSourceBuilder = new ExplicitItemSource.Builder();
            foreach (IItemKey item in itemKeys)
            {
                //Re-fetch the item at the time of packaging to make sure it's current
                Item reFetchedItem = Sitecore.Data.Database.GetDatabase(item.DatabaseName).GetItem(item.Guid, LanguageManager.DefaultLanguage, item.Version);

                IEntryData   ied      = new ItemEntryData(reFetchedItem);
                PackageEntry iedEntry = new PackageEntry(ied);
                explicitSourceBuilder.Put(iedEntry);
            }
            ExplicitItemSource explicitSource = explicitSourceBuilder.Source;

            project.Sources.Add(explicitSource);

            return(project);
        }
Example #18
0
        protected override void ProcessRecord()
        {
            PerformInstallAction(() =>
            {
                PackageProject packageProject = null;
                var fileName = Path;
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                if (!System.IO.Path.IsPathRooted(fileName))
                {
                    fileName = FullPackageProjectPath(fileName);
                }

                if (File.Exists(fileName))
                {
                    var isZip = false;
                    using (var stream = FileUtil.OpenRead(fileName))
                    {
                        if (ZipUtils.IsZipContent(stream))
                        {
                            isZip = true;
                        }
                    }

                    packageProject = !isZip ? IOUtils.LoadSolution(FileUtil.ReadFromFile(fileName)) : ExtractPackageProject(fileName);
                }

                if (packageProject == null)
                {
                    WriteError(typeof(FileNotFoundException), "Cannot find the package.zip contained within the provided file.",
                               ErrorIds.FieldNotFound, ErrorCategory.ObjectNotFound, null);
                }
                else
                {
                    WriteObject(packageProject, false);
                }
            });
        }
        /// <summary>
        /// Generates the package.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        private string GeneratePackage(List <Item> list)
        {
            string fullName = Context.User.Profile.FullName;

            using (new UserSwitcher(Sitecore.Security.Accounts.User.FromName("sitecore\\admin", false)))
            {
                Database       contentDatabase = Context.ContentDatabase;
                PackageProject solution        = new PackageProject();
                solution.Metadata.PackageName = list[0].Name;
                solution.Metadata.Author      = fullName;
                ExplicitItemSource explicitItemSource = new ExplicitItemSource();
                explicitItemSource.Name = list[0].Name;

                Item[] objArray = list.ToArray();
                if (objArray != null && objArray.Length > 0)
                {
                    list.AddRange(objArray);
                }
                foreach (Item obj in list)
                {
                    explicitItemSource.Entries.Add(new ItemReference(obj.Uri, false).ToString());
                }
                solution.Sources.Add(explicitItemSource);
                solution.SaveProject = true;

                string fileName = list[0].Name + "_" + DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss_fffffff") + ".zip";
                string str      = Settings.PackagePath + "\\";

                using (PackageWriter packageWriter = new PackageWriter(str + fileName))
                {
                    Context.SetActiveSite("shell");
                    packageWriter.Initialize(Installer.CreateInstallationContext());
                    PackageGenerator.GeneratePackage(solution, packageWriter);
                    Context.SetActiveSite("website");
                }

                return(str + fileName);
            }
        }
        public UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
        {
            if (packageData == null && symbolPackageData == null)
            {
                throw new ArgumentNullException();
            }

            if (packageData != null)
            {
                PushPackage(package, packageFormat, packageData);
            }

            if (symbolPackageData != null)
            {
                CreateJob(package, symbolPackageData);
            }

            return(new UploadReport
            {
                Summary = "OK",
            });
        }
Example #21
0
        public override void Execute(CommandContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            //get current item
            Item   currentItem     = context.Items[0];
            string currentItemId   = currentItem.ID.ToString();
            string currentItemName = currentItem.Name;
            string currentItemDB   = currentItem.Database.Name;
            string currentDateTime = DateTime.UtcNow.ToString("yyyyMMddTHHmmssfff");

            IEnumerable <IItemKey> itemKeys = context.Items.Select(x => new ItemKey(x) as IItemKey);
            string recurseVal = context.Parameters.Get("recurse");
            bool   recurse    = (!string.IsNullOrEmpty(recurseVal) && true.ToString().ToLowerInvariant().CompareTo(recurseVal.ToLowerInvariant()) == 0);

            if (recurse)
            {
                itemKeys = itemKeys.Union(currentItem.Axes.GetDescendants().Select(x => new ItemKey(x) as IItemKey));
            }
            PackageProject project = InstantPackageManager.GetPackageFromItems(itemKeys);

            string path     = Sitecore.Configuration.Settings.PackagePath;
            string fileName = string.Format("{0}{1}_{2}_{3}_{4}.zip", currentItemName, (recurse ? "-WithSubItems" : ""),
                                            currentItemId.Trim(("{}").ToCharArray()), currentItemDB, currentDateTime);
            string fullPath = path + '\\' + fileName;

            //refactor this into a different object
            project = InstantPackageManager.SetMetaData(project);

            PackageWriter      writer            = new PackageWriter(fullPath);
            IProcessingContext processingContext = new SimpleProcessingContext();

            writer.Initialize(processingContext);
            PackageGenerator.GeneratePackage(project, writer);

            Context.ClientPage.ClientResponse.Download(fullPath);
        }
        /// <summary>
        /// Generates the package.
        /// </summary>
        /// <param name="items">The items.</param>
        /// <param name="packageName">Name of the package.</param>
        /// <param name="packageAuthor">The package author.</param>
        /// <returns>Download path</returns>
        public virtual string GeneratePackage(IEnumerable <ItemUri> items, string packageName, string packageAuthor)
        {
            try
            {
                var project = new PackageProject
                {
                    Metadata =
                    {
                        PackageName = packageName.Trim(),
                        Author      = packageAuthor,
                        Version     = DateTime.UtcNow.ToString("yyyyMMddHHmmss")
                    }
                };

                var filePath = FileUtil.MakePath(Settings.PackagePath, string.Format("{0}-{1}.{2}", project.Metadata.Version, PackageUtils.CleanupFileName(project.Metadata.PackageName), "zip"));
                var source   = new ExplicitItemSource {
                    Name = "PackMan added Items"
                };

                foreach (var item in items)
                {
                    source.Entries.Add(new ItemReference(item, false).ToString());
                }

                project.Sources.Add(source);
                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    WritePackage(project, filePath);
                    return(filePath);
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(ex.Message, ex, this);
                return(null);
            }
        }
Example #23
0
 public UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
 {
     //TODO: quick and dirty
     try
     {
         var version = new Version {
             Company = caller.Company, Repository = package.Repository, Project = package.Name, Name = package.Version.Name
         };
         CreateVersion(version);
         PushPackage(ref version, packageData, package);
         CreateJob(symbolPackageData, package);
         return(new UploadReport {
             Summary = "OK"
         });
     }
     catch (Exception e)
     {
         return(new UploadReport
         {
             Summary = "Error",
             Exception = e.ToString(),
         });
     }
 }
Example #24
0
        /// <summary>
        /// Executes the specified context.
        /// Saves a HotPackage project to XML using a naming scheme similar to the one used in the downloader
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Execute(CommandContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            throw new NotImplementedException();

            string currentDateTime = DateTime.UtcNow.ToString("yyyyMMddTHHmmssfff");

            string path     = Sitecore.Configuration.Settings.PackagePath;
            string fileName = string.Format("InstantPackage_{0}.xml", currentDateTime);
            string fullPath = path + '\\' + fileName;


            InstantPackageManager packageManager = new InstantPackageManager(new PackageSourceDictionary());
            PackageProject        package        = packageManager.GetPackage();

            PackageWriter      writer            = new PackageWriter(fullPath);
            IProcessingContext processingContext = new SimpleProcessingContext();

            writer.Initialize(processingContext);
            PackageGenerator.GeneratePackage(package, writer);

//			package.SaveProject(fullPath);
        }
Example #25
0
        public override void Execute(CommandContext context)
        {
            Assert.ArgumentNotNull(context, "context");

            InstantPackageManager packageManager = new InstantPackageManager(new PackageSourceDictionary());
            PackageProject        package        = packageManager.GetPackage();

            string currentDateTime = DateTime.UtcNow.ToString(InstantPackageManager.SortableTimeFormat);            //possibly obsolete with use of version number.

            string path     = Sitecore.Configuration.Settings.PackagePath;
            string fileName = string.Format("InstantPackage_{0}-{1}.zip", Sitecore.Context.Site.HostName, currentDateTime);
            string fullPath = path + '\\' + fileName;

            //refactor this into a different object
            package = InstantPackageManager.SetMetaData(package);

            PackageWriter      writer            = new PackageWriter(fullPath);
            IProcessingContext processingContext = new SimpleProcessingContext();

            writer.Initialize(processingContext);
            PackageGenerator.GeneratePackage(package, writer);

            Context.ClientPage.ClientResponse.Download(fullPath);
        }
Example #26
0
        public PackageGenerationResult Generate(Commit commit, bool getAdded = true, bool getUpdated = true)
        {
            var result = new PackageGenerationResult();

            StringBuilder commitNameBuilder = new StringBuilder();

            commitNameBuilder.Append(commit.Name);
            if (getAdded)
            {
                commitNameBuilder.Append("-added");
            }

            if (getUpdated)
            {
                commitNameBuilder.Append("-updated");
            }

            commitNameBuilder.Append(".zip");
            var commitName = commitNameBuilder.ToString();

            var path = PathToFile;

            result.Name       = commitName;
            result.Path       = path;
            result.Successful = false;

            var db       = _databaseSelector.GetSelectedDataBase();
            var document = new PackageProject();

            document.Sources.Clear();
            var commitUserName = commit.Invoker?.Name;

            document.Metadata.PackageName = !string.IsNullOrWhiteSpace(commit.Name) ? commit.Name : Constants.Package.DefaultCommitName;
            document.Metadata.Author      = !string.IsNullOrWhiteSpace(commitUserName) ? commitUserName : Constants.Package.DefaultAuthorName;
            document.Metadata.Publisher   = !string.IsNullOrWhiteSpace(User.Current.Name) ? User.Current.Name : Constants.Package.DefaultAuthorName;
            document.Metadata.Version     = Constants.Package.DefaultVersion;


            var itemsIds = new List <ID>();

            if (getAdded)
            {
                itemsIds = itemsIds.Union(commit.AddedItems).ToList();
            }
            if (getUpdated)
            {
                itemsIds = itemsIds.Union(commit.ChangedItems).ToList();
            }

            var items = new List <Item>();

            itemsIds.ForEach(x =>
            {
                var item = db.GetItem(x);
                if (item != null)
                {
                    items.Add(item);
                }
            });

            ExplicitItemSource source = new ExplicitItemSource();

            source.Name         = Constants.Package.SourceName;
            source.SkipVersions = true;

            foreach (Item item in items)
            {
                if (item != null)
                {
                    source.Entries.Add(new ItemReference(item.Uri, false).ToString());
                }
            }

            document.Sources.Add(source);
            document.SaveProject = true;

            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                using (var writer = new PackageWriter(MainUtil.MapPath($"{path}{commitName}")))
                {
                    Context.SetActiveSite(Constants.Package.ShellSite);
                    writer.Initialize(Installer.CreateInstallationContext());
                    PackageGenerator.GeneratePackage(document, writer);
                    Context.SetActiveSite(Constants.Package.MainSite);
                    result.Successful = true;
                }
            }

            return(result);
        }
 protected override bool?GetProjectPermission(Caller caller, string companyName, PackageProject project)
 {
     return(null);
 }
Example #28
0
        public static string GeneratePackage(PackageManifest manifest)
        {
            var packageProject = new PackageProject
            {
                Metadata =
                {
                    PackageName = manifest.PackageName,
                    Author      = manifest.Author,
                    Version     = manifest.Version,
                    Publisher   = manifest.Publisher
                }
            };

            foreach (var fileSource in manifest.Files)
            {
                if (fileSource == null || fileSource.Entries == null || fileSource.Entries.Count == 0)
                {
                    continue;
                }

                var packageFileSource = new ExplicitFileSource
                {
                    Name = "Files"
                };

                packageFileSource.Converter.Transforms.Add(
                    new InstallerConfigurationTransform(
                        new BehaviourOptions(fileSource.InstallMode, fileSource.MergeMode)));

                foreach (var item in fileSource.Entries)
                {
                    var pathMapped = MainUtil.MapPath(item.Path);

                    packageFileSource.Entries.Add(pathMapped);
                }

                if (packageFileSource.Entries.Count > 0)
                {
                    packageProject.Sources.Add(packageFileSource);
                }
            }


            foreach (var itemSource in manifest.Items)
            {
                if (itemSource == null || itemSource.Entries == null || itemSource.Entries.Count == 0)
                {
                    continue;
                }

                List <Item> items             = new List <Item>();
                var         packageItemSource = new ExplicitItemSource
                {
                    Name = itemSource.Name
                };

                packageItemSource.Converter.Transforms.Add(
                    new InstallerConfigurationTransform(
                        new BehaviourOptions(itemSource.InstallMode, itemSource.MergeMode)));

                using (new SecurityDisabler())
                {
                    foreach (var item in itemSource.Entries)
                    {
                        var db = ResolveDatabase(item.Database);

                        var itemUri = db.Items.GetItem(item.Path);
                        if (itemUri != null)
                        {
                            items.Add(itemUri);

                            if (item.IncludeChildren)
                            {
                                var    paths         = Sitecore.StringUtil.Split(itemUri.Paths.Path, '/', true).Where(p => p != null & p != string.Empty).Select(p => "#" + p + "#").ToList();
                                string allChildQuery = string.Format("/{0}//*", Sitecore.StringUtil.Join(paths, "/"));
                                var    children      = db.Items.Database.SelectItems(allChildQuery);

                                if (children != null && children.Length > 0)
                                {
                                    items.AddRange(children);
                                }
                            }
                        }
                    }

                    foreach (var item in items)
                    {
                        packageItemSource.Entries.Add(new ItemReference(item.Uri, false).ToString());
                    }
                }

                if (packageItemSource.Entries.Count > 0)
                {
                    packageProject.Sources.Add(packageItemSource);
                }
            }

            packageProject.SaveProject = true;

            var  location = MainUtil.MapPath($"{ Sitecore.Configuration.Settings.PackagePath}/{ manifest.PackageName}");
            bool exists   = System.IO.Directory.Exists(location);

            if (!exists)
            {
                System.IO.Directory.CreateDirectory(location);
            }

            var packagePath = $"{location}/{manifest.PackageName}.zip";

            try
            {
                using (var writer = new PackageWriter(packagePath))
                {
                    using (new SecurityDisabler())
                    {
                        SiteContext targetSiteContext = SiteContext.GetSite("shell");
                        using (var context = new SiteContextSwitcher(targetSiteContext))
                        {
                            writer.Initialize(Installer.CreateInstallationContext());

                            PackageGenerator.GeneratePackage(packageProject, writer);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Package was not created. Message: {ex.Message}", ex);
            }


            return(packagePath);
        }
 public virtual void PushPackage(ref Version version, byte[] package, PackageProject packageProject)
 {
     throw new NotImplementedException("Not implemented: " + MethodBase.GetCurrentMethod().Name);
 }
 public virtual void CreateJob(byte[] package, PackageProject project)
 {
     throw new NotImplementedException("Not implemented: " + MethodBase.GetCurrentMethod().Name);
 }
 public UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
 {
     //TODO: quick and dirty
     try
     {
         var version = new Version {Company = caller.Company, Repository = package.Repository, Project = package.Name, Name = package.Version.Name};
         CreateVersion(version);
         PushPackage(ref version, packageData, package);
         CreateJob(symbolPackageData, package);
         return new UploadReport { Summary = "OK" };
     }
     catch(Exception e)
     {
         return new UploadReport
                    {
                        Summary = "Error",
                        Exception = e.ToString(),
                    };                
     }
 }
        private void PerformUpload(Caller caller, PackageProject packageProject, string path)
        {
            if (log.IsDebugEnabled)
                log.DebugFormat("Uploading package");

            var packagePath = GetFilePath(path);
            var symbolPackagePath = GetSymbolPackagePath(path);

            var package = File.Exists(packagePath) ? File.ReadAllBytes(packagePath) : null;
            var symbolPackage = File.Exists(symbolPackagePath) ? File.ReadAllBytes(symbolPackagePath) : null;

            using (var session = backendFactory.Create(caller))
            {
                var report = session.UploadPackage(packageProject, GetPackageFormat(), package, symbolPackage);

                if (report.Summary != "OK")
                {
                    var builder = new StringBuilder();
                    builder.AppendLine(report.Summary);
                    builder.AppendLine();

                    if (!string.IsNullOrEmpty(report.Exception))
                    {
                        builder.AppendLine("Exception:");
                        builder.AppendLine(report.Exception);
                        builder.AppendLine();
                    }

                    if (!string.IsNullOrEmpty(report.Exception))
                    {
                        builder.AppendLine("Log:");
                        builder.AppendLine(report.Log);
                        builder.AppendLine();
                    }

                    throw new Exception(builder.ToString());
                }
            }

            if (log.IsDebugEnabled)
                log.DebugFormat("Uploaded upload package");
        }
 protected abstract bool?GetProjectPermission(Caller caller, string companyName, PackageProject project);
        private void CreateJob(PackageProject metadata, byte[] data)
        {
            string directory = Path.Combine(metadata.Name, metadata.Version.Name);

            Directory.CreateDirectory(Path.Combine(configuration.DataPath, directory));

            string file = Path.Combine(configuration.DataPath, directory, metadata.Name + ".symbols.zip");

            File.WriteAllBytes(file, data);

            using (var zipMemoryStream = new MemoryStream(data))
                using (var zipfile = ZipFile.Read(zipMemoryStream))
                {
                    var zipInfo = new TransformingWrapperPackageFile(new ZipPackageFile(zipfile), new UrlTransformation());
                    var addInfo = addInfoBuilder.Build(zipInfo);

                    string binariesDirectory = Path.Combine(directory, "Binaries");
                    Directory.CreateDirectory(Path.Combine(configuration.DataPath, binariesDirectory));
                    string sourcesDirectory = Path.Combine(directory, "Sources");
                    Directory.CreateDirectory(Path.Combine(configuration.DataPath, sourcesDirectory));

                    foreach (var binaryInfo in addInfo.Binaries)
                    {
                        if (binaryInfo.SymbolInfo == null)
                        {
                            continue;
                        }

                        string binaryDirectory = Path.Combine(binariesDirectory, binaryInfo.Name, binaryInfo.SymbolHash);
                        Directory.CreateDirectory(Path.Combine(configuration.DataPath, binaryDirectory));

                        using (var binaryInfoStream = binaryInfo.File.Stream)
                            using (var binaryStream = File.OpenWrite(Path.Combine(configuration.DataPath, binaryDirectory, binaryInfo.Name + "." + binaryInfo.Type)))
                                binaryInfoStream.CopyTo(binaryStream);

                        using (var symbolInfoStream = binaryInfo.SymbolInfo.File.Stream)
                            using (var symbolStream = File.OpenWrite(Path.Combine(configuration.DataPath, binaryDirectory, binaryInfo.Name + "." + binaryInfo.SymbolInfo.Type)))
                                symbolInfoStream.CopyTo(symbolStream);

                        string indexDirectory = Path.Combine(configuration.IndexPath, binaryInfo.Name);
                        Directory.CreateDirectory(indexDirectory);

                        File.AppendAllText(Path.Combine(indexDirectory, binaryInfo.SymbolHash + ".txt"), binaryDirectory + Environment.NewLine);

                        var sourceIndex = new List <string>();

                        foreach (var sourceInfo in binaryInfo.SymbolInfo.SourceInfos.Where(info => info.ActualPath != null))
                        {
                            string sourcePath = Path.Combine(sourcesDirectory, sourceInfo.KeyPath);
                            Directory.CreateDirectory(Path.Combine(configuration.DataPath, Path.GetDirectoryName(sourcePath)));

                            sourceIndex.Add(sourceInfo.OriginalPath + "|" + sourceInfo.KeyPath);

                            using (var sourceInfoStream = sourceInfo.ActualPath.Stream)
                                using (var convertedStream = SourceConverter.Convert(sourceInfoStream))
                                    using (var sourceStream = File.OpenWrite(Path.Combine(configuration.DataPath, sourcePath)))
                                        convertedStream.CopyTo(sourceStream);

                            File.WriteAllLines(Path.Combine(configuration.DataPath, binaryDirectory, binaryInfo.Name + ".txt"), sourceIndex);
                        }
                    }
                }

            File.Delete(file);
        }
 protected override bool? GetProjectPermission(Caller caller, string companyName, PackageProject project)
 {
     return null;
 }
 public virtual UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
 {
     return service.UploadPackage(caller, package, packageFormat, packageData, symbolPackageData);
 }
Example #37
0
 public virtual UploadReport UploadPackage(PackageProject package, string packageFormat, byte[] packageData, byte[] symbolPackageData)
 {
     return(service.UploadPackage(caller, package, packageFormat, packageData, symbolPackageData));
 }
        private void PerformUpload(Caller caller, PackageProject packageProject, string path)
        {
            if (log.IsDebugEnabled)
                log.DebugFormat("Uploading package");

            var packagePath = GetFilePath(path);
            var symbolPackagePath = GetSymbolPackagePath(path);

            var package = File.Exists(packagePath) ? File.ReadAllBytes(packagePath) : null;
            var symbolPackage = File.Exists(symbolPackagePath) ? File.ReadAllBytes(symbolPackagePath) : null;

            using (var session = backendFactory.Create(caller))
            {
                var report = session.UploadPackage(packageProject, GetPackageFormat(), package, symbolPackage);

                if (report.Summary != "OK")
                    throw new Exception(report.Summary);
            }

            if (log.IsDebugEnabled)
                log.DebugFormat("Uploaded upload package");
        }
Example #39
0
 public virtual void PushPackage(ref Version version, byte[] package, PackageProject packageProject)
 {
     throw new NotImplementedException("Not implemented: " + MethodBase.GetCurrentMethod().Name);
 }
Example #40
0
 public virtual void CreateJob(byte[] package, PackageProject project)
 {
     throw new NotImplementedException("Not implemented: " + MethodBase.GetCurrentMethod().Name);
 }
 protected abstract bool? GetProjectPermission(Caller caller, string companyName, PackageProject project);
 public static PackageProject SetMetaData(PackageProject project)
 {
     return(SetMetaData(project, "Instant Package"));
 }
 protected abstract void GetMetadata(string path, string repository, out PackageProject project, out IList <MetadataEntry> metadata, out ILookup <ContentType, string> contents);
        private void PushPackage(PackageProject metadata, string packageFormat, byte[] data)
        {
            var directory = Path.Combine(configuration.DataPath, metadata.Name, metadata.Version.Name);
            Directory.CreateDirectory(directory);

            var file = Path.Combine(directory, GetPackageName(packageFormat, metadata.Name, metadata.Version.Name));
            if (File.Exists(file))
            {
                File.Delete(file);
            }
            File.WriteAllBytes(file, data);
        }
        private void SynchronizePermissions(Caller caller, string company, PackageProject packageProject)
        {
            var permission = GetProjectPermission(caller, company, packageProject);

            if (permission.HasValue)
            {
                var configuration = configurationFactory.Create(company);

                if (string.IsNullOrEmpty(configuration.GatewayLogin) || string.IsNullOrEmpty(configuration.GatewayPassword))
                    throw new Exception("Missing gateway configuration");

                using (var session = backendFactory.Create(new Caller { Company = company, Name = configuration.GatewayLogin, KeyType = "API", KeyValue = configuration.GatewayPassword }))
                {
                    var project = new Project { Company = company, Repository = packageProject.Repository, Name = packageProject.Name };

                    if (permission.Value)
                    {
                        try
                        {
                            session.CreateProject(project);
                        }
                        catch (Exception)
                        {
                            //ignore if exists
                        }
                    }

                    try
                    {
                        session.SetProjectPermissions(new User { Company = caller.Company, Name = caller.Name }, project, new Permission { Grant = false, Read = false, Write = permission.Value });
                    }
                    catch (Exception)
                    {
                        //ignore if not exists
                    }

                    if (!permission.Value)
                        throw new Exception("External permission source denied publish access");
                }
            }
        }
        private void CreateJob(PackageProject metadata, byte[] data)
        {
            string directory = Path.Combine(metadata.Name, metadata.Version.Name);
            Directory.CreateDirectory(Path.Combine(configuration.DataPath, directory));

            string file = Path.Combine(configuration.DataPath, directory, metadata.Name + ".symbols.zip");
            if (File.Exists(file))
            {
                File.Delete(file);
            }
            File.WriteAllBytes(file, data);

            using (var zipMemoryStream = new MemoryStream (data))
            using (var zipfile = ZipFile.Read(zipMemoryStream))
            {
                var zipInfo = new TransformingWrapperPackageFile(new ZipPackageFile(zipfile), new UrlTransformation());
                var addInfo = addInfoBuilder.Build(zipInfo);

                string binariesDirectory = Path.Combine(directory, "Binaries");
                Directory.CreateDirectory(Path.Combine(configuration.DataPath, binariesDirectory));
                string sourcesDirectory = Path.Combine(directory, "Sources");
                Directory.CreateDirectory(Path.Combine(configuration.DataPath, sourcesDirectory));

                foreach (var binaryInfo in addInfo.Binaries)
                {
                    if (binaryInfo.SymbolInfo == null)
                        continue;

                    if (binaryInfo.SymbolHash != binaryInfo.SymbolInfo.Hash)
                        throw new InvalidOperationException(string.Format("Incorrect hash code for '{0}' binaryHash '{1}' symbolHash '{2}'.", binaryInfo.Name, binaryInfo.SymbolHash, binaryInfo.SymbolInfo.Hash));

                    string binaryDirectory = Path.Combine(binariesDirectory, binaryInfo.Name, binaryInfo.SymbolHash);
                    Directory.CreateDirectory(Path.Combine(configuration.DataPath, binaryDirectory));

                    using (var binaryInfoStream = binaryInfo.File.Stream)
                    {
                        using (var binaryStream = File.OpenWrite(Path.Combine(configuration.DataPath, binaryDirectory, binaryInfo.Name + "." + binaryInfo.Type)))
                            binaryInfoStream.CopyTo(binaryStream);
                    }

                    using (var symbolInfoStream = binaryInfo.SymbolInfo.File.Stream)
                    {
                        using (var symbolStream = File.OpenWrite(Path.Combine(configuration.DataPath, binaryDirectory, binaryInfo.Name + "." + binaryInfo.SymbolInfo.Type)))
                            symbolInfoStream.CopyTo(symbolStream);
                    }

                    string indexDirectory = Path.Combine(configuration.IndexPath, binaryInfo.Name);
                    Directory.CreateDirectory(indexDirectory);

                    File.AppendAllText(Path.Combine(indexDirectory, binaryInfo.SymbolHash + ".txt"), binaryDirectory + Environment.NewLine);

                    var sourceIndex = new List<string>();

                    foreach (var sourceInfo in binaryInfo.SymbolInfo.SourceInfos.Where(info => info.ActualPath != null))
                    {
                        string sourcePath = Path.Combine(sourcesDirectory, sourceInfo.KeyPath.Replace(":/", ""));
                        Directory.CreateDirectory(Path.Combine(configuration.DataPath, Path.GetDirectoryName(sourcePath)));

                        sourceIndex.Add(sourceInfo.OriginalPath + "|" + sourceInfo.KeyPath.Replace(":/", ""));

                        using (var sourceInfoStream = sourceInfo.ActualPath.Stream)
                        {
                            using (var convertedStream = SourceConverter.Convert(sourceInfoStream))
                            {
                                using (var sourceStream = File.OpenWrite(Path.Combine(configuration.DataPath, sourcePath)))
                                    convertedStream.CopyTo(sourceStream);
                            }
                        }
                    }

                    var txtFile = Path.Combine(configuration.DataPath, binaryDirectory, binaryInfo.Name + ".txt");
                    if (File.Exists(txtFile))
                    {
                        File.Delete(txtFile);
                    }
                    File.WriteAllLines(txtFile, sourceIndex.ToArray());
                }
            }

            File.Delete(file);
        }
 protected abstract void GetMetadata(string path, string repository, out PackageProject project, out IList<MetadataEntry> metadata, out ILookup<ContentType, string> contents);