/// <summary> /// Mains the specified args. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Source: {0}", options.Source); Console.WriteLine("Target: {0}", options.Target); Console.WriteLine("Output: {0}", options.Output); Console.WriteLine("Collision behavior: {0}", options.CollisionBehavior); Console.WriteLine("Configuration: {0}", options.Configuration); Console.WriteLine("Path to project file: {0}", options.ScProjFilePath); if (ExclusionHandler.HasValidExclusions(options.Configuration, options.ScProjFilePath)) { var exclusions = ExclusionHandler.GetExcludedItems(options.ScProjFilePath, options.Configuration); ExclusionHandler.RemoveExcludedItems(options.Source, exclusions); ExclusionHandler.RemoveExcludedItems(options.Target, exclusions); } var diff = new DiffInfo( DiffGenerator.GetDiffCommands(options.Source, options.Target, options.CollisionBehavior), "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target)); PackageGenerator.GeneratePackage(diff, string.Empty, options.Output); } else { Console.WriteLine(options.GetUsage()); } }
protected override void EndProcessing() { // Use default logger XmlConfigurator.Configure((XmlElement)ConfigurationManager.GetSection("log4net")); PerformInstallAction( () => { var diff = new DiffInfo( CommandList, string.IsNullOrEmpty(Name) ? "Sitecore PowerShell Extensions Generated Update Package" : Name, Readme ?? string.Empty, Tag ?? string.Empty); var fileName = Path; if (string.IsNullOrEmpty(fileName)) { fileName = string.Format("{0}.update", Name); } if (!System.IO.Path.IsPathRooted(fileName)) { fileName = FullPackageProjectPath(fileName); } if (ShouldProcess(fileName, "Export update package")) { PackageGenerator.GeneratePackage(diff, LicenseFileName, fileName); } }); }
protected override void BeginProcessing() { try { var currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", Path.Combine(currentDirectory, "Sitecore.Courier.dll.config")); ResetConfigMechanism(); string version = Guid.NewGuid().ToString(); Console.WriteLine("Source: {0}", Source); Console.WriteLine("Target: {0}", Target); Console.WriteLine("Output: {0}", Output); Console.WriteLine("SerializationProvider: {0}", SerializationProvider); Console.WriteLine("CollisionBehavior: {0}", CollisionBehavior); Console.WriteLine("IncludeFiles: {0}", IncludeFiles); Console.WriteLine("DacPac: {0}", DacPac); RainbowSerializationProvider.Enabled = SerializationProvider == SerializationProvider.Rainbow; RainbowSerializationProvider.IncludeFiles = IncludeFiles; RainbowSerializationProvider.EnsureRevision = EnsureRevision; var diff = new DiffInfo( DiffGenerator.GetDiffCommands(Source, Target, IncludeSecurity, version, CollisionBehavior), "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", Source, Target)); if (IncludeSecurity) { diff.Commands.Add(new PostStepFileSystemDataItem(currentDirectory, string.Empty, PostDeployDll) .GenerateAddCommand().FirstOrDefault()); diff.PostStep = PostStep; diff.Version = version; } if (DacPac) { SqlConverter c = new SqlConverter(); c.ConvertPackage(diff, Output); var builder = new DacPacBuilder(); DirectoryInfo d = new DirectoryInfo(Output); foreach (var file in d.GetFiles("*.sql")) { builder.ConvertToDacPac(file.FullName, Path.Combine(file.DirectoryName, $"{Path.GetFileNameWithoutExtension(file.Name)}.dacpac")); } } else { PackageGenerator.GeneratePackage(diff, string.Empty, Output); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); throw ex; } }
/// <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); } }
protected void Page_Load(object sender, EventArgs e) { using (new SecurityDisabler()) { Sitecore.Context.SetActiveSite("shell"); PackageGenerator.GeneratePackage( Sitecore.Configuration.Settings.DataFolder + "/packages/Mobile Device Detector.xml", Sitecore.Configuration.Settings.DataFolder + "/packages/Mobile Device Detector.zip", new SimpleProcessingContext()); } }
public int Build() { var project = _contexts.First().ProjectFile; var packDiagnostics = new List <DiagnosticMessage>(); var mainPackageGenerator = new PackageGenerator(project, _configuration, _artifactPathsCalculator); var symbolsPackageGenerator = new SymbolPackageGenerator(project, _configuration, _artifactPathsCalculator); return(mainPackageGenerator.BuildPackage(_contexts, packDiagnostics) && symbolsPackageGenerator.BuildPackage(_contexts, packDiagnostics) ? 0 : 1); }
static void Main(string[] args) { var pckg = new PackageGenerator(); pckg.DirectorySet.WorkingDirectory = ""; pckg.Id = "Lovelyripple.Demo"; Console.ForegroundColor = ConsoleColor.White; var properties = new List <ClassModel.PropertyModel>(); var firstNameValue = new ValueModel(typeof(string), "Tomasz"); var numOfPpl = new ValueModel(typeof(int), 123); properties.Add(new ClassModel.PropertyModel("FirstName", typeof(string), false, firstNameValue, PropertyScope.Get)); properties.Add(new ClassModel.PropertyModel("NumberOfPeople", typeof(int), false, numOfPpl, PropertyScope.GetSet)); var assetValues = new List <ValueModel>(); assetValues.Add(new ValueModel(typeof(string), "Emails")); assetValues.Add(new ValueModel(typeof(string), "ToBusiness")); assetValues.Add(new ValueModel(typeof(string), "Text")); assetValues.Add(new ValueModel(typeof(bool), false)); assetValues.Add(new ValueModel(typeof(bool), true)); assetValues.Add(new ValueModel(typeof(int), 321)); properties.Add(new ClassModel.PropertyModel("AssetInfo", "Norian.Configuration.Base.AssetInformation", assetValues, PropertyScope.GetSet)); var credsValues = new List <ValueModel>(); credsValues.Add(new ValueModel(typeof(string), "tpawlicki87")); credsValues.Add(new ValueModel(typeof(string), "ChangeMe1!")); properties.Add(new ClassModel.PropertyModel("Creds", typeof(NetworkCredential), credsValues, PropertyScope.GetSet)); var classModel = new ClassModel("Norian.Configuration.Base", "TestDev", null, properties, null); var models = new List <ClassModel>(); var assetProps = new List <ClassModel.PropertyModel>(); assetProps.Add(new ClassModel.PropertyModel("Group", typeof(string), false, null, PropertyScope.Get)); assetProps.Add(new ClassModel.PropertyModel("Name", typeof(string), false, null, PropertyScope.Get)); assetProps.Add(new ClassModel.PropertyModel("ValueType", typeof(string), false, null, PropertyScope.Get)); assetProps.Add(new ClassModel.PropertyModel("HasSuffix", typeof(bool), false, null, PropertyScope.Get)); assetProps.Add(new ClassModel.PropertyModel("IsPerRobot", typeof(bool), false, null, PropertyScope.Get)); assetProps.Add(new ClassModel.PropertyModel("NumOfAssets", typeof(int), false, null, PropertyScope.Get)); var assetInfoModel = new ClassModel("Norian.Configuration.Base", "AssetInformation", null, assetProps, null); models.Add(assetInfoModel); models.Add(classModel); CodeGenerator.LogMessage = LogMsg; //CodeGenerator.SaveTo = new System.IO.FileInfo(Path.Combine(Directory.GetCurrentDirectory(),"test.cs")); pckg.ClassModels.AddRange(models); pckg.Build(); Console.WriteLine(); Console.WriteLine("--------------------"); Console.WriteLine("ready"); }
public List <ISource <PackageEntry> > GetSources(string packagePath) { var sources = PackageGenerator.NewProjectFromPackage(packagePath).Sources; var count = sources.Count; var sourceList = new List <ISource <PackageEntry> >(); for (var i = 0; i < count; i++) { if (sources[i] != null) { sourceList.Add(sources[i]); } } return(sourceList); }
private void BuildFunctions() { if (factory.Components.Any(c => c is Function)) { var storageAccountName = NameGenerator.Unique("fnsa", maxNameLength); props["fn_sa_name"] = storageAccountName; props["name"] = storageAccountName; GenerateTf("storage_account", storageAccountName.ToLower()); var sizes = factory.Components.OfType <Function>().GroupBy(c => c.Size); foreach (var size in sizes) { var spName = NameGenerator.Unique($"fnsp{size.Key}", maxNameLength); props["fn_sp_name"] = spName.ToLower(); props["name"] = spName; props["size"] = size.Key; GenerateTf("service_plan", spName); foreach (var function in size.ToList()) { var cadlInterpreter = new CadlInterpreter(); props["name"] = function.FunctionName; if (function.OutputQueue != null) { props["q_sa_name"] = function.OutputQueue.StorageAccount; } GenerateTf("function", function.ComponentName); var functionFolder = $"{factory.CodePath}/{function.FunctionName}/{Function.FolderName}"; Directory.CreateDirectory($"{factory.CodePath}/{function.FunctionName}"); Directory.CreateDirectory(functionFolder); var js = cadlInterpreter.CompileToJs(function, factory.Components, props); File.WriteAllText($"{functionFolder}/index.js", js); var packageGeneratpr = new PackageGenerator(function.FunctionName, cadlInterpreter.DependsOnModules); File.WriteAllText($"{factory.CodePath}/{function.FunctionName}/package.json", packageGeneratpr.Package); } } } }
public SimulationImplementation(SimulationSettings settings, ProgressHandler handler) { using var scope = Framework.Container.BeginLifetimeScope(); mapper = scope.Resolve <IMapper>(); reporting = scope.Resolve <IReportingService>(); progress = handler; var algAirports = mapper.Map <List <AlgorithmAirport> >(settings.Airports); var algPlanes = mapper.Map <List <AlgorithmPlane> >(settings.Planes); var idCurrent = 0; foreach (var airport in algAirports) { airport.InternalId = idCurrent++; } idCurrent = 0; foreach (var plane in algPlanes) { plane.InternalId = idCurrent++; } rng = settings.Seed.HasValue ? new Random(settings.Seed.Value) : new Random(); populationRng = settings.InitialPopulationSeed.HasValue ? new Random(settings.InitialPopulationSeed.Value) : new Random(); DistanceMap = AirportDistanceMap.FromAirports(algAirports); Airports = algAirports; Planes = algPlanes; IterationCount = settings.NumberOfIterations; reporting.WithAiports(Airports).WithPlanes(Planes).FinishInit(); packageGenerator = PackageGenerator.WithSettings(settings.PackageGeneration, rng); FuelPricePerLiter = settings.FuelPricePerLiter; PopulationSize = settings.GenerationSize; MutationProbability = settings.MutationProbability; MutationProbabilityRngRange = (int)(100 / MutationProbability); if (settings.PenaltyPercent <= 0) { throw new ArgumentException(nameof(settings.PenaltyPercent)); } PenaltyPerDayPercentage = settings.PenaltyPercent; }
private static void ProcessFolder(string directory, string outputFolderPath) { var client = new ServiceClient(); foreach (var productName in client.GetProductNames()) { var filePrefix = PackageGenerator.GetFilePrefix(productName); var prefix = PackageGenerator.GetAbbr(productName); if (string.IsNullOrEmpty(prefix)) { continue; } foreach (var version in client.GetVersions(productName)) { var majorMinor = PackageGenerator.GetMajorMinor(version); foreach (var release in version.Releases) { var revision = release.Revision; var pattern = filePrefix + " " + majorMinor + "* rev. " + revision + ".zip"; var zipfiles = Directory.GetFiles(directory, pattern, SearchOption.AllDirectories); if (zipfiles.Length <= 0) { continue; } var releaseVersion = PackageGenerator.GetReleaseVersion(majorMinor, revision); var file = zipfiles.First(); try { // Create nupkg file new PackageGenerator().Generate(prefix, productName, file, releaseVersion, outputFolderPath); } catch (Exception ex) { Log.Error("Error processing file " + file + ". " + ex.Message + Environment.NewLine + "Stack trace:" + Environment.NewLine + ex.StackTrace); } } } } }
/// <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 override void Execute() { if (ConfigurationMetadata.PackageId == Metadata.PackageId) { // create NEW Genyman configuration file Log.Information("Generating a new genyman generator solution"); ProcessHandlebarTemplates(); } else { var packageId = ConfigurationMetadata.PackageId; var resolvePackageResult = DotNetRunner.ResolvePackage(packageId, ConfigurationMetadata.NugetSource, Update, ConfigurationMetadata.Version); if (resolvePackageResult.success) { var generator = new PackageGenerator(); generator.InputFileName = InputFileName; generator.PackageId = resolvePackageResult.packageId; generator.Execute(Args); } } }
/// <summary> /// Mains the specified args. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Source: {0}", options.Source); Console.WriteLine("Target: {0}", options.Target); Console.WriteLine("Output: {0}", options.Output); var diff = new DiffInfo( DiffGenerator.GetDiffCommands(options.Source, options.Target), "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target)); PackageGenerator.GeneratePackage(diff, string.Empty, options.Output); } else { Console.WriteLine(options.GetUsage()); } }
public override void Process(BuildPackageArgs args) { if (this.AbortIfErrorsDetected(args)) { return; } if (args.PackageFiles.Entries.Count > 0) { args.Package.Sources.Add(args.PackageFiles); } if (args.PackageItems.Entries.Count > 0 || args.PackageSources.Sources.Count > 0) { args.Package.Sources.Add(args.PackageSources); } args.Package.SaveProject = true; try { this.Log.Debug("Generating package '" + args.PackageFilePath + "'...", this); using (new SiteContextSwitcher(SiteContext.GetSite("shell"))) using (new DatabaseSwitcher(Database.GetDatabase("core"))) using (var writer = new PackageWriter(args.PackageFilePath)) { var context = Sitecore.Install.Serialization.IOUtils.SerializationContext; writer.Initialize(Installer.CreateInstallationContext()); PackageGenerator.GeneratePackage(args.Package, writer); } } catch (Exception ex) { args.Errors.Add(ex.GetType().Name, ex.Message); this.Log.Error("Error generating package '" + args.PackageFilePath + "'", ex, this); } }
protected override void BeginProcessing() { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Sitecore.Courier.dll.config")); ResetConfigMechanism(); Console.WriteLine("Source: {0}", Source); Console.WriteLine("Target: {0}", Target); Console.WriteLine("Output: {0}", Output); Console.WriteLine("SerializationProvider: {0}", SerializationProvider); Console.WriteLine("CollisionBehavior: {0}", CollisionBehavior); Console.WriteLine("IncludeFiles: {0}", IncludeFiles); RainbowSerializationProvider.Enabled = SerializationProvider == SerializationProvider.Rainbow; RainbowSerializationProvider.IncludeFiles = IncludeFiles; var diff = new DiffInfo( DiffGenerator.GetDiffCommands(Source, Target, CollisionBehavior), "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", Source, Target)); PackageGenerator.GeneratePackage(diff, string.Empty, Output); }
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); }
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); }
/// <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); }
public override bool Execute() { if (!File.Exists(ManifestPath)) { Log.LogError("Cannont find manifest '{0}", ManifestPath); return false; } if (string.IsNullOrWhiteSpace(ApplicationVersion)) { Log.LogError("Version not provided"); return false; } if (!Directory.Exists(PackageDataRootDirectory)) { Log.LogError("Package root directory'{0}' does not exist", PackageDataRootDirectory); return false; } DeployitManifest manifest; try { var reader = new StreamReader(ManifestPath, DeployitManifest.Encoding); using (reader) { manifest = DeployitManifest.Load(reader); } } catch (Exception ex) { Log.LogErrorFromException(ex); return false; } manifest.Version = ApplicationVersion; ApplicationName = manifest.ApplicationName; var packageBuilder = new PackageGenerator(); packageBuilder.GeneratePackage(manifest, PackageDataRootDirectory, PackagePath); return true; }
public void GeneratePackage() { var getReaderProcessor = ReaderTypeProcessor.GetTypeProcessor(this.FileType); var items = getReaderProcessor.ReadFile(this.FilePath); var packageProject = new PackageProject { Metadata = { PackageName = this.PackageName, Author = this.Author, Version = this.Version, Publisher = this.Publisher } }; var packageFileSource = new ExplicitFileSource { Name = "Custom File Source" }; var packageItemSource = new ExplicitItemSource { Name = "Custom Item Source" }; var sourceCollection = new SourceCollection <PackageEntry>(); sourceCollection.Add(packageItemSource); foreach (var item in items) { if (item.ObjectType.ToLower().Equals("item")) { var itemUri = Factory.GetDatabase(Settings.GetSetting("SourceDatabase")).Items.GetItem(item.ObjectPath); if (itemUri != null) { if (item.IncludeSubItem.ToLower().Equals("true")) { sourceCollection.Add(new ItemSource() { SkipVersions = true, Database = itemUri.Uri.DatabaseName, Root = itemUri.Uri.ItemID.ToString() }); } else { packageItemSource.Entries.Add(new ItemReference(itemUri.Uri, false).ToString()); } } } else if (item.ObjectType.ToLower().Equals("file")) { var pathMapped = MainUtil.MapPath(item.ObjectPath); packageFileSource.Entries.Add(pathMapped); } } if (packageFileSource.Entries.Count > 0) { packageProject.Sources.Add(packageFileSource); } if (packageItemSource.Entries.Count > 0 || sourceCollection.Sources.Count > 0) { packageProject.Sources.Add(sourceCollection); } packageProject.SaveProject = true; var packageGeneratorFolder = Settings.GetSetting("PackageGeneratorFolder"); using (var writer = new PackageWriter(MainUtil.MapPath(string.Format("{0}/{1}/{2}.zip", Settings.PackagePath, packageGeneratorFolder, this.PackageName)))) { Context.SetActiveSite("shell"); writer.Initialize(Installer.CreateInstallationContext()); PackageGenerator.GeneratePackage(packageProject, writer); Context.SetActiveSite("website"); } }
protected CodeAdder asyncerr(PackageGenerator <AsyncError <T> > gen) { return(Generic <AsyncError <T> >(gen, OnAsyncErrorReceived)); }
protected CodeAdder async(PackageGenerator <Async <T> > gen) { return(Generic <Async <T> >(gen, OnAsyncCommandReceived)); }
protected override string BuildPackage() { var commands = new List <ICommand>(); foreach (var item in Items) { var syncItem = ItemSynchronization.BuildSyncItem(item); var contentDataItem = new ContentDataItem(string.Empty, item.Paths.ParentPath, item.Name, syncItem); var command = new AddItemCommand(contentDataItem); commands.Add(command); } var rootPath = FileUtil.MapPath("/"); foreach (var fileName in Files) { if (FileUtil.IsFolder(fileName)) { foreach (var file in Directory.GetFiles(FileUtil.MapPath(fileName), "*", SearchOption.AllDirectories)) { var fileInfo = new FileInfo(file); if ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { continue; } if ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System) { continue; } var fileItem = new FileSystemDataItem(rootPath, Path.GetDirectoryName(file), Path.GetFileName(file)); var command = new AddFileCommand(fileItem); commands.Add(command); } } else { var fileItem = new FileSystemDataItem(rootPath, Path.GetDirectoryName(fileName), Path.GetFileName(fileName)); var command = new AddFileCommand(fileItem); commands.Add(command); } } var diff = new DiffInfo(commands) { Author = Author, PostStep = PostStep, Publisher = Publisher, Readme = Readme, Version = Version, Title = PackageName }; var directoryName = Path.GetDirectoryName(FileName) ?? string.Empty; directoryName = directoryName.Replace("\\", "/"); var folderPath = FileUtil.MapPath(directoryName); diff.Serialize(folderPath); var packageFileName = FileUtil.UnmapPath(folderPath, false) + "/" + DiffInfo.OutputFileName; PackageGenerator.GeneratePackage(diff, packageFileName); return(packageFileName); }
protected CodeAdder sync(PackageGenerator <SyncReply <T> > gen) { return(Generic <SyncReply <T> >(gen, OnSyncCommandReceived)); }
protected CodeAdder Generic <T1>(PackageGenerator <T1> gen, Action <byte, T1> action) where T1 : ServicePacket <T> { return(code => (list => action(code, gen(list)))); }
protected override string BuildPackage() { var project = new PackageProject(); var sourceCollection = new SourceCollection <PackageEntry>(); var itemSource = new ExplicitItemSource { SkipVersions = false }; sourceCollection.Add(itemSource); var list = new List <ID>(); foreach (var item in Items) { var i = item; if (list.Any(id => id == i.ID)) { continue; } list.Add(item.ID); var reference = new ItemReference(item.Database.Name, item.Paths.Path, item.ID, LanguageManager.DefaultLanguage, Data.Version.Latest).Reduce(); itemSource.Entries.Add(reference.ToString()); } var fileSource = new ExplicitFileSource(); sourceCollection.Add(fileSource); foreach (var fileName in Files) { if (FileUtil.IsFolder(fileName)) { foreach (var file in Directory.GetFiles(FileUtil.MapPath(fileName), "*", SearchOption.AllDirectories)) { var fileInfo = new FileInfo(file); if ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { continue; } if ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System) { continue; } fileSource.Entries.Add(file); } } else { fileSource.Entries.Add(fileName); } } project.Sources.Add(sourceCollection); project.Name = "Sitecore Package"; project.Metadata.PackageName = PackageName; project.Metadata.Author = Author; project.Metadata.Version = Version; project.Metadata.Publisher = Publisher; project.Metadata.License = License; project.Metadata.Comment = Comment; project.Metadata.Readme = Readme; project.Metadata.PostStep = PostStep; var context = new SimpleProcessingContext(); var intermediateFile = GetIntermediateFileName(FileName); try { using (var writer = new PackageWriter(PathUtils.MapPath(intermediateFile))) { writer.Initialize(context); PackageGenerator.GeneratePackage(project, writer); } Commit(intermediateFile, FileName); } catch { Cleanup(intermediateFile); throw; } return(FileName); }
protected override void ProcessRecord() { var fileName = Path; if (!Zip.IsPresent) { PerformInstallAction(() => { if (fileName == null) { //name of the zip file when not defined fileName = string.Format( "{0}{1}{2}.xml", Project.Metadata.PackageName, string.IsNullOrEmpty(Project.Metadata.Version) ? "" : "-", Project.Metadata.Version); } if (!System.IO.Path.IsPathRooted(fileName)) { fileName = FullPackageProjectPath(fileName); } if (!System.IO.Path.HasExtension(fileName)) { fileName = fileName + ".xml"; } if (NoClobber.IsPresent && System.IO.File.Exists(fileName)) { WriteError(typeof(IOException), $"The file '{fileName}' already exists.", ErrorIds.FileAlreadyExists, ErrorCategory.ResourceExists, fileName); } if (ShouldProcess(fileName, "Export package project")) { FileUtil.WriteToFile(fileName, IOUtils.StoreObject(Project)); } }); } else { PerformInstallAction( () => { if (IncludeProject.IsPresent) { Project.SaveProject = true; } if (fileName == null) { //name of the zip file when not defined fileName = $"{Project.Metadata.PackageName}-PS-{Project.Metadata.Version}.zip"; } if (!System.IO.Path.IsPathRooted(fileName)) { fileName = FullPackagePath(fileName); } if (!System.IO.Path.HasExtension(fileName)) { fileName = fileName + ".zip"; } if (NoClobber.IsPresent && System.IO.File.Exists(fileName)) { WriteError(typeof(IOException), $"The file '{fileName}' already exists.", ErrorIds.FileAlreadyExists, ErrorCategory.ResourceExists, fileName); } if (ShouldProcess(fileName, "Export package")) { using (var writer = new PackageWriter(fileName)) { writer.Initialize(Installer.CreateInstallationContext()); PackageGenerator.GeneratePackage(Project, writer); } } }); } }
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); }
/// <summary> /// Mains the specified args. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Source: {0}", options.Source); Console.WriteLine("Target: {0}", options.Target); Console.WriteLine("Output: {0}", options.Output); Console.WriteLine("Collision behavior: {0}", options.CollisionBehavior); Console.WriteLine("Use Rainbow: {0}", options.UseRainbow); Console.WriteLine("Include Security: {0}", options.IncludeSecurity); Console.WriteLine("Include Files: {0}", options.IncludeFiles); Console.WriteLine("Configuration: {0}", options.Configuration); Console.WriteLine("Ensure Revision: {0}", options.EnsureRevision); Console.WriteLine("Path to project file: {0}", options.ScProjFilePath); Console.WriteLine("DacPac Output: {0}", options.DacPac); string version = Guid.NewGuid().ToString(); SanitizeOptions(options); if (ExclusionHandler.HasValidExclusions(options.Configuration, options.ScProjFilePath)) { var exclusions = ExclusionHandler.GetExcludedItems(options.ScProjFilePath, options.Configuration); ExclusionHandler.RemoveExcludedItems(options.Source, exclusions); ExclusionHandler.RemoveExcludedItems(options.Target, exclusions); } RainbowSerializationProvider.Enabled = options.UseRainbow; RainbowSerializationProvider.IncludeFiles = options.IncludeFiles; RainbowSerializationProvider.EnsureRevision = options.EnsureRevision; var commands = DiffGenerator.GetDiffCommands(options.Source, options.Target, options.IncludeSecurity, version, options.CollisionBehavior); var diff = new DiffInfo( commands, "Sitecore Courier Package", string.Empty, string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target)); if (options.IncludeSecurity) { var currentDirectory = Directory.GetCurrentDirectory(); commands.Add(new PostStepFileSystemDataItem(currentDirectory, string.Empty, PostDeployDll) .GenerateAddCommand().FirstOrDefault()); diff.PostStep = PostStep; diff.Version = version; } if (options.DacPac) { SqlConverter c = new SqlConverter(); c.ConvertPackage(diff, options.Output); var builder = new DacPacBuilder(); DirectoryInfo d = new DirectoryInfo(options.Output); foreach (var file in d.GetFiles("*.sql")) { builder.ConvertToDacPac(file.FullName, Path.Combine(file.DirectoryName, $"{Path.GetFileNameWithoutExtension(file.Name)}.dacpac")); } } else { PackageGenerator.GeneratePackage(diff, string.Empty, options.Output); } } else { Console.WriteLine(options.GetUsage()); } }
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); }