コード例 #1
0
        public void AgentSupplyGpiTest()
        {
            IGpiA retGpiA = null;

            Regulus.Serialization.ISerializer serializer = new Regulus.Serialization.Dynamic.Serializer();
            IProtocol protocol = ProtocolHelper.CreateProtocol(serializer);

            Stream cdClient = new Regulus.Remote.Standalone.Stream();

            Network.IStreamable             peerClient = cdClient;
            PackageWriter <ResponsePackage> writer     = new PackageWriter <ResponsePackage>(serializer);

            writer.Start(new ReverseStream(cdClient));

            Ghost.IAgent agent = new Regulus.Remote.Ghost.Agent(protocol) as Ghost.IAgent;
            agent.QueryNotifier <IGpiA>().Supply += gpi => retGpiA = gpi;
            agent.Start(peerClient);

            writer.ServerToClient(serializer, ServerToClientOpCode.LoadSoul, new Regulus.Remote.PackageLoadSoul()
            {
                EntityId = 1, ReturnType = false, TypeId = 1
            });
            writer.ServerToClient(serializer, ServerToClientOpCode.LoadSoulCompile, new Regulus.Remote.PackageLoadSoulCompile()
            {
                EntityId = 1, TypeId = 1, ReturnId = 0, PassageId = 0
            });
            while (retGpiA == null)
            {
                agent.Update();
            }
            agent.Stop();
            writer.Stop();
            Assert.AreNotEqual(null, retGpiA);
        }
コード例 #2
0
ファイル: User.cs プロジェクト: jiowchern/Regulus.Remote
        public User(IStreamable client, IProtocol protocol, object state)
        {
            State  = state;
            Stream = client;

            _Serialize = protocol.GetSerialize();

            _EnableLock = new object();

            _Peer     = client;
            _Protocol = protocol;



            _Responses = new System.Collections.Concurrent.ConcurrentQueue <ResponsePackage>();
            _Requests  = new System.Collections.Concurrent.ConcurrentQueue <RequestPackage>();
            _Reader    = new PackageReader <RequestPackage>(protocol.GetSerialize());
            _Writer    = new PackageWriter <ResponsePackage>(protocol.GetSerialize());

            _ExternalRequests = new System.Collections.Concurrent.ConcurrentQueue <RequestPackage>();

            _SoulProvider = new SoulProvider(this, this, protocol);

            _Updater = new ThreadUpdater(_AsyncUpdate);
        }
コード例 #3
0
        private static Task WritePackage(PackageWriter writer, Package package, string outputPath, CancellationToken token)
        {
            var task = Task.Run(async() =>
            {
                // execute actual operation in child task
                var childTask = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        //writer.WriteProgress += WriteProgressUpdate;
                        writer.Version          = PackageVersion.V13;
                        writer.Compression      = CompressionMethod.LZ4;
                        writer.CompressionLevel = CompressionLevel.MaxCompression;
                        writer.Write();
                    }
                    catch (Exception)
                    {
                        // ignored because an exception on a cancellation request
                        // cannot be avoided if the stream gets disposed afterwards
                    }
                }, TaskCreationOptions.AttachedToParent);

                var awaiter = childTask.GetAwaiter();
                while (!awaiter.IsCompleted)
                {
                    await Task.Delay(0, token);
                }
            }, token);

            return(task);
        }
コード例 #4
0
ファイル: AssetData.cs プロジェクト: boformer/MovableBridge
        public override void OnAssetSaved(string name, object asset, out Dictionary <string, byte[]> userData)
        {
            if (m_Data == null)
            {
                userData = null;
                return;
            }

            Debug.Log($"Saving MovableBridgeAIData for {name}");

            using (var stream = new MemoryStream()) {
                using (var writer = new PackageWriter(stream)) {
                    writer.Write(kVersion);
                    m_Data.Write(writer);
                }

                userData = new Dictionary <string, byte[]>
                {
                    { kDataKey, stream.ToArray() }
                };
            }

            var prefab = ToolsModifierControl.toolController.m_editPrefabInfo;

            ApplyCustomAI(prefab, m_Data);
            m_Data = null;
        }
コード例 #5
0
        public static bool CreatePackage(string dataRootPath, List <string> inputPaths, string outputPath, List <string> ignoredFiles)
        {
            try
            {
                if (!dataRootPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    dataRootPath += Path.DirectorySeparatorChar;
                }

                var package = new Package();

                foreach (var f in inputPaths)
                {
                    AddFilesToPackage(package, f, dataRootPath, outputPath, ignoredFiles);
                }

                DivinityApp.Log($"Writing package '{outputPath}'.");
                using (var writer = new PackageWriter(package, outputPath))
                {
                    WritePackage(writer, package, outputPath);
                }
                return(true);
            }
            catch (Exception ex)
            {
                DivinityApp.Log($"Error creating package: {ex}");
                return(false);
            }
        }
コード例 #6
0
 /// <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);
     }
 }
コード例 #7
0
        public static async Task <bool> CreatePackage(string dataRootPath, List <string> inputPaths, string outputPath, List <string> ignoredFiles, CancellationToken?token = null)
        {
            try
            {
                if (token == null)
                {
                    token = CancellationToken.None;
                }

                if (token.Value.IsCancellationRequested)
                {
                    Log.Here().Warning($"Package cancellation requested.");
                    //return Task.FromCanceled(token.Value);
                    return(false);
                }

                if (!dataRootPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    dataRootPath += Path.DirectorySeparatorChar;
                }

                var package = new Package();

                AppController.Main.UpdateProgressLog("Parsing project folders...");

                foreach (var f in inputPaths)
                {
                    if (token.Value.IsCancellationRequested)
                    {
                        throw new TaskCanceledException("Cancelled package creation.");
                    }
                    AppController.Main.UpdateProgressLog($"Searching folder \"{f}\" for files to add to package.");
                    await AddFilesToPackage(package, f, dataRootPath, outputPath, ignoredFiles, token.Value);
                }

                AppController.Main.UpdateProgressLog($"Writing package to \"{outputPath}\"");

                using (var writer = new PackageWriter(package, outputPath))
                {
                    await WritePackage(writer, package, outputPath, token.Value);
                }

                Log.Here().Activity($"Package successfully created at {outputPath}");
                return(true);
            }
            catch (Exception ex)
            {
                if (!token.Value.IsCancellationRequested)
                {
                    Log.Here().Error($"Error creating package: {ex.ToString()}");
                }
                else
                {
                    Log.Here().Important($"Cancelled creating package: {ex.ToString()}");
                }
                return(false);
            }
        }
コード例 #8
0
        public GhostSerializer(ISerializer serializer)
        {
            _Reader   = new PackageReader <ResponsePackage>(serializer);
            _Writer   = new PackageWriter <RequestPackage>(serializer);
            _Sends    = new System.Collections.Concurrent.ConcurrentQueue <RequestPackage>();
            _Receives = new System.Collections.Concurrent.ConcurrentQueue <ResponsePackage>();

            _ResponseEvent += _Empty;
        }
コード例 #9
0
ファイル: AgentOnlineStage.cs プロジェクト: tuita520/Regulus
            public OnlineStage(IPeer peer, AgentCore core, ISerializer serializer)
            {
                _Core = core;

                _Peer     = peer;
                _Reader   = new PackageReader <ResponsePackage>(serializer);
                _Writer   = new PackageWriter <RequestPackage>(serializer);
                _Sends    = new Collection.Queue <RequestPackage>();
                _Receives = new Collection.Queue <ResponsePackage>();
            }
コード例 #10
0
        public void Process(AntidotePackagePipelineArgs args)
        {
            string packagePath = Path.Combine(Settings.PackagePath, String.Format("{0}.antidote{1}", Path.GetFileNameWithoutExtension(args.AntidotePackageProject.Name), Path.GetExtension(args.AntidotePackageProject.Name)));
            ISink<PackageEntry> writer = new PackageWriter(packagePath);
            ITaskOutput output = new DefaultOutput();
            writer.Initialize(new SimpleProcessingContext(output));
            PackageGenerator.GeneratePackage(args.AntidotePackageProject, writer);

            Context.ClientPage.ClientResponse.Alert("Antidote package generated");
        }
コード例 #11
0
ファイル: AgentOnlineStage.cs プロジェクト: jiowchern/Regulus
            public OnlineStage(Socket socket, AgentCore core)
            {
                _Core = core;

                _Socket = socket;
                _Reader = new PackageReader<ResponsePackage>();
                _Writer = new PackageWriter<RequestPackage>(OnlineStage.LowFps);
                _Sends = new Collection.Queue<RequestPackage>();
                _Receives = new Collection.Queue<ResponsePackage>();
            }
コード例 #12
0
        public void TestWriteAndRead()
        {
            var package = new Package {
                Magic = "PKGV0005"
            };

            package.Entries.Add(new PackageEntry
            {
                Bytes    = Encoding.ASCII.GetBytes("Hello world!"),
                FullPath = "hello_world.txt",
            });

            package.Entries.Add(new PackageEntry
            {
                Bytes    = Encoding.ASCII.GetBytes("Test"),
                FullPath = "test.txt",
            });

            // Write
            IPackageWriter writer = new PackageWriter();
            var            stream = new MemoryStream();

            using (var binaryWriter = new BinaryWriter(stream, Encoding.UTF8, true))
            {
                writer.WriteTo(binaryWriter, package);
            }

            // Read
            stream.Position = 0;
            var packageReader = new PackageReader {
                ReadEntryBytes = true
            };

            Package readPackage;

            using (var binaryReader = new BinaryReader(stream, Encoding.UTF8, true))
            {
                readPackage = packageReader.ReadFrom(binaryReader);
            }

            // Verify
            Assert.AreEqual(package.Magic, readPackage.Magic);
            Assert.AreEqual(package.Entries.Count, readPackage.Entries.Count);

            for (var i = 0; i < package.Entries.Count; i++)
            {
                var entry     = package.Entries[i];
                var readEntry = readPackage.Entries[i];

                Assert.AreEqual(entry.Bytes, readEntry.Bytes);
                Assert.AreEqual(entry.Extension, readEntry.Extension);
                Assert.AreEqual(entry.Length, readEntry.Length);
                Assert.AreEqual(entry.Offset, readEntry.Offset);
            }
        }
コード例 #13
0
ファイル: ServerSocket.cs プロジェクト: kodlar/r-i-m
 public void Ping()
 {
     try
     {
         byte[] data = PackageWriter.CreatePing();
         Stream.Write(data, 0, data.Length);
     }
     catch
     {
         Disconnect();
     }
 }
コード例 #14
0
        public static async Task <bool> CreatePackageAsync(string dataRootPath, List <string> inputPaths, string outputPath, List <string> ignoredFiles, CancellationToken?token = null)
        {
            try
            {
                if (token == null)
                {
                    token = CancellationToken.None;
                }

                if (token.Value.IsCancellationRequested)
                {
                    return(false);
                }

                if (!dataRootPath.EndsWith(Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar.ToString()))
                {
                    dataRootPath += Alphaleonis.Win32.Filesystem.Path.DirectorySeparatorChar;
                }

                var package = new Package();

                foreach (var f in inputPaths)
                {
                    if (token.Value.IsCancellationRequested)
                    {
                        throw new TaskCanceledException("Cancelled package creation.");
                    }
                    await AddFilesToPackageAsync(package, f, dataRootPath, outputPath, ignoredFiles, token.Value);
                }

                DivinityApp.Log($"Writing package '{outputPath}'.");
                using (var writer = new PackageWriter(package, outputPath))
                {
                    await WritePackageAsync(writer, package, outputPath, token.Value);
                }
                return(true);
            }
            catch (Exception ex)
            {
                if (!token.Value.IsCancellationRequested)
                {
                    DivinityApp.Log($"Error creating package: {ex.ToString()}");
                }
                else
                {
                    DivinityApp.Log($"Cancelled creating package: {ex.ToString()}");
                }
                return(false);
            }
        }
コード例 #15
0
 protected override async Task OnWrite(PackageWriter writer)
 {
     try
     {
         if (Saving != null)
         {
             await Saving(writer, this);
         }
     }
     catch (Exception ex)
     {
         ExceptionThrown = ex;
     }
 }
コード例 #16
0
ファイル: Peer.cs プロジェクト: jiowchern/Regulus
        public Peer(Socket client)
        {
            _EnableLock = new object();

            _Socket = client;
            _SoulProvider = new SoulProvider(this, this);
            _Responses = new Regulus.Collection.Queue<ResponsePackage>();
            _Requests = new Regulus.Collection.Queue<RequestPackage>();

            _Enable = true;

            _Reader = new PackageReader<RequestPackage>();
            _Writer = new PackageWriter<ResponsePackage>();
        }
コード例 #17
0
 private static void WritePackage(PackageWriter writer, Package package, string outputPath)
 {
     try
     {
         //writer.WriteProgress += WriteProgressUpdate;
         writer.Version          = PackageVersion.V13;
         writer.Compression      = CompressionMethod.LZ4;
         writer.CompressionLevel = CompressionLevel.MaxCompression;
         writer.Write();
     }
     catch (Exception)
     {
         // ignored because an exception on a cancellation request
         // cannot be avoided if the stream gets disposed afterwards
     }
 }
コード例 #18
0
        public Peer(IPeer client, IProtocol protocol)
        {
            _Serialize = protocol.GetSerialize();

            _EnableLock = new object();

            _Peer         = client;
            _Protocol     = protocol;
            _SoulProvider = new SoulProvider(this, this, protocol);
            _Responses    = new System.Collections.Concurrent.ConcurrentQueue <ResponsePackage>();
            _Requests     = new System.Collections.Concurrent.ConcurrentQueue <RequestPackage>();

            _Enable = true;

            _Reader = new PackageReader <RequestPackage>(protocol.GetSerialize());
            _Writer = new PackageWriter <ResponsePackage>(protocol.GetSerialize());
        }
コード例 #19
0
ファイル: PackageBuilder.cs プロジェクト: showconcept/Deploy
        /// <summary>
        /// Builds the MSI package to the specified filename.
        /// </summary>
        /// <param name="filename">The filename of the MSI package.</param>
        /// <exception cref="ArgumentException">The <paramref name="filename"/> parameter is null or empty.</exception>
        /// <exception cref="PackageException">A validation error or other platform error occurred</exception>
        public void Build(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentException(Resources.Argument_NullOrEmpty, nameof(filename));
            }

            var validator = new PackageValidator(this);

            validator.Validate();

            try
            {
                using (var writer = new PackageWriter(this, filename))
                    writer.Write();
            }
            catch (Exception ex)
            {
                throw new PackageException(Resources.Package_PlatformError, ex);
            }
        }
コード例 #20
0
        /// <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);
            }
        }
コード例 #21
0
        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);
            }
        }
コード例 #22
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);
        }
コード例 #23
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);
        }
コード例 #24
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);
        }
コード例 #25
0
        protected override void ProcessRecord()
        {
            var fileName = Path;

            if (!Zip.IsPresent)
            {
                PerformInstallAction(() =>
                {
                    if (fileName == null)
                    {
                        //name of the zip file when not defined
                        fileName = $"{Project.Metadata.PackageName}{(string.IsNullOrEmpty(Project.Metadata.Version) ? "" : "-")}{Project.Metadata.Version}{Constants.SolutionExtension}";
                    }

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

                    if (!System.IO.Path.HasExtension(fileName))
                    {
                        fileName = fileName + Constants.SolutionExtension;
                    }

                    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}{Constants.PackageExtension}";
                        }

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

                        if (!System.IO.Path.HasExtension(fileName))
                        {
                            fileName = fileName + Constants.PackageExtension;
                        }

                        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);
                            }
                        }
                    });
            }
        }
コード例 #26
0
        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);
        }
コード例 #27
0
        public WebdeployProjectEmitter([NotNull] IConfiguration configuration, [NotNull] ITraceService trace, [ItemNotNull, NotNull, ImportMany] IEnumerable <IEmitter> emitters, [NotNull] IFileSystem fileSystem) : base(configuration, trace, emitters, fileSystem)
        {
            ISqlGenerator sqlGenerator = new SitecorePackageSqlGenerator();

            PackageWriter = new PackageWriter(fileSystem, sqlGenerator, OutputDirectory);
        }
コード例 #28
0
        public static bool RenameSave(string pathToSave, string newName)
        {
            try
            {
                string baseOldName = Path.GetFileNameWithoutExtension(pathToSave);
                string baseNewName = Path.GetFileNameWithoutExtension(newName);
                string output      = Path.ChangeExtension(Path.Combine(Path.GetDirectoryName(pathToSave), newName), ".lsv");

                using (var reader = new PackageReader(pathToSave))
                {
                    Package          package             = reader.Read();
                    AbstractFileInfo saveScreenshotImage = package.Files.FirstOrDefault(p => p.Name.EndsWith(".png"));
                    if (saveScreenshotImage != null)
                    {
                        saveScreenshotImage.Name = saveScreenshotImage.Name.Replace(Path.GetFileNameWithoutExtension(saveScreenshotImage.Name), baseNewName);

                        Trace.WriteLine($"Renamed internal screenshot '{saveScreenshotImage.Name}' in '{output}'.");
                    }

                    // Edit the saved date in the meta.lsf to avoid "corruption" messages

                    /*
                     * AbstractFileInfo metaFile = package.Files.FirstOrDefault(p => p.Name == "meta.lsf");
                     * if (metaFile != null)
                     * {
                     *      Resource resource;
                     *      System.IO.MemoryStream ms = null;
                     *      System.IO.Stream rsrcStream = null;
                     *      try
                     *      {
                     *              rsrcStream = metaFile.MakeStream();
                     *              using (var rsrcReader = new LSFReader(rsrcStream))
                     *              {
                     *                      resource = rsrcReader.Read();
                     *
                     *                      if (resource != null)
                     *                      {
                     *                              var saveTimeNode = resource.FindNode("SaveTime");
                     *
                     *                              if (saveTimeNode != null)
                     *                              {
                     *                                      NodeAttribute yearAtt = null;
                     *                                      NodeAttribute monthAtt = null;
                     *                                      NodeAttribute dayAtt = null;
                     *                                      NodeAttribute hoursAtt = null;
                     *                                      NodeAttribute minutesAtt = null;
                     *                                      NodeAttribute secondsAtt = null;
                     *                                      NodeAttribute millisecondsAtt = null;
                     *
                     *                                      saveTimeNode.Attributes.TryGetValue("Year", out yearAtt);
                     *                                      saveTimeNode.Attributes.TryGetValue("Month", out monthAtt);
                     *                                      saveTimeNode.Attributes.TryGetValue("Day", out dayAtt);
                     *                                      saveTimeNode.Attributes.TryGetValue("Hours", out hoursAtt);
                     *                                      saveTimeNode.Attributes.TryGetValue("Minutes", out minutesAtt);
                     *                                      saveTimeNode.Attributes.TryGetValue("Seconds", out secondsAtt);
                     *                                      saveTimeNode.Attributes.TryGetValue("Milliseconds", out millisecondsAtt);
                     *
                     *                                      var time = DateTime.Now;
                     *
                     *                                      Trace.WriteLine($"Year: {yearAtt.Type}");
                     *                                      Trace.WriteLine($"Month: {monthAtt.Type}");
                     *                                      Trace.WriteLine($"Day: {dayAtt.Type}");
                     *                                      Trace.WriteLine($"Hours: {hoursAtt.Type}");
                     *                                      Trace.WriteLine($"Minutes: {minutesAtt.Type}");
                     *                                      Trace.WriteLine($"Seconds: {secondsAtt.Type}");
                     *                                      Trace.WriteLine($"Milliseconds: {millisecondsAtt.Type}");
                     *
                     *                                      yearAtt.Value = (Byte)time.Year;
                     *                                      monthAtt.Value = (Byte)time.Month;
                     *                                      dayAtt.Value = (Byte)time.Day;
                     *                                      hoursAtt.Value = (Byte)time.Hour;
                     *                                      minutesAtt.Value = (Byte)time.Minute;
                     *                                      secondsAtt.Value = (Byte)time.Second;
                     *                                      millisecondsAtt.Value = (UInt16)time.Millisecond;
                     *
                     *                                      Trace.WriteLine($"Updated SaveTime in save's meta.lsf.");
                     *                              }
                     *                              else
                     *                              {
                     *                                      Trace.WriteLine($"Couldn't find SaveTime node '{String.Join(";", resource.Regions.Values.First().Children.Keys)}'.");
                     *                              }
                     *
                     *                              ms = new System.IO.MemoryStream(new byte[4096], true);
                     *                              var rscrWriter = new LSFWriter(ms, FileVersion.CurrentVersion);
                     *                              rscrWriter.Write(resource);
                     *                              ms.Position = 0;
                     *                              var data = ms.ToArray();
                     *
                     *                              if (!ms.CanRead) Trace.WriteLine("MemoryStream is not readable!");
                     *                              if(!ms.CanWrite) Trace.WriteLine("MemoryStream is not writable!");
                     *                              if(!rsrcStream.CanRead) Trace.WriteLine("rsrcStream is not readable!");
                     *                              if(!rsrcStream.CanWrite) Trace.WriteLine("rsrcStream is not writable!");
                     *
                     *                              rsrcStream.Write(data, 0, data.Length);
                     *                              ms.Close();
                     *                      }
                     *              }
                     *      }
                     *      finally
                     *      {
                     *              if (metaFile != null) metaFile.ReleaseStream();
                     *              if (ms != null) ms.Dispose();
                     *              if (rsrcStream != null) rsrcStream.Dispose();
                     *      }
                     * }
                     */
                    using (var writer = new PackageWriter(package, output))
                    {
                        writer.Version          = Package.CurrentVersion;
                        writer.Compression      = LSLib.LS.Enums.CompressionMethod.Zlib;
                        writer.CompressionLevel = CompressionLevel.DefaultCompression;
                        writer.Write();
                    }

                    File.SetLastWriteTime(output, File.GetLastWriteTime(pathToSave));
                    File.SetLastAccessTime(output, File.GetLastAccessTime(pathToSave));

                    return(true);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"Failed to rename save: {ex.ToString()}");
            }

            return(false);
        }
コード例 #29
0
ファイル: Packages.cs プロジェクト: viruswevh/ObscurCore
        private static void SymmetricPackageTest(string testName, List <FileInfo> data, PayloadLayoutScheme scheme, bool outputToFile = false, bool precomputed = false)
        {
            // Process of writing destroys preKey variable passed in for security
            // We must copy it to a local variable before reading the package back
            var preKey = KeyProviders.Alice.SymmetricKeys.ElementAt(
                StratCom.EntropySupplier.Next(KeyProviders.Alice.SymmetricKeys.Count()));

            var totalLen = data.Sum(file => file.Length);
            int expLen   = (int)(totalLen * 1.1);

            TimeSpan enc, dec;

            using (var ms = new MemoryStream(expLen)) {
                var sw            = Stopwatch.StartNew();
                var packageWriter = new PackageWriter(preKey, lowEntropy: false, layoutScheme: scheme); // low entropy = false

                foreach (var file in data)
                {
                    packageWriter.AddFile(file.FullName);
                }

                if (precomputed)
                {
                    if (scheme == PayloadLayoutScheme.Simple)
                    {
                        packageWriter.SetPayloadConfiguration(PayloadLayoutConfigurationFactory.CreateSimplePreallocated(data.Count));
                    }
                    else if (scheme == PayloadLayoutScheme.Frameshift)
                    {
                        packageWriter.SetPayloadConfiguration(
                            PayloadLayoutConfigurationFactory.CreateFrameshiftPrecomputedVariable(data.Count));
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }

                packageWriter.Write(ms, false);
                sw.Stop();
                enc = sw.Elapsed;
                sw.Reset();
                ms.Seek(0, SeekOrigin.Begin);
                if (outputToFile)
                {
                    using (var fs = new FileStream(
                               IOTestBase.PackageDestinationDirectory.FullName + Path.DirectorySeparatorChar + testName +
                               IOTestBase.PackageExtension, FileMode.Create)) {
                        ms.CopyTo(fs);
                    }
                    ms.Seek(0, SeekOrigin.Begin);
                }
                sw.Start();
                // Now read it back
                var readingPackage = PackageReader.FromStream(ms, KeyProviders.Alice);
                readingPackage.ReadToDirectory(IOTestBase.PackageDestinationDirectory.FullName, true);
                sw.Stop();
                dec = sw.Elapsed;
            }

            var megabytes = (double)totalLen / 1024 / 1024;

            Assert.Pass("{0} ms / {1:N2} MB/s -> {2} ms / {3:N2} MB/s.", enc.Milliseconds, (1000.0 / (double)enc.Milliseconds) * megabytes,
                        dec.Milliseconds, (1000.0 / (double)dec.Milliseconds) * megabytes);
        }
コード例 #30
0
ファイル: OsirisPane.cs プロジェクト: thunderysteak/lslib
        private void SaveSavegameDatabase()
        {
            var     packageReader = new PackageReader(storyFilePath.Text);
            Package package       = packageReader.Read();

            AbstractFileInfo globalsLsf = package.Files.FirstOrDefault(p => p.Name == "globals.lsf");

            if (globalsLsf == null)
            {
                MessageBox.Show("The specified package is not a valid savegame (globals.lsf not found)", "Load Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Load globals.lsf
            Resource resource;
            Stream   rsrcStream = globalsLsf.MakeStream();

            try
            {
                using (var rsrcReader = new LSFReader(rsrcStream))
                {
                    resource = rsrcReader.Read();
                }
            }
            finally
            {
                globalsLsf.ReleaseStream();
            }

            // Save story resource and pack into the Story.Story attribute in globals.lsf
            using (var storyStream = new MemoryStream())
            {
                var storyWriter = new StoryWriter();
                storyWriter.Write(storyStream, _story);

                LSLib.LS.Node storyNode = resource.Regions["Story"].Children["Story"][0];
                storyNode.Attributes["Story"].Value = storyStream.ToArray();
            }

            // Save globals.lsf
            var rewrittenStream = new MemoryStream();
            // TODO: Resave using original version
            var rsrcWriter = new LSFWriter(rewrittenStream, FileVersion.CurrentVersion);

            rsrcWriter.Write(resource);
            rewrittenStream.Seek(0, SeekOrigin.Begin);

            // Re-package global.lsf
            var            rewrittenPackage = new Package();
            StreamFileInfo globalsRepacked  = StreamFileInfo.CreateFromStream(rewrittenStream, "globals.lsf");

            rewrittenPackage.Files.Add(globalsRepacked);

            List <AbstractFileInfo> files = package.Files.Where(x => x.Name != "globals.lsf").ToList();

            rewrittenPackage.Files.AddRange(files);

            using (var packageWriter = new PackageWriter(rewrittenPackage, $"{storyFilePath.Text}.tmp"))
            {
                // TODO: Resave using original version and flags
                packageWriter.Version          = PackageVersion.V13;
                packageWriter.Compression      = CompressionMethod.Zlib;
                packageWriter.CompressionLevel = CompressionLevel.DefaultCompression;
                packageWriter.Write();
            }

            rewrittenStream.Dispose();
            packageReader.Dispose();

            // Create a backup of the original .lsf
            string backupPath = $"{storyFilePath.Text}.backup";

            if (!File.Exists(backupPath))
            {
                File.Move(storyFilePath.Text, backupPath);
            }
            else
            {
                File.Delete(storyFilePath.Text);
            }

            // Replace original savegame with new one
            File.Move($"{storyFilePath.Text}.tmp", storyFilePath.Text);
        }
コード例 #31
0
        protected override void ProcessRecord()
        {
            string 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);
                    }

                    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 = string.Format(
                                    "{0}-PS-{1}.zip", Project.Metadata.PackageName, Project.Metadata.Version);
                            }

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

                            using (var writer = new PackageWriter(fileName))
                            {
                                writer.Initialize(Installer.CreateInstallationContext());
                                PackageGenerator.GeneratePackage(Project, writer);
                            }
                        });
            }
        }
コード例 #32
0
        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);
                        }
                    }
                });
            }
        }
コード例 #33
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);
        }
コード例 #34
0
        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");
            }
        }
コード例 #35
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);
        }
コード例 #36
0
ファイル: ExportPackageCommand.cs プロジェクト: ostat/Console
        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))
                    {
                        var error = String.Format("The file '{0}' already exists.", fileName);
                        WriteError(new ErrorRecord(new IOException(error), error, 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 = string.Format(
                                "{0}-PS-{1}.zip", Project.Metadata.PackageName, Project.Metadata.Version);
                        }

                        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))
                        {
                            var error = String.Format("The file '{0}' already exists.", fileName);
                            WriteError(new ErrorRecord(new IOException(error), error, ErrorCategory.ResourceExists, fileName));
                        }

                        if (ShouldProcess(fileName, "Export package"))
                        {
                            using (var writer = new PackageWriter(fileName))
                            {
                                writer.Initialize(Installer.CreateInstallationContext());
                                PackageGenerator.GeneratePackage(Project, writer);
                            }
                        }
                    });
            }
        }