public override void Init(Manifest m, Dictionary<string, string> info) { loadInfo = info; // Avoid standard loading mechanisms so we // can display loadscreen as early as possible r = Game.Renderer; if (r == null) return; sheet = new Sheet(SheetType.BGRA, Platform.ResolvePath(loadInfo["Image"])); var res = r.Resolution; bounds = new Rectangle(0, 0, res.Width, res.Height); borderTop = new Sprite(sheet, new Rectangle(161, 128, 62, 33), TextureChannel.Alpha); borderBottom = new Sprite(sheet, new Rectangle(161, 223, 62, 33), TextureChannel.Alpha); borderLeft = new Sprite(sheet, new Rectangle(128, 161, 33, 62), TextureChannel.Alpha); borderRight = new Sprite(sheet, new Rectangle(223, 161, 33, 62), TextureChannel.Alpha); cornerTopLeft = new Sprite(sheet, new Rectangle(128, 128, 33, 33), TextureChannel.Alpha); cornerTopRight = new Sprite(sheet, new Rectangle(223, 128, 33, 33), TextureChannel.Alpha); cornerBottomLeft = new Sprite(sheet, new Rectangle(128, 223, 33, 33), TextureChannel.Alpha); cornerBottomRight = new Sprite(sheet, new Rectangle(223, 223, 33, 33), TextureChannel.Alpha); nodLogo = new Sprite(sheet, new Rectangle(0, 256, 256, 256), TextureChannel.Alpha); gdiLogo = new Sprite(sheet, new Rectangle(256, 256, 256, 256), TextureChannel.Alpha); evaLogo = new Sprite(sheet, new Rectangle(256, 64, 128, 64), TextureChannel.Alpha); nodPos = new float2(bounds.Width / 2 - 384, bounds.Height / 2 - 128); gdiPos = new float2(bounds.Width / 2 + 128, bounds.Height / 2 - 128); evaPos = new float2(bounds.Width - 43 - 128, 43); brightBlock = new Sprite(sheet, new Rectangle(320, 0, 16, 35), TextureChannel.Alpha); dimBlock = new Sprite(sheet, new Rectangle(336, 0, 16, 35), TextureChannel.Alpha); versionText = m.Mod.Version; }
public void Init(Manifest m, Dictionary<string, string> info) { var sheet = new Sheet(SheetType.BGRA, info["Image"]); var res = Game.Renderer.Resolution; bounds = new Rectangle(0, 0, res.Width, res.Height); sprite = new Sprite(sheet, new Rectangle(0, 0, 1024, 480), TextureChannel.Alpha); }
public DotNetNugDirectory(DirectoryName directoryName) : base(directoryName) { var manifestFile = GetChildFile("MANIFEST.json"); var manifestContent = manifestFile.ReadToEnd(); _manifest = JsonUtil.Get<Manifest>(manifestContent); }
public Manifest Create(Manifest manifest) { try { if (ApiUrl == string.Empty) { throw new Exception(Errors.ERR_CONFIGM_MISSING_APIURL); } var uriBuilder = new UriBuilder(ApiUrl + "/manifests"); if (DevKey != string.Empty) { uriBuilder.Query = "subscription-key=" + DevKey; } var strManifest = ModelManager.ModelToJson(manifest); var json = Rest.Post(uriBuilder.Uri, strManifest); manifest = ModelManager.JsonToModel<Manifest>(json); } catch (Exception err) { var errString = string.Format(Errors.ERR_CONFIGM_MODEL_NOT_CREATED, manifest.name) + ", " + err.Message; if (err.InnerException != null) errString += ", " + err.InnerException.Message; throw new Exception(errString); } return manifest; }
public ManifestModel(Manifest manifest) { this.ID = manifest.ID; this.Date = manifest.Date; this.Cost = manifest.Cost; this.Remark = manifest.Remark; }
public void ManifestValidatesManifestFiles() { // Arrange var manifest = new Manifest { Metadata = new ManifestMetadata { Id = "Foobar", Version = "1.0", Authors = "test-author", Description = "desc", }, Files = new List<ManifestFile> { new ManifestFile { Source = "|", Target = "<" }, new ManifestFile { Source = @"foo\bar\|>", Target = "lib" }, new ManifestFile { Source = @"foo\**\*.cs", Exclude = "Exclude|" } } }; // Act and Assert ExceptionAssert.Throws<ValidationException>(() => Manifest.Validate(manifest), "Source path '|' contains invalid characters.\r\nTarget path '<' contains invalid characters.\r\nSource path 'foo\\bar\\|>' contains invalid characters.\r\nExclude path 'Exclude|' contains invalid characters."); }
/// <summary> /// Creates a new digest mismatch exception. /// </summary> /// <param name="expectedDigest">The digest value the <see cref="Store.Model.Implementation"/> was supposed to have.</param> /// <param name="actualDigest">The digest value that was actually calculated.</param> /// <param name="expectedManifest">The <see cref="Manifest"/> that resulted in the <paramref name="expectedDigest"/>; may be <seealso langword="null"/>.</param> /// <param name="actualManifest">The <see cref="Manifest"/> that resulted in the <paramref name="actualDigest"/>.</param> public DigestMismatchException(string expectedDigest = null, string actualDigest = null, Manifest expectedManifest = null, Manifest actualManifest = null) : base(GetMessage(expectedDigest, actualDigest, expectedManifest, actualManifest)) { ExpectedDigest = expectedDigest; ActualDigest = actualDigest; ExpectedManifest = expectedManifest; ActualManifest = actualManifest; }
public static ManifestLoadResult CreateSuccess(string path, Manifest m) { return new ManifestLoadResult { Path = path, Manifest = m }; }
public ModContentPromptLogic(Widget widget, Manifest mod, ModContent content, Action continueLoading) { var panel = widget.Get("CONTENT_PROMPT_PANEL"); var headerTemplate = panel.Get<LabelWidget>("HEADER_TEMPLATE"); var headerLines = !string.IsNullOrEmpty(content.InstallPromptMessage) ? content.InstallPromptMessage.Replace("\\n", "\n").Split('\n') : new string[0]; var headerHeight = 0; foreach (var l in headerLines) { var line = (LabelWidget)headerTemplate.Clone(); line.GetText = () => l; line.Bounds.Y += headerHeight; panel.AddChild(line); headerHeight += headerTemplate.Bounds.Height; } panel.Bounds.Height += headerHeight; panel.Bounds.Y -= headerHeight / 2; var advancedButton = panel.Get<ButtonWidget>("ADVANCED_BUTTON"); advancedButton.Bounds.Y += headerHeight; advancedButton.OnClick = () => { Ui.OpenWindow("CONTENT_PANEL", new WidgetArgs { { "mod", mod }, { "content", content }, { "onCancel", Ui.CloseWindow } }); }; var quickButton = panel.Get<ButtonWidget>("QUICK_BUTTON"); quickButton.IsVisible = () => !string.IsNullOrEmpty(content.QuickDownload); quickButton.Bounds.Y += headerHeight; quickButton.OnClick = () => { var modFileSystem = new FileSystem.FileSystem(Game.Mods); modFileSystem.LoadFromManifest(mod); var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null); modFileSystem.UnmountAll(); var download = downloadYaml.FirstOrDefault(n => n.Key == content.QuickDownload); if (download == null) throw new InvalidOperationException("Mod QuickDownload `{0}` definition not found.".F(content.QuickDownload)); Ui.OpenWindow("PACKAGE_DOWNLOAD_PANEL", new WidgetArgs { { "download", new ModContent.ModDownload(download.Value) }, { "onSuccess", continueLoading } }); }; var backButton = panel.Get<ButtonWidget>("BACK_BUTTON"); backButton.Bounds.Y += headerHeight; backButton.OnClick = Ui.CloseWindow; Game.RunAfterTick(Ui.ResetTooltips); }
public ModContentLogic(Widget widget, Manifest mod, ModContent content, Action onCancel) { this.content = content; var panel = widget.Get("CONTENT_PANEL"); var modFileSystem = new FileSystem.FileSystem(Game.Mods); modFileSystem.LoadFromManifest(mod); var sourceYaml = MiniYaml.Load(modFileSystem, content.Sources, null); foreach (var s in sourceYaml) sources.Add(s.Key, new ModContent.ModSource(s.Value)); var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null); foreach (var d in downloadYaml) downloads.Add(d.Key, new ModContent.ModDownload(d.Value)); modFileSystem.UnmountAll(); scrollPanel = panel.Get<ScrollPanelWidget>("PACKAGES"); template = scrollPanel.Get<ContainerWidget>("PACKAGE_TEMPLATE"); var headerTemplate = panel.Get<LabelWidget>("HEADER_TEMPLATE"); var headerLines = !string.IsNullOrEmpty(content.HeaderMessage) ? content.HeaderMessage.Replace("\\n", "\n").Split('\n') : new string[0]; var headerHeight = 0; foreach (var l in headerLines) { var line = (LabelWidget)headerTemplate.Clone(); line.GetText = () => l; line.Bounds.Y += headerHeight; panel.AddChild(line); headerHeight += headerTemplate.Bounds.Height; } panel.Bounds.Height += headerHeight; panel.Bounds.Y -= headerHeight / 2; scrollPanel.Bounds.Y += headerHeight; var discButton = panel.Get<ButtonWidget>("CHECK_DISC_BUTTON"); discButton.Bounds.Y += headerHeight; discButton.IsVisible = () => discAvailable; discButton.OnClick = () => Ui.OpenWindow("DISC_INSTALL_PANEL", new WidgetArgs { { "afterInstall", () => { } }, { "sources", sources }, { "content", content } }); var backButton = panel.Get<ButtonWidget>("BACK_BUTTON"); backButton.Bounds.Y += headerHeight; backButton.OnClick = () => { Ui.CloseWindow(); onCancel(); }; PopulateContentList(); Game.RunAfterTick(Ui.ResetTooltips); }
public ModData( params string[] mods ) { Manifest = new Manifest( mods ); ObjectCreator = new ObjectCreator( Manifest ); LoadScreen = ObjectCreator.CreateObject<ILoadScreen>(Manifest.LoadScreen.Value); LoadScreen.Init(Manifest.LoadScreen.NodesDict.ToDictionary(x => x.Key, x => x.Value.Value)); LoadScreen.Display(); WidgetLoader = new WidgetLoader( this ); }
public ModData( params string[] mods ) { Manifest = new Manifest( mods ); ObjectCreator = new ObjectCreator( Manifest ); LoadScreen = ObjectCreator.CreateObject<ILoadScreen>(Manifest.LoadScreen); LoadScreen.Init(); LoadScreen.Display(); WidgetLoader = new WidgetLoader( this ); }
public InstallModLogic(Widget widget, Manifest mod) { var panel = widget.Get("INSTALL_MOD_PANEL"); var mods = mod.RequiresMods.Where(m => !Game.IsModInstalled(m)).Select(m => "{0} ({1})".F(m.Key, m.Value)); var text = string.Join(", ", mods); panel.Get<LabelWidget>("MOD_LIST").Text = text; panel.Get<ButtonWidget>("BACK_BUTTON").OnClick = Ui.CloseWindow; }
public ManifestEditorDialog(Manifest manifest, EditorMode mode = EditorMode.View) { InitializeComponent(); this.Icon = new Icon("Graphics\\EliteDangerousIcon.ico"); this.manifest = manifest; this.mode = mode; if (mode == EditorMode.View) SetUpViewer(); }
public Manifest ToManifest() { Manifest manifest = new Manifest() { ID = this.ID, Date = this.Date, Cost = this.Cost, Remark = this.Remark }; return manifest; }
public HttpResponseMessage UpdateManifest(Manifest manifest) { bool result = _bll.UpdateManifest(manifest); if (result) { return Request.CreateResponse(HttpStatusCode.OK, "更新成功"); } else { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "更新出错"); } }
public void NAME() { var m = new Manifest(); m.Name = "log4net"; m.Version = "1.1"; m.Files.Add(new ManifestEntry { Name = "log4net.dll" }); Console.WriteLine(JsonUtil.ToJson(m)); }
private static void AddManifestToLists(Manifest candidate, List<Manifest> candidates, List<Manifest> used) { bool isUsed = false; for (int x = 0; x < used.Count; x++) if (used[x].Equals(candidate)) isUsed = true; if (isUsed) used.Add(candidate); else candidates.Add(candidate); }
public HttpResponseMessage AddManifest(Manifest manifest) { manifest = _bll.AddManifest(manifest); var response = Request.CreateResponse<Manifest>(HttpStatusCode.Created, manifest); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { controller = "Manifests", id = manifest.ID })); return response; }
public static Manifest LoadManifestFromFile(string path) { Manifest m = new Manifest(); System.IO.StreamReader reader = new System.IO.StreamReader(path); string xmldata = reader.ReadToEnd(); reader.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xmldata); XmlNode manifest = doc.GetElementsByTagName(Manifest.Element.Manifest)[0]; m.Read(manifest); doc.Clone(); return m; }
public void CreateManifestFile() { var path = Path.GetFullPath("TestData\\ManifestFileV1"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); // Remove the file if it exists var filename = Config.ManifestFile(path); if (File.Exists(filename)) File.Delete(filename); var mf = new Manifest(path); mf.AddPage(1, 5, new KeyEx(new byte[] { 5 }, 5), new KeyEx(new byte[] { 5, 1 }, 5)); mf.AddPage(1, 6, new KeyEx(new byte[] { 6 }, 6), new KeyEx(new byte[] { 6, 1 }, 6)); mf.AddPage(1, 4, new KeyEx(new byte[] { 4 }, 4), new KeyEx(new byte[] { 4, 1 }, 4)); using (var mfSnap = mf.GetLatestManifest()) { PageRecord[] pg = mfSnap.GetPagesAtLevel(1); Assert.AreEqual(1, pg[0].Level); Assert.AreEqual(4, pg[0].Version); Assert.AreEqual(1, pg[1].Level); Assert.AreEqual(5, pg[1].Version); Assert.AreEqual(1, pg[2].Level); Assert.AreEqual(6, pg[2].Version); } mf = new Manifest(path); mf.ModifyPages(new List<PageRecord>{ new PageRecord(1, 8, new KeyEx( new byte[] { 16 }, 16), new KeyEx(new byte[] { 16, 1 }, 16) ), new PageRecord(1, 9, new KeyEx( new byte[] { 1 }, 1), new KeyEx(new byte[] { 1, 1 }, 1) ), new PageRecord(1, 16, new KeyEx( new byte[] { 10 }, 10), new KeyEx(new byte[] { 10, 1 }, 10) ) }, new List<PageRef>{ new PageRef{ Level = 1, Version = 6}, new PageRef{ Level = 1, Version = 4}, }); mf = new Manifest(path); using (var mfSnap = mf.GetLatestManifest()) { var pg = mfSnap.GetPagesAtLevel(1); Assert.AreEqual(1, pg[0].Level); Assert.AreEqual(9, pg[0].Version); Assert.AreEqual(1, pg[1].Level); Assert.AreEqual(5, pg[1].Version); Assert.AreEqual(1, pg[2].Level); Assert.AreEqual(16, pg[2].Version); Assert.AreEqual(1, pg[3].Level); Assert.AreEqual(8, pg[3].Version); } }
/// <summary> /// Initializes a new instance of the <see cref="L20nCore.Translator"/> class. /// </summary> public Translator() { m_Manifest = new Manifest(); m_Globals = new Dictionary<string, Objects.L20nObject>(); m_DummyObject = new Objects.Dummy(); CurrentLocale = null; m_DefaultContext = null; m_CurrentContext = null; AddSystemGlobals(); }
/// <summary> /// Creates a new manifest directory task. /// </summary> /// <param name="path">The path of the directory to operate on.</param> /// <param name="manifest">The contents of a <see cref="Implementations.Manifest"/> file describing the directory.</param> /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about IO tasks.</param> protected DirectoryOperation([NotNull] string path, [NotNull] Manifest manifest, [NotNull] ITaskHandler handler) { #region Sanity checks if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (manifest == null) throw new ArgumentNullException(nameof(manifest)); if (handler == null) throw new ArgumentNullException(nameof(handler)); #endregion Path = path; Manifest = manifest; Handler = handler; ElementPaths = Manifest.ListPaths(); }
// Initializes a new instance of the KeyValueStore. public KeyValueStore(string baseFileName, RazorCache cache) { if (!Directory.Exists (baseFileName)) Directory.CreateDirectory (baseFileName); _manifest = new Manifest (baseFileName); _manifest.Logger = RazorDBx.C5.Logger.Log; int memTableVersion = _manifest.CurrentVersion (0); CheckForIncompleteJournalRotation (baseFileName, memTableVersion); // Check for a previously aborted journal rotation. _currentJournaledMemTable = new JournaledMemTable (_manifest.BaseFileName, memTableVersion); // Create new journal for this run (and potentially load from disk, if there was data loaded previously). _cache = cache == null ? new RazorCache () : cache; }
private void Button_Click(object sender, RoutedEventArgs e) { Package p = new Package(); p.unique_identifier = "boo"; p.version = "1"; Manifest manifest = new Manifest(); manifest.AddItem(new Item("id1",".\\test.html","application/xhtml+xml", null)); manifest.AddItem(new Item("id2", ".\\test.html", "application/xhtml+xml", null)); manifest.AddItem(new Item("toc", txtNcxFile.Text, "application/x-dtbncx+xml", null)); p.myManifest = manifest; Metadata metadata = new Metadata(); p.myMetadata = metadata; metadata.title = "My title"; Spine s = new Spine("ncx"); s.AddItemRef(new ItemRef("id11","yes")); s.AddItemRef(new ItemRef("id12","yes")); p.mySpine = s; Guide g = new Guide(); g.AddReference(new Reference("toc", "title",txtNcxFile.Text)); g.AddReference(new Reference("toc1", "title2", ".//ref.html")); p.myGuide = g; TextWriter tw = serialise(p); txtPackage.Text = tw.ToString(); tw.Close(); NavigationCentereXtended ncx = new NavigationCentereXtended(); ncx.myDocAuthor = new DocAuthor("John h author"); ncx.myDocTitle = new DocTitle("My Book.."); ncx.myNavList.AddNavTarget(new NavTarget(new NavLabel("Nav Label 1"), new Content("content.html"))); ncx.myNavList.AddNavTarget(new NavTarget(new NavLabel("Nav Label 2"), new Content("content2.html"))); ncx.myNavMap.AddNavPoint(new NavPoint(1, "id1", "point class", new NavLabel("Nav Label 1"), new Content("srctext"))); ncx.myNavMap.AddNavPoint(new NavPoint(1, "id1", "point class2 ", new NavLabel("Nav Label 2"), new Content("srctext"))); ncx.myNcxHead = new NcxHead(); ncx.myNcxHead.myMeta = new Meta("content", "name"); ncx.myPageList.AddPageTarget(new PageTarget("id1", "type", "value", new NavLabel("txtLabel"), new Content("src1"))); ncx.myPageList.AddPageTarget(new PageTarget("id2", "type", "value", new NavLabel("txtLabel2"), new Content("src2"))); TextWriter tw2 = serialise(ncx); txtNcx.Text = tw2.ToString(); tw2.Close(); }
public void LevelMergeDuplicateValuesTest() { string path = Path.GetFullPath("TestData\\LevelMergeDuplicateValuesTest"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); foreach (string file in Directory.GetFiles(path)) { File.Delete(file); } int num_tables_to_merge = 4; int items_per_table = 2500; int totalData = 0; for (int i = 0; i < num_tables_to_merge; i++) { var mt = new MemTable(); for (int j = 0; j < items_per_table; j++) { int numToStore = j % 100; var key = new Key(new ByteArray(BitConverter.GetBytes(numToStore))); var value = new Value(BitConverter.GetBytes(j)); mt.Add(key, value); } mt.WriteToSortedBlockTable("TestData\\LevelMergeDuplicateValuesTest", 0, i); totalData += mt.Size; } var cache = new RazorCache(); var timer = new Stopwatch(); timer.Start(); Manifest mf = new Manifest("TestData\\LevelMergeDuplicateValuesTest"); SortedBlockTable.MergeTables(cache, mf, 1, new List<PageRef>{ new PageRef { Level = 0, Version = 0}, new PageRef { Level = 0, Version = 1}, new PageRef { Level = 0, Version = 2}, new PageRef { Level = 0, Version = 3} }, ExceptionHandling.ThrowAll, null); timer.Stop(); // Open the block table and scan it to check the stored values var sbt = new SortedBlockTable(cache, mf.BaseFileName, 1, 1); try { var pairs = sbt.Enumerate().ToList(); Assert.AreEqual(100, pairs.Count()); Assert.AreEqual(2400, BitConverter.ToInt32(pairs.First().Value.ValueBytes, 0)); } finally { sbt.Close(); } Console.WriteLine("Wrote a multilevel merge with duplicates at a throughput of {0} MB/s", (double)totalData / timer.Elapsed.TotalSeconds / (1024.0 * 1024.0)); }
private void CreateCourseDom() { var d = new DomDocument<Manifest>(); ADL.SCORM.Namespaces.LoadNamespaceMappings(d); pMessages = new UserMessageCollection(); if (d.Load(this.pMessages, this.pManifestFileInfo)) { this.pManifest = d.DocumentElement; } else { throw new ApplicationException("The imsmanifet that was selected could not be loaded."); } }
public ModData( params string[] mods ) { Manifest = new Manifest( mods ); ObjectCreator = new ObjectCreator( Manifest ); LoadScreen = ObjectCreator.CreateObject<ILoadScreen>(Manifest.LoadScreen); LoadScreen.Init(); LoadScreen.Display(); FileSystem.LoadFromManifest( Manifest ); ChromeProvider.Initialize( Manifest.Chrome ); SheetBuilder = new SheetBuilder( TextureChannel.Red ); CursorSheetBuilder = new CursorSheetBuilder( this ); AvailableMaps = FindMaps( mods ); WidgetLoader = new WidgetLoader( this ); }
public static void SaveManifestToFile(string path, Manifest m) { if (!System.IO.Directory.Exists(Manifest.ManifestFolder)) System.IO.Directory.CreateDirectory(Manifest.ManifestFolder); XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.Indentation = 4; writer.Formatting = Formatting.Indented; writer.Settings.NewLineHandling = NewLineHandling.Entitize; writer.Settings.NewLineOnAttributes = true; writer.WriteStartDocument(); writer.WriteComment("This file is generated by Android Manifest Editor (created by Peyman Abdi peyman[at]nemo-games[dot]com)."); m.Write(writer); writer.Close(); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); }
public void Init(Manifest m, Dictionary<string, string> info) { // Avoid standard loading mechanisms so we // can display the loadscreen as early as possible r = Game.Renderer; if (r == null) return; messages = info["Text"].Split(','); var s = new Sheet(info["Image"]); logo = new Sprite(s, new Rectangle(0, 0, 256, 256), TextureChannel.Alpha); stripe = new Sprite(s, new Rectangle(256, 0, 256, 256), TextureChannel.Alpha); stripeRect = new Rectangle(0, r.Resolution.Height / 2 - 128, r.Resolution.Width, 256); logoPos = new float2(r.Resolution.Width / 2 - 128, r.Resolution.Height / 2 - 128); }
public void DockerfileUrl(string sourceRepoBranch) { using TempFolderContext tempFolderContext = TestHelper.UseTempFolder(); const string SourceRepoUrl = "https://www.github.com/dotnet/dotnet-docker"; const string RepoName = "repo"; const string TagName = "tag"; // Create Dockerfile string DockerfileDir = $"1.0/{RepoName}/os"; Directory.CreateDirectory(Path.Combine(tempFolderContext.Path, DockerfileDir)); string dockerfileRelativePath = Path.Combine(DockerfileDir, "Dockerfile"); string dockerfileFullPath = PathHelper.NormalizePath(Path.Combine(tempFolderContext.Path, dockerfileRelativePath)); File.WriteAllText(dockerfileFullPath, "FROM base:tag"); // Create MCR tags metadata template file StringBuilder tagsMetadataTemplateBuilder = new StringBuilder(); tagsMetadataTemplateBuilder.AppendLine($"$(McrTagsYmlRepo:{RepoName})"); tagsMetadataTemplateBuilder.Append($"$(McrTagsYmlTagGroup:{TagName})"); string tagsMetadataTemplatePath = Path.Combine(tempFolderContext.Path, "tags.yaml"); File.WriteAllText(tagsMetadataTemplatePath, tagsMetadataTemplateBuilder.ToString()); string emptyFileName = "emptyFile.md"; string emptyFilePath = Path.Combine(tempFolderContext.Path, emptyFileName); File.WriteAllText(emptyFilePath, string.Empty); // Create manifest Manifest manifest = ManifestHelper.CreateManifest( ManifestHelper.CreateRepo(RepoName, new Image[] { ManifestHelper.CreateImage( ManifestHelper.CreatePlatform(dockerfileRelativePath, new string[] { TagName })) }, readme: emptyFileName, readmeTemplate: emptyFileName, mcrTagsMetadataTemplate: Path.GetFileName(tagsMetadataTemplatePath)) ); string manifestPath = Path.Combine(tempFolderContext.Path, "manifest.json"); File.WriteAllText(manifestPath, JsonConvert.SerializeObject(manifest)); // Load manifest IManifestOptionsInfo manifestOptions = ManifestHelper.GetManifestOptions(manifestPath); ManifestInfo manifestInfo = ManifestInfo.Load(manifestOptions); RepoInfo repo = manifestInfo.AllRepos.First(); Mock <IGitService> gitServiceMock = new Mock <IGitService>(); const string DockerfileSha = "random_sha"; if (sourceRepoBranch == null) { gitServiceMock .Setup(o => o.GetCommitSha(dockerfileFullPath, true)) .Returns(DockerfileSha); } // Execute generator string result = McrTagsMetadataGenerator.Execute( gitServiceMock.Object, manifestInfo, repo, SourceRepoUrl, sourceRepoBranch); TagsMetadata tagsMetadata = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build() .Deserialize <TagsMetadata>(result); string branchOrSha = sourceRepoBranch ?? DockerfileSha; Assert.Equal($"{SourceRepoUrl}/blob/{branchOrSha}/{DockerfileDir}/Dockerfile", tagsMetadata.Repos[0].TagGroups[0].Dockerfile); }
public WorkloadViewModel(string manifestPath) { var manifest = Manifest.FromManifestFile(manifestPath); Workloads = manifest.Workloads.CreateDerivedCollection(x => new WillowPackage(x.Value, manifest)); }
public void ReadFromReadsAllMetadataValues() { var references = new List <PackageReferenceSet> { new PackageReferenceSet( (NuGetFramework)null, new [] { "Test.dll" } ), new PackageReferenceSet( NuGetFramework.Parse("hello"), new [] { "world.winmd" } ) }; // Arrange var manifestStream = CreateManifest( id: "Test-Pack2", version: "1.0.0-alpha", title: "blah", authors: "Outercurve", licenseUrl: "http://nuget.org/license", projectUrl: "http://nuget.org/project", iconUrl: "https://nuget.org/icon", requiresLicenseAcceptance: true, developmentDependency: true, description: "This is not a description", summary: "This is a summary", releaseNotes: "Release notes", copyright: "Copyright 2012", language: "fr-FR", tags: "Test Unit", dependencies: new[] { new PackageDependency("Test", VersionRange.Parse("1.2.0")) }, assemblyReference: new[] { new FrameworkAssemblyReference("System.Data", new[] { NuGetFramework.Parse("4.0") }) }, references: references, serviceable: true, packageTypes: new[] { new PackageType("foo", new Version(2, 0, 0)), new PackageType("bar", new Version(0, 0)) }, minClientVersion: "2.0.1.0" ); var manifestMetadata = new ManifestMetadata { Id = "Test-Pack2", Version = NuGetVersion.Parse("1.0.0-alpha"), Description = "This is not a description", Authors = new[] { "Outercurve" }, RequireLicenseAcceptance = true, DevelopmentDependency = true, Summary = "This is a summary", ReleaseNotes = "Release notes", Copyright = "Copyright 2012", Language = "fr-FR", Tags = "Test Unit", Serviceable = true, DependencyGroups = new[] { new PackageDependencyGroup( NuGetFramework.AnyFramework, new [] { new PackageDependency("Test", VersionRange.Parse("1.2.0")) } ) }, FrameworkReferences = new[] { new FrameworkAssemblyReference("System.Data", new [] { NuGetFramework.Parse("4.0") } ) }, PackageAssemblyReferences = new[] { new PackageReferenceSet( (NuGetFramework)null, new [] { "Test.dll" } ), new PackageReferenceSet( NuGetFramework.Parse("hello"), new [] { "world.winmd" } ) }, PackageTypes = new[] { new PackageType("foo", new Version(2, 0, 0)), new PackageType("bar", new Version(0, 0)) }, MinClientVersionString = "2.0.1.0", }; manifestMetadata.SetLicenseUrl("http://nuget.org/license"); manifestMetadata.SetProjectUrl("http://nuget.org/project"); manifestMetadata.SetIconUrl("https://nuget.org/icon"); var expectedManifest = new Manifest(manifestMetadata); // Act var manifest = Manifest.ReadFrom(manifestStream, validateSchema: true); // Assert AssertManifest(expectedManifest, manifest); }
// this code is insanely stupid, and mostly my fault -- chrisf void PrepareMapResources(Manifest manifest, Map map) { Rules.LoadRules(manifest, map); tileset = Rules.TileSets[map.Tileset]; tilesetRenderer = new TileSetRenderer(tileset, new Size(manifest.TileSize, manifest.TileSize)); var shadowIndex = new int[] { 3, 4 }; var palette = new Palette(FileSystem.Open(tileset.Palette), shadowIndex); // required for desert terrain in RA var playerPalette = tileset.PlayerPalette ?? tileset.Palette; var shadowedPalette = new Palette(FileSystem.Open(playerPalette), shadowIndex); surface1.Bind(map, tileset, tilesetRenderer, palette, shadowedPalette); // construct the palette of tiles var palettes = new[] { tilePalette, actorPalette, resourcePalette }; foreach (var p in palettes) { p.Visible = false; p.SuspendLayout(); } var templateOrder = tileset.EditorTemplateOrder ?? new string[] { }; foreach (var tc in tileset.Templates.GroupBy(t => t.Value.Category).OrderBy(t => templateOrder.ToList().IndexOf(t.Key))) { var category = tc.Key ?? "(Uncategorized)"; var categoryHeader = new Label { BackColor = SystemColors.Highlight, ForeColor = SystemColors.HighlightText, Text = category, AutoSize = false, Height = 24, TextAlign = ContentAlignment.MiddleLeft, Width = tilePalette.ClientSize.Width, }; // hook this manually, anchoring inside FlowLayoutPanel is flaky. tilePalette.Resize += (_, e) => categoryHeader.Width = tilePalette.ClientSize.Width; if (tilePalette.Controls.Count > 0) { tilePalette.SetFlowBreak( tilePalette.Controls[tilePalette.Controls.Count - 1], true); } tilePalette.Controls.Add(categoryHeader); foreach (var t in tc) { try { var bitmap = tilesetRenderer.RenderTemplate((ushort)t.Key, palette); var ibox = new PictureBox { Image = bitmap, Width = bitmap.Width / 2, Height = bitmap.Height / 2, SizeMode = PictureBoxSizeMode.StretchImage }; var brushTemplate = new BrushTemplate { Bitmap = bitmap, N = t.Key }; ibox.Click += (_, e) => surface1.SetTool(new BrushTool(brushTemplate)); var template = t.Value; tilePalette.Controls.Add(ibox); tt.SetToolTip(ibox, "{1}:{0} ({2}x{3})".F(template.Image, template.Id, template.Size.X, template.Size.Y)); } catch { } } } var actorTemplates = new List <ActorTemplate>(); foreach (var a in Rules.Info.Keys) { try { var info = Rules.Info[a]; if (!info.Traits.Contains <RenderSimpleInfo>()) { continue; } var etf = info.Traits.GetOrDefault <EditorTilesetFilterInfo>(); if (etf != null && etf.ExcludeTilesets != null && etf.ExcludeTilesets.Contains(tileset.Id)) { continue; } if (etf != null && etf.RequireTilesets != null && !etf.RequireTilesets.Contains(tileset.Id)) { continue; } var templatePalette = shadowedPalette; var rsi = info.Traits.GetOrDefault <RenderSimpleInfo>(); // exception for desert buildings if (rsi != null && rsi.Palette != null && rsi.Palette.Contains("terrain")) { templatePalette = palette; } var template = RenderUtils.RenderActor(info, tileset, templatePalette); var ibox = new PictureBox { Image = template.Bitmap, Width = 32, Height = 32, SizeMode = PictureBoxSizeMode.Zoom, BorderStyle = BorderStyle.FixedSingle }; ibox.Click += (_, e) => surface1.SetTool(new ActorTool(template)); actorPalette.Controls.Add(ibox); tt.SetToolTip(ibox, "{0}".F(info.Name)); actorTemplates.Add(template); } catch { } } surface1.BindActorTemplates(actorTemplates); var resourceTemplates = new List <ResourceTemplate>(); foreach (var a in Rules.Info["world"].Traits.WithInterface <ResourceTypeInfo>()) { try { var template = RenderUtils.RenderResourceType(a, tileset.Extensions, shadowedPalette); var ibox = new PictureBox { Image = template.Bitmap, Width = 32, Height = 32, SizeMode = PictureBoxSizeMode.Zoom, BorderStyle = BorderStyle.FixedSingle }; ibox.Click += (_, e) => surface1.SetTool(new ResourceTool(template)); resourcePalette.Controls.Add(ibox); tt.SetToolTip(ibox, "{0}:{1}cr".F(template.Info.Name, template.Info.ValuePerUnit)); resourceTemplates.Add(template); } catch { } } surface1.BindResourceTemplates(resourceTemplates); foreach (var p in palettes) { p.Visible = true; p.ResumeLayout(); } miniMapBox.Image = Minimap.AddStaticResources(surface1.Map, Minimap.TerrainBitmap(surface1.Map, true)); propertiesToolStripMenuItem.Enabled = true; toolStripMenuItemProperties.Enabled = true; resizeToolStripMenuItem.Enabled = true; toolStripMenuItemResize.Enabled = true; saveToolStripMenuItem.Enabled = true; toolStripMenuItemSave.Enabled = true; saveAsToolStripMenuItem.Enabled = true; miniMapToPng.Enabled = true; PopulateActorOwnerChooser(); }
private void AssertManifest(Manifest expected, Manifest actual) { Assert.Equal(expected.Metadata.Id, actual.Metadata.Id); Assert.Equal(expected.Metadata.Version, actual.Metadata.Version); Assert.Equal(expected.Metadata.Description, actual.Metadata.Description); Assert.Equal(expected.Metadata.Authors, actual.Metadata.Authors); Assert.Equal(expected.Metadata.Copyright, actual.Metadata.Copyright); Assert.Equal(expected.Metadata.IconUrl, actual.Metadata.IconUrl); Assert.Equal(expected.Metadata.Language, actual.Metadata.Language); Assert.Equal(expected.Metadata.LicenseUrl, actual.Metadata.LicenseUrl); Assert.Equal(expected.Metadata.Owners, actual.Metadata.Owners); Assert.Equal(expected.Metadata.ProjectUrl, actual.Metadata.ProjectUrl); Assert.Equal(expected.Metadata.ReleaseNotes, actual.Metadata.ReleaseNotes); Assert.Equal(expected.Metadata.RequireLicenseAcceptance, actual.Metadata.RequireLicenseAcceptance); Assert.Equal(expected.Metadata.DevelopmentDependency, actual.Metadata.DevelopmentDependency); Assert.Equal(expected.Metadata.Summary, actual.Metadata.Summary); Assert.Equal(expected.Metadata.Tags, actual.Metadata.Tags); Assert.Equal(expected.Metadata.Serviceable, actual.Metadata.Serviceable); Assert.Equal(expected.Metadata.MinClientVersion, actual.Metadata.MinClientVersion); if (expected.Metadata.DependencyGroups != null) { var actualDependencyGroups = actual.Metadata.DependencyGroups.ToList(); var expectedDependencyGroups = expected.Metadata.DependencyGroups.ToList(); for (int i = 0; i < expectedDependencyGroups.Count; i++) { AssertDependencyGroup(expectedDependencyGroups[i], actualDependencyGroups[i]); } } if (expected.Metadata.FrameworkReferences != null) { var actualFrameworkReferences = actual.Metadata.FrameworkReferences.ToList(); var expectedFrameworkReferences = expected.Metadata.FrameworkReferences.ToList(); for (int i = 0; i < expectedFrameworkReferences.Count; i++) { AssertFrameworkAssemblies(expectedFrameworkReferences[i], actualFrameworkReferences[i]); } } if (expected.Metadata.PackageAssemblyReferences != null) { var actualAssemblyReferences = actual.Metadata.PackageAssemblyReferences.ToList(); var expectedAssemblyReferences = expected.Metadata.PackageAssemblyReferences.ToList(); for (int i = 0; i < expectedAssemblyReferences.Count; i++) { AssertReference(expectedAssemblyReferences[i], actualAssemblyReferences[i]); } } if (expected.Files != null) { var actualFiles = actual.Files.ToList(); var expectedFiles = expected.Files.ToList(); for (int i = 0; i < expectedFiles.Count; i++) { AssertFile(expectedFiles[i], actualFiles[i]); } } if (expected.Metadata.PackageTypes != null) { var actualPackageTypes = actual.Metadata.PackageTypes.ToList(); var expectedPackageTypes = expected.Metadata.PackageTypes.ToList(); Assert.Equal(expectedPackageTypes.Count, actualPackageTypes.Count); for (int i = 0; i < expectedPackageTypes.Count; i++) { Assert.Equal(expectedPackageTypes[i], actualPackageTypes[i]); } } }
static void Main(string[] args) { var path = ""; if (args.Length == 1) { path = Path.GetFullPath(args[0]); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } Environment.CurrentDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location); var propertyProvider = new PropertyProvider() { { "version", GitVersionInformation.NuGetVersionV2 } }; var packageBuilder = new PackageBuilder(); using (var spec = File.OpenRead(Path.Combine("Assets", "Costura.Fody.nuspec"))) { var manifest = Manifest.ReadFrom(spec, propertyProvider, false); packageBuilder.Populate(manifest.Metadata); } packageBuilder.PopulateFiles("", new[] { new ManifestFile { Source = "Costura.Fody.dll", Target = "" }, new ManifestFile { Source = "Costura.Fody.pdb", Target = "" }, new ManifestFile { Source = "Costura.Tasks.dll", Target = "" }, new ManifestFile { Source = "Costura.Tasks.pdb", Target = "" } }); #if DEBUG var config = "Debug"; #else var config = "Release"; #endif packageBuilder.PopulateFiles("..\\..\\..\\Costura.Lib\\bin\\" + config, new[] { new ManifestFile { Source = "Costura.dll", Target = "lib/dotnet" }, new ManifestFile { Source = "Costura.pdb", Target = "lib/dotnet" }, new ManifestFile { Source = "Costura.dll", Target = "lib/portable-net+sl+win+wpa+wp" }, new ManifestFile { Source = "Costura.pdb", Target = "lib/portable-net+sl+win+wpa+wp" } }); // TODO NetStandard not supported by Costura //packageBuilder.PopulateFiles($"..\\..\\..\\Costura.LibNetStandard\\bin\\{config}\\netstandard1.4", new[] { // new ManifestFile { Source = "Costura.dll", Target = "lib/netstandard1.4" }, // new ManifestFile { Source = "Costura.pdb", Target = "lib/netstandard1.4" } //}); packageBuilder.PopulateFiles("Assets", new[] { new ManifestFile { Source = "install.ps1", Target = "tools" }, new ManifestFile { Source = "uninstall.ps1", Target = "tools" }, new ManifestFile { Source = "Costura.Fody.targets", Target = "build/dotnet" }, new ManifestFile { Source = "Costura.Fody.targets", Target = "build/portable-net+sl+win+wpa+wp" } }); var packagePath = Path.Combine(path, $"{packageBuilder.Id}.{packageBuilder.Version}.nupkg"); using (var file = new FileStream(packagePath, FileMode.Create)) { Console.WriteLine($"Saving file {packagePath}"); packageBuilder.Save(file); } }
protected HostViewModelBase(Host currentHost, IEnumerable <Manifest> manifests, Manifest currentManifest, IEnumerable <BizTalkBaseObject> breadCrumbs, IEnumerable <BizTalkApplication> applications, IEnumerable <Host> hosts) : base(manifests, currentManifest, breadCrumbs, applications, hosts) { CurrentHost = currentHost; }
public static void WriteManifest(Manifest manifest, System.IO.Stream output) { }
public void CreateDefaultScopes_WithManifest_ReturnsScopesAndCollections() { // Arrange var factory = new ScopeFactory(new Mock <ILogger <Scope> >().Object, CreateCollectionFactoryMock()); var manifest = new Manifest { scopes = new List <ScopeDef> { new ScopeDef { name = "scope1", uid = "100", collections = new List <CollectionDef> { new CollectionDef { name = "collection1", uid = "1" }, new CollectionDef { name = "collection2", uid = "2" } } }, new ScopeDef { name = "scope2", uid = "200", collections = new List <CollectionDef> { new CollectionDef { name = "collection3", uid = "fe" }, new CollectionDef { name = "collection4", uid = "ff" } } } } }; // Act var result = factory.CreateScopes(CreateBucketMock(factory), manifest).ToList(); // Assert var scope1 = result.First(p => p.Name == "scope1"); Assert.Equal("100", scope1.Id); var collection1 = scope1["collection1"]; Assert.Equal("collection1", collection1.Name); Assert.Equal((uint?)1, collection1.Cid); var collection2 = scope1["collection2"]; Assert.Equal("collection2", collection2.Name); Assert.Equal((uint?)2, collection2.Cid); var scope2 = result.First(p => p.Name == "scope2"); Assert.Equal("100", scope1.Id); var collection3 = scope2["collection3"]; Assert.Equal("collection3", collection3.Name); Assert.Equal((uint?)0xfe, collection3.Cid); var collection4 = scope2["collection4"]; Assert.Equal("collection4", collection4.Name); Assert.Equal((uint?)0xff, collection4.Cid); }
void FileStreamTest_OnAssetStreamFailed(Manifest metaData, System.IO.Stream stream) { succeed = 1; }
public async Task IngestKustoImageInfoCommand_MultipleRepos() { using TempFolderContext tempFolderContext = TestHelper.UseTempFolder(); string repo1Image1DockerfilePath = DockerfileHelper.CreateDockerfile("1.0/sdk/os", tempFolderContext); string repo1Image2DockerfilePath = DockerfileHelper.CreateDockerfile("1.0/sdk/os2", tempFolderContext); string repo2Image2DockerfilePath = DockerfileHelper.CreateDockerfile("2.0/sdk/os", tempFolderContext); Manifest manifest = CreateManifest( CreateRepo("r1", CreateImage( new Platform[] { CreatePlatform(repo1Image1DockerfilePath, new string[] { "t1" }), CreatePlatform(repo1Image2DockerfilePath, new string[] { "t2" }) }, productVersion: "1.0.2", sharedTags: new Dictionary <string, Tag> { { "st1", new Tag() } })), CreateRepo("r2", CreateImage( new Platform[] { CreatePlatform(repo2Image2DockerfilePath, new string[] { "t3" }) }, productVersion: "2.0.5")) ); string manifestPath = Path.Combine(tempFolderContext.Path, "manifest.json"); File.WriteAllText(manifestPath, JsonConvert.SerializeObject(manifest)); ImageArtifactDetails srcImageArtifactDetails = new() { Repos = { new RepoData { Repo = "r1", Images = { new ImageData { Manifest = new ManifestData { Created = new DateTime(2020, 4, 20, 21, 57, 00, DateTimeKind.Utc), Digest = "abc", SharedTags = new List <string> { "st1" } }, Platforms = { { Helpers.ImageInfoHelper.CreatePlatform( repo1Image1DockerfilePath, created: new DateTime(2020, 4, 20, 21, 56, 50, DateTimeKind.Utc), digest: "def", simpleTags: new List <string> { "t1" }, layers: new List <string> { "qwe", "asd" }) }, { Helpers.ImageInfoHelper.CreatePlatform( repo1Image2DockerfilePath, created: new DateTime(2020, 4, 20, 21, 56, 56, DateTimeKind.Utc), digest: "ghi", simpleTags: new List <string> { "t2" }, layers: new List <string> { "qwe" }) } }, ProductVersion = "1.0.2", } } }, new RepoData { Repo = "r2", Images = { new ImageData { Platforms = { Helpers.ImageInfoHelper.CreatePlatform( repo2Image2DockerfilePath, created: new DateTime(2020, 4, 20, 21, 56, 58, DateTimeKind.Utc), digest: "jkl", simpleTags: new List <string> { "t3" }, layers: new List <string> { "zxc" }) }, ProductVersion = "2.0.5" } } } } }; string expectedImageData = @"""def"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os/Dockerfile"",""r1"",""2020-04-20 21:56:50"" ""t1"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os/Dockerfile"",""r1"",""2020-04-20 21:56:50"" ""ghi"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os2/Dockerfile"",""r1"",""2020-04-20 21:56:56"" ""t2"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os2/Dockerfile"",""r1"",""2020-04-20 21:56:56"" ""jkl"",""amd64"",""Linux"",""Ubuntu 20.04"",""2.0.5"",""2.0/sdk/os/Dockerfile"",""r2"",""2020-04-20 21:56:58"" ""t3"",""amd64"",""Linux"",""Ubuntu 20.04"",""2.0.5"",""2.0/sdk/os/Dockerfile"",""r2"",""2020-04-20 21:56:58"""; expectedImageData = expectedImageData.NormalizeLineEndings(Environment.NewLine).Trim(); string expectedLayerData = @"""qwe"",""0"",""2"",""def"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os/Dockerfile"",""r1"",""2020-04-20 21:56:50"" ""asd"",""0"",""1"",""def"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os/Dockerfile"",""r1"",""2020-04-20 21:56:50"" ""qwe"",""0"",""1"",""ghi"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.2"",""1.0/sdk/os2/Dockerfile"",""r1"",""2020-04-20 21:56:56"" ""zxc"",""0"",""1"",""jkl"",""amd64"",""Linux"",""Ubuntu 20.04"",""2.0.5"",""2.0/sdk/os/Dockerfile"",""r2"",""2020-04-20 21:56:58"""; expectedLayerData = expectedLayerData.NormalizeLineEndings(Environment.NewLine).Trim(); await ValidateExecuteAsync(tempFolderContext, manifestPath, srcImageArtifactDetails, expectedImageData, expectedLayerData); }
public async Task SyndicatedTag() { using TempFolderContext tempFolderContext = TestHelper.UseTempFolder(); string repo1Image1DockerfilePath = DockerfileHelper.CreateDockerfile("1.0/sdk/os", tempFolderContext); Manifest manifest = CreateManifest( CreateRepo("repo1", CreateImage( new Platform[] { CreatePlatform(repo1Image1DockerfilePath, new string[] { "t1", "t2", "t3" }) }, productVersion: "1.0.5")) ); const string syndicatedRepository = "repo2"; Platform platform = manifest.Repos.First().Images.First().Platforms.First(); platform.Tags["t1"].Syndication = new TagSyndication { Repo = syndicatedRepository }; platform.Tags["t2"].Syndication = new TagSyndication { Repo = syndicatedRepository, DestinationTags = new string[] { "t2a", "t2b" } }; string manifestPath = Path.Combine(tempFolderContext.Path, "manifest.json"); File.WriteAllText(manifestPath, JsonConvert.SerializeObject(manifest)); ImageArtifactDetails srcImageArtifactDetails = new() { Repos = { new RepoData { Repo = "repo1", Images = { new ImageData { Platforms = { Helpers.ImageInfoHelper.CreatePlatform( repo1Image1DockerfilePath, created: new DateTime(2020, 4, 20, 21, 56, 58, DateTimeKind.Utc), digest: "jkl", simpleTags: new List <string> { "t1", "t2", "t3" }, layers: new List <string> { "zxc" }) }, ProductVersion = "1.0.5" } } } } }; string expectedImageData = @"""jkl"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo1"",""2020-04-20 21:56:58"" ""jkl"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo2"",""2020-04-20 21:56:58"" ""t1"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo1"",""2020-04-20 21:56:58"" ""t1"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo2"",""2020-04-20 21:56:58"" ""t2"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo1"",""2020-04-20 21:56:58"" ""t2a"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo2"",""2020-04-20 21:56:58"" ""t2b"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo2"",""2020-04-20 21:56:58"" ""t3"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo1"",""2020-04-20 21:56:58"""; expectedImageData = expectedImageData.NormalizeLineEndings(Environment.NewLine).Trim(); string expectedLayerData = @"""zxc"",""0"",""1"",""jkl"",""amd64"",""Linux"",""Ubuntu 20.04"",""1.0.5"",""1.0/sdk/os/Dockerfile"",""repo1"",""2020-04-20 21:56:58"""; expectedLayerData = expectedLayerData.NormalizeLineEndings(Environment.NewLine).Trim(); await ValidateExecuteAsync(tempFolderContext, manifestPath, srcImageArtifactDetails, expectedImageData, expectedLayerData); }
// Methods public static void WriteManifest(Manifest manifest) { }
/// <summary> /// For testing purposes. Wipes contents of this workspace /// </summary> public static void Reset() { Incoming = new Dictionary <string, byte[]>(); Repository = new Dictionary <string, byte[]>(); _manifest = new Manifest(); }
protected override async Task <int> ExecuteInternalAsync() { Manifest manifest = await GetManifestAsync(); IEnumerable <ILibraryOperationResult> validationResults = await manifest.GetValidationResultsAsync(CancellationToken.None); if (!validationResults.All(r => r.Success)) { LogErrors(validationResults.SelectMany(r => r.Errors)); return(0); } IEnumerable <ILibraryInstallationState> installedLibraries = ValidateParametersAndGetLibrariesToUpdate(manifest); if (installedLibraries == null || !installedLibraries.Any()) { Logger.Log(string.Format(Resources.Text.NoLibraryFoundToUpdate, LibraryName.Value), LogLevel.Operation); return(0); } ILibraryInstallationState libraryToUpdate = null; if (installedLibraries.Count() > 1) { Logger.Log(string.Format(Resources.Text.MoreThanOneLibraryFoundToUpdate, LibraryName.Value), LogLevel.Operation); libraryToUpdate = LibraryResolver.ResolveLibraryByUserChoice(installedLibraries, HostEnvironment); } else { libraryToUpdate = installedLibraries.First(); } string newLibraryId = null; if (ToVersion.HasValue()) { newLibraryId = LibraryIdToNameAndVersionConverter.Instance.GetLibraryId(libraryToUpdate.Name, ToVersion.Value(), libraryToUpdate.ProviderId); } else { string latestVersion = await GetLatestVersionAsync(libraryToUpdate, CancellationToken.None); if (!string.IsNullOrEmpty(latestVersion)) { newLibraryId = LibraryIdToNameAndVersionConverter.Instance.GetLibraryId(libraryToUpdate.Name, latestVersion, libraryToUpdate.ProviderId); } } if (newLibraryId == null || newLibraryId == libraryToUpdate.LibraryId) { Logger.Log(string.Format(Resources.Text.LatestVersionAlreadyInstalled, libraryToUpdate.LibraryId), LogLevel.Operation); return(0); } Manifest backup = manifest.Clone(); string oldLibraryName = libraryToUpdate.Name; manifest.ReplaceLibraryId(libraryToUpdate, newLibraryId); // Delete files from old version of the library. await backup.RemoveUnwantedFilesAsync(manifest, CancellationToken.None); IEnumerable <ILibraryOperationResult> results = await manifest.RestoreAsync(CancellationToken.None); ILibraryOperationResult result = null; foreach (ILibraryOperationResult r in results) { if (!r.Success && r.Errors.Any(e => e.Message.Contains(libraryToUpdate.LibraryId))) { result = r; break; } else if (r.Success && r.InstallationState.LibraryId == libraryToUpdate.LibraryId && r.InstallationState.ProviderId == libraryToUpdate.ProviderId && r.InstallationState.DestinationPath == libraryToUpdate.DestinationPath) { result = r; break; } } if (result.Success) { await manifest.SaveAsync(HostEnvironment.EnvironmentSettings.ManifestFileName, CancellationToken.None); Logger.Log(string.Format(Resources.Text.LibraryUpdated, oldLibraryName, newLibraryId), LogLevel.Operation); } else if (result.Errors != null) { if (ToVersion.HasValue()) { Logger.Log(string.Format(Resources.Text.UpdateLibraryFailed, oldLibraryName, ToVersion.Value()), LogLevel.Error); } else { Logger.Log(string.Format(Resources.Text.UpdateLibraryToLatestFailed, oldLibraryName), LogLevel.Error); } foreach (IError error in result.Errors) { Logger.Log(string.Format("[{0}]: {1}", error.Code, error.Message), LogLevel.Error); } } return(0); }
void WriteCache(IEnumerable <Bundle> bundles) { var cache = Container.Resolve <IBundleCollectionCache>(); cache.Write(Manifest.Static(bundles)); }
public void ManifestGroupDependencySetsByTargetFrameworkAndPutNullFrameworkFirst() { // Arrange var manifest = new Manifest( new ManifestMetadata { Id = "Foobar", Version = NuGetVersion.Parse("1.0"), Authors = new[] { "test-author" }, Description = "desc", DependencyGroups = new[] { new PackageDependencyGroup( NuGetFramework.Parse(".NETFramework40"), new [] { new PackageDependency("B") } ), new PackageDependencyGroup( NuGetFramework.AnyFramework, new [] { new PackageDependency("A") } ), new PackageDependencyGroup( NuGetFramework.AnyFramework, new [] { new PackageDependency("C") } ), new PackageDependencyGroup( NuGetFramework.Parse("Silverlight35"), new [] { new PackageDependency("D") } ), new PackageDependencyGroup( NuGetFramework.Parse("net40"), new [] { new PackageDependency("E") } ), new PackageDependencyGroup( NuGetFramework.Parse("sl35"), new [] { new PackageDependency("F") } ), new PackageDependencyGroup( NuGetFramework.Parse("winrt45"), new List <PackageDependency>() ), } } ); // Act var dependencyGroups = manifest.Metadata.DependencyGroups.ToList(); // Assert Assert.Equal(4, dependencyGroups.Count); Assert.Equal(NuGetFramework.AnyFramework, dependencyGroups[0].TargetFramework); Assert.Equal(2, dependencyGroups[0].Packages.Count()); Assert.Equal("A", dependencyGroups[0].Packages.First().Id); Assert.Equal("C", dependencyGroups[0].Packages.Last().Id); Assert.Equal(NuGetFramework.Parse(".NETFramework, Version=4.0"), dependencyGroups[1].TargetFramework); Assert.Equal(2, dependencyGroups[1].Packages.Count()); Assert.Equal("B", dependencyGroups[1].Packages.First().Id); Assert.Equal("E", dependencyGroups[1].Packages.Last().Id); Assert.Equal(NuGetFramework.Parse("Silverlight, Version=3.5"), dependencyGroups[2].TargetFramework); Assert.Equal(2, dependencyGroups[2].Packages.Count()); Assert.Equal("D", dependencyGroups[2].Packages.First().Id); Assert.Equal("F", dependencyGroups[2].Packages.Last().Id); Assert.Equal(NuGetFramework.Parse("WinRT, Version=4.5"), dependencyGroups[3].TargetFramework); Assert.Equal(0, dependencyGroups[3].Packages.Count()); }
/// <summary> /// Build a new project from source /// </summary> /// <param name="cleanOutputDir"></param> public void Build(bool cleanOutputDir = true) { var startTime = DateTime.Now; Records.Clear(); Record($"---- DBP Build begin at {startTime.ToString()} ----"); var fullSourceRoot = Path.Combine(Directory.GetCurrentDirectory(), Manifest.SourceDir); var fullOutputRoot = Path.Combine(Directory.GetCurrentDirectory(), Manifest.OutputDir); if (cleanOutputDir) { try { Directory.Delete(fullOutputRoot, true); } catch (Exception ex) { SenparcTrace.BaseExceptionLog(ex); } } if (!Directory.Exists(fullOutputRoot)) { Directory.CreateDirectory(fullOutputRoot); } //Copy all files Record($"===== start copy all files ====="); CopyDirectory(fullSourceRoot, fullOutputRoot); Record($"---- end copy all files ----"); Record($"---- {(DateTime.Now - startTime).TotalSeconds} seconds ----"); int groupIndex = 0; foreach (var configGroup in Manifest.ConfigGroup) { groupIndex++; Record($"config group: {groupIndex}"); var omitFiles = configGroup.OmitFiles.SelectMany(f => Directory.GetFiles(fullOutputRoot, f, SearchOption.AllDirectories)).ToList(); var files = configGroup.Files.SelectMany(f => Directory.GetFiles(fullOutputRoot, f, SearchOption.AllDirectories)) .Where(f => !omitFiles.Contains(f)).ToList(); foreach (var file in files) { Record($"dynamic file: {file}"); var newContent = new StringBuilder(); string fileContent = null; using (var fs = new FileStream(file, FileMode.Open)) { using (var sr = new StreamReader(fs, Encoding.UTF8)) { fileContent = sr.ReadToEnd(); } } #region File Mark if (fileContent.Contains(FILE_MARK_PREFIX)) { //judgement whether this file can keep var regex = new Regex($@"{FILE_MARK_PREFIX}(?<kw>[^\r\n ,]*)"); var match = regex.Match(fileContent); if (match.Success && !configGroup.KeepFileConiditions.Any(z => z == match.Groups["kw"].Value)) { //remove this file Record($"remove this file"); try { File.Delete(file); } catch (Exception ex) { Record($"delete file error:{ex}"); } continue; } } #endregion #region ReplaceContents XDocument xml = null; dynamic json = null; foreach (var replaceContent in configGroup.ReplaceContents) { #region Xml if (replaceContent.XmlContent != null) { try { xml = xml ?? XDocument.Parse(fileContent); ReplaceXmlElements(xml.Root, replaceContent.XmlContent); } catch (Exception ex) { Record($"Xml file format wrong"); SenparcTrace.SendCustomLog("Xml file format wrong", ex.Message); } } #endregion #region Json else if (replaceContent.JsonContent != null) { try { var serializer = new JavaScriptSerializer(); json = serializer.Deserialize(fileContent, typeof(object)); ReplaceJsonNodes(json, replaceContent.JsonContent); } catch (Exception ex) { Record($"Json file format wrong"); SenparcTrace.SendCustomLog("Json file format wrong", ex.Message); } } #endregion } if (xml != null) { fileContent = xml.ToString(); Record($"Xml file changed."); } else if (json != null) { fileContent = JsonConvert.SerializeObject(json); Record($"Json file changed."); } #endregion #region Content Mark if (fileContent.Contains(BEGIN_MARK_PERFIX)) { var lines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); var keep = true; var removeBlockCount = 0; var i = 0; foreach (var line in lines) { i++; if (keep) { if (line.Contains(BEGIN_MARK_PERFIX)) { //begin to check Conditions if (!configGroup.KeepContentConiditions.Any(z => line.Contains(z))) { //drop content keep = false; removeBlockCount++; continue; } } //keep newContent.Append(line); if (i != lines.Count()) { newContent.Append(Environment.NewLine); //not last Item } } else { //not keep, waiting the end mark if (line.Contains(END_MARK)) { keep = true; } } } } else { newContent.Append(fileContent); } #endregion #region save new file //save the file to OutputDir using (var fs = new FileStream(file, FileMode.Truncate)) { var sw = new StreamWriter(fs, Encoding.UTF8); sw.Write(newContent.ToString()); sw.Flush(); fs.Flush(true); Record($"modified and saved a new file: {file}"); } #endregion } } var manifestFileName = Path.Combine(fullOutputRoot, "manifest.config"); using (var logFs = new FileStream(manifestFileName, FileMode.Create)) { var sw = new StreamWriter(logFs, Encoding.UTF8); sw.Write(Manifest.ToJson()); sw.Flush(); logFs.Flush(true); } Record($"saved manifest file: {manifestFileName}"); var logFileName = Path.Combine(fullOutputRoot, "DPB.log"); Record($"saved log file: {logFileName}"); Record($"===== DPB Build Finished ====="); Record($"---- Total time: {(DateTime.Now - startTime).TotalSeconds} seconds ----"); using (var logFs = new FileStream(logFileName, FileMode.Create)) { var sw = new StreamWriter(logFs, Encoding.UTF8); var logs = new StringBuilder(); Records.ForEach(z => logs.AppendLine(z)); sw.Write(logs.ToString()); sw.Flush(); logFs.Flush(true); } }
public void DuplicatedPlatform() { using TempFolderContext tempFolderContext = TestHelper.UseTempFolder(); const string SourceRepoUrl = "https://www.github.com/dotnet/dotnet-docker"; const string RepoName = "repo"; const string SourceBranch = "branch"; // Create MCR tags metadata template file StringBuilder tagsMetadataTemplateBuilder = new StringBuilder(); tagsMetadataTemplateBuilder.AppendLine($"$(McrTagsYmlRepo:{RepoName})"); tagsMetadataTemplateBuilder.AppendLine($"$(McrTagsYmlTagGroup:concreteTagA)"); string tagsMetadataTemplatePath = Path.Combine(tempFolderContext.Path, "tags.yaml"); File.WriteAllText(tagsMetadataTemplatePath, tagsMetadataTemplateBuilder.ToString()); string emptyFileName = "emptyFile.md"; string emptyFilePath = Path.Combine(tempFolderContext.Path, emptyFileName); File.WriteAllText(emptyFilePath, string.Empty); // Create manifest Manifest manifest = ManifestHelper.CreateManifest( ManifestHelper.CreateRepo(RepoName, new Image[] { ManifestHelper.CreateImage( new Platform[] { ManifestHelper.CreatePlatform( DockerfileHelper.CreateDockerfile($"1.0/{RepoName}/os", tempFolderContext), new string[] { "concreteTagZ", "concreteTagA" }) }, sharedTags: new Dictionary <string, Tag> { { "shared1", new Tag() }, { "latest", new Tag() }, }), ManifestHelper.CreateImage( new Platform[] { ManifestHelper.CreatePlatform( DockerfileHelper.CreateDockerfile($"1.0/{RepoName}/os", tempFolderContext), Array.Empty <string>()) }, sharedTags: new Dictionary <string, Tag> { { "shared2", new Tag() } }) }, readme: emptyFileName, readmeTemplate: emptyFileName, mcrTagsMetadataTemplate: Path.GetFileName(tagsMetadataTemplatePath)) ); string manifestPath = Path.Combine(tempFolderContext.Path, "manifest.json"); File.WriteAllText(manifestPath, JsonConvert.SerializeObject(manifest)); // Load manifest IManifestOptionsInfo manifestOptions = ManifestHelper.GetManifestOptions(manifestPath); ManifestInfo manifestInfo = ManifestInfo.Load(manifestOptions); RepoInfo repo = manifestInfo.AllRepos.First(); Mock <IGitService> gitServiceMock = new Mock <IGitService>(); // Execute generator string result = McrTagsMetadataGenerator.Execute( gitServiceMock.Object, manifestInfo, repo, SourceRepoUrl, SourceBranch); TagsMetadata tagsMetadata = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build() .Deserialize <TagsMetadata>(result); // Verify the output only contains the platform with the documented tag Assert.Single(tagsMetadata.Repos[0].TagGroups); Assert.Equal( $"{SourceRepoUrl}/blob/{SourceBranch}/1.0/{RepoName}/os/Dockerfile", tagsMetadata.Repos[0].TagGroups[0].Dockerfile); List <string> expectedTags = new List <string> { "concreteTagZ", "concreteTagA", "shared2", "shared1", "latest" }; Assert.Equal(expectedTags, tagsMetadata.Repos[0].TagGroups[0].Tags); }
public void TestIndexDotJsonWithNonEnglishCharacters() { var rawHtml = @" <!DOCTYPE html> <html> <head> <meta charset=""utf-8""> <title>This is title in head metadata</title> </head> <body> <h1> This is Title </h1> <p class='data-searchable'> Hello World, Microsoft </p> <article> <h1> This is article title </h1> docfx can do anything... and it supports non-english characters like these: ãâáà êé í õôó Типы шрифтов 人物 文字 </article> </body> </html> "; // prepares temp folder and file for testing purposes // ExtractSearchIndex should probably be refactored so we can test it without depending on the filesystem var tempTestFolder = "temp_test_folder"; if (Directory.Exists(tempTestFolder)) { Directory.Delete(tempTestFolder, true); } Directory.CreateDirectory(tempTestFolder); File.WriteAllText(Path.Combine(tempTestFolder, "index.html"), rawHtml, new UTF8Encoding(false)); // prepares fake manifest object var outputFileInfo = new OutputFileInfo(); outputFileInfo.RelativePath = "index.html"; var manifestItem = new ManifestItem() { OutputFiles = new Dictionary <string, OutputFileInfo>() }; manifestItem.OutputFiles.Add(".html", outputFileInfo); var manifest = new Manifest() { Files = new List <ManifestItem>() }; manifest.Files.Add(manifestItem); // process the fake manifest, using tempTestFolder as the output folder _extractor.Process(manifest, tempTestFolder); var expectedIndexJSON = @"{ ""index.html"": { ""href"": ""index.html"", ""title"": ""This is title in head metadata"", ""keywords"": ""Hello World, Microsoft This is article title docfx can do anything... and it supports non-english characters like these: ãâáà êé í õôó Типы шрифтов 人物 文字"" } }"; var actualIndexJSON = File.ReadAllText(Path.Combine(tempTestFolder, "index.json"), Encoding.UTF8); Assert.Equal(expectedIndexJSON, actualIndexJSON); }
private IEnumerable <ILibraryInstallationState> ValidateParametersAndGetLibrariesToUpdate(Manifest manifest) { var errors = new List <string>(); if (string.IsNullOrWhiteSpace(LibraryName.Value)) { errors.Add(Resources.Text.LibraryIdRequiredForUpdate); } IProvider provider = null; if (Provider.HasValue()) { provider = ManifestDependencies.GetProvider(Provider.Value()); if (provider == null) { errors.Add(string.Format(Resources.Text.ProviderNotInstalled, Provider.Value())); } } if (ToVersion.HasValue() && string.IsNullOrWhiteSpace(ToVersion.Value())) { errors.Add(string.Format(Resources.Text.InvalidToVersion, ToVersion.Value())); } if (errors.Any()) { throw new InvalidOperationException(string.Join(Environment.NewLine, errors)); } return(manifest.Libraries.Where(l => l.Name.Equals(LibraryName.Value, StringComparison.OrdinalIgnoreCase))); }
public Manifest Process(Manifest manifest, string outputFolder) { throw new NotImplementedException(); }
public ModContentPromptLogic(Widget widget, Manifest mod, ModContent content, Action continueLoading) { var panel = widget.Get("CONTENT_PROMPT_PANEL"); var headerTemplate = panel.Get <LabelWidget>("HEADER_TEMPLATE"); var headerLines = !string.IsNullOrEmpty(content.InstallPromptMessage) ? content.InstallPromptMessage.Replace("\\n", "\n").Split('\n') : new string[0]; var headerHeight = 0; foreach (var l in headerLines) { var line = (LabelWidget)headerTemplate.Clone(); line.GetText = () => l; line.Bounds.Y += headerHeight; panel.AddChild(line); headerHeight += headerTemplate.Bounds.Height; } panel.Bounds.Height += headerHeight; panel.Bounds.Y -= headerHeight / 2; var advancedButton = panel.Get <ButtonWidget>("ADVANCED_BUTTON"); advancedButton.Bounds.Y += headerHeight; advancedButton.OnClick = () => { Ui.OpenWindow("CONTENT_PANEL", new WidgetArgs { { "mod", mod }, { "content", content }, { "onCancel", Ui.CloseWindow } }); }; var quickButton = panel.Get <ButtonWidget>("QUICK_BUTTON"); quickButton.IsVisible = () => !string.IsNullOrEmpty(content.QuickDownload); quickButton.Bounds.Y += headerHeight; quickButton.OnClick = () => { var modFileSystem = new FileSystem.FileSystem(Game.Mods); modFileSystem.LoadFromManifest(mod); var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null); modFileSystem.UnmountAll(); var download = downloadYaml.FirstOrDefault(n => n.Key == content.QuickDownload); if (download == null) { throw new InvalidOperationException("Mod QuickDownload `{0}` definition not found.".F(content.QuickDownload)); } Ui.OpenWindow("PACKAGE_DOWNLOAD_PANEL", new WidgetArgs { { "download", new ModContent.ModDownload(download.Value) }, { "onSuccess", continueLoading } }); }; var backButton = panel.Get <ButtonWidget>("BACK_BUTTON"); backButton.Bounds.Y += headerHeight; backButton.OnClick = Ui.CloseWindow; Game.RunAfterTick(Ui.ResetTooltips); }
private void FilterDependencies(string targetPath, ISet <string> dependencyToRemove) { var fileName = Path.GetFileName(targetPath); Log.LogMessage($"Updating {fileName}"); using (var fileStream = File.Open(targetPath, FileMode.Open)) using (var package = new ZipArchive(fileStream, ZipArchiveMode.Update)) using (var packageReader = new PackageArchiveReader(fileStream, leaveStreamOpen: true)) { var referencesFrameworkOnlyAssembly = false; var nuspecFile = packageReader.GetNuspecFile(); using (var stream = package.OpenFile(nuspecFile)) { var reader = Manifest.ReadFrom(stream, validateSchema: true); stream.Position = 0; var packageBuilder = new PackageBuilder(stream, basePath: null); var updatedGroups = new List <PackageDependencyGroup>(); foreach (var group in packageBuilder.DependencyGroups) { var packages = new List <PackageDependency>(); var updatedGroup = new PackageDependencyGroup(group.TargetFramework, packages); foreach (var dependency in group.Packages) { if (dependencyToRemove.Contains(dependency.Id)) { referencesFrameworkOnlyAssembly = true; Log.LogMessage($" Remove dependency on '{dependency.Id}'"); continue; } packages.Add(dependency); } updatedGroups.Add(updatedGroup); } if (referencesFrameworkOnlyAssembly) { packageBuilder.DependencyGroups.Clear(); packageBuilder.DependencyGroups.AddRange(updatedGroups); var updatedManifest = Manifest.Create(packageBuilder); var inMemory = new MemoryStream(); updatedManifest.Save(inMemory); inMemory.Position = 0; // Hack the raw nuspec to add the <frameworkReference> dependency var rawNuspec = XDocument.Load(inMemory, LoadOptions.PreserveWhitespace); var ns = rawNuspec.Root.GetDefaultNamespace(); var metadata = rawNuspec.Root.Descendants(ns + "metadata").Single(); metadata.Add( new XElement(ns + "frameworkReferences", new XElement(ns + "group", new XAttribute("targetFramework", NuGetFramework.Parse(SharedFrameworkTargetFramework).GetFrameworkString()), new XElement(ns + "frameworkReference", new XAttribute("name", "Microsoft.AspNetCore.App"))))); stream.Position = 0; stream.SetLength(0); rawNuspec.Save(stream); } else { Log.LogMessage($"No changes made to {fileName}"); } } } }
/// <summary> /// LetsGo /// </summary> /// <param name="manifest">manifest entity</param> public LetsGo(Manifest manifest) { Manifest = manifest; }
public void Pack(string nuspecPath, string nupkgPath, Manifest manifest, bool packSymbols) { bool creatingSymbolsPackage = packSymbols && (Path.GetExtension(nupkgPath) == _symbolsPackageExtension); try { PackageBuilder builder = new PackageBuilder(); string baseDirectoryPath = (string.IsNullOrEmpty(BaseDirectory)) ? Path.GetDirectoryName(nuspecPath) : BaseDirectory; builder.Populate(manifest.Metadata); builder.PopulateFiles(baseDirectoryPath, manifest.Files); if (creatingSymbolsPackage) { // For symbols packages, filter out excludes PathResolver.FilterPackageFiles( builder.Files, file => file.Path, SymbolPackageExcludes); // Symbol packages are only valid if they contain both symbols and sources. Dictionary <string, bool> pathHasMatches = LibPackageExcludes.ToDictionary( path => path, path => PathResolver.GetMatches(builder.Files, file => file.Path, new[] { path }).Any()); if (!pathHasMatches.Values.Any(i => i)) { Log.LogMessage(LogImportance.Low, $"Nuspec {nuspecPath} does not contain symbol or source files. Not creating symbol package."); return; } foreach (var pathPair in pathHasMatches.Where(pathMatchPair => !pathMatchPair.Value)) { Log.LogMessage(LogImportance.Low, $"Nuspec {nuspecPath} does not contain any files matching {pathPair.Key}. Not creating symbol package."); return; } } else if (!packSymbols) { // for packages which do not include symbols (not symbols or packed packages), filter lib excludes PathResolver.FilterPackageFiles( builder.Files, file => file.Path, LibPackageExcludes); } var directory = Path.GetDirectoryName(nupkgPath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (var fileStream = File.Create(nupkgPath)) { builder.Save(fileStream); } Log.LogMessage($"Created '{nupkgPath}'"); } catch (Exception e) { string packageType = "lib"; if (creatingSymbolsPackage) { packageType = "symbol"; } else if (packSymbols) { packageType = "packed"; } Log.LogError($"Error when creating nuget {packageType} package from {nuspecPath}. {e}"); } }
/// <summary> /// Exports the page. /// </summary> /// <param name="page">The page.</param> /// <param name="isRecursive">if set to <c>true</c> [should export children].</param> /// <returns>a <see cref="T:System.IO.MemoryStream"/> of the exported page package.</returns> public MemoryStream ExportPage(Page page, bool isRecursive) { // Create a temp directory to hold package contents in staging area string packageId = Guid.NewGuid().ToString(); var packageDirectory = CreatePackageDirectory(page.InternalName, packageId); var webRootPath = HttpContext.Current.Server.MapPath("~"); // Create a manifest for this page export... Manifest manifest = new Manifest(); manifest.Metadata = new ManifestMetadata(); manifest.Metadata.Authors = "PageExport"; manifest.Metadata.Version = "0.0"; manifest.Metadata.Id = packageId; manifest.Metadata.Description = (string.IsNullOrEmpty(page.Description)) ? "a page export" : page.Description; manifest.Files = new List <ManifestFile>(); // Generate the JSON from model data and write it to disk, then add it to the manifest var json = GetJson(page, isRecursive); using (var file = new StreamWriter(Path.Combine(packageDirectory.FullName, "export.json"))) { file.Write(json); } AddToManifest(manifest, packageDirectory.FullName, webRootPath, "export.json", SearchOption.TopDirectoryOnly); // * Find out from `page` which Blocks need to be packaged up (recursively if ExportChildren box is checked) // * Grab asset folders for each Block's code file uniquely (Scripts, Assets, CSS folders) // * Add them to the package manifest var blockTypes = new Dictionary <Guid, BlockType>(); var uniqueDirectories = new Dictionary <string, string>(); FindUniqueBlockTypesAndDirectories(page, isRecursive, blockTypes, uniqueDirectories); foreach (var blockType in blockTypes.Values) { var sourcePath = HttpContext.Current.Server.MapPath(blockType.Path); var directory = sourcePath.Substring(0, sourcePath.LastIndexOf(Path.DirectorySeparatorChar)); var fileName = Path.GetFileNameWithoutExtension(sourcePath); var pattern = string.Format("{0}.*", fileName); AddToManifest(manifest, directory, webRootPath, pattern, SearchOption.TopDirectoryOnly); } // Second pass through blocks. Determine which folders (by convention) need to be added // to the package manifest. foreach (var dir in uniqueDirectories.Keys) { var sourcePath = HttpContext.Current.Server.MapPath(dir); // Are there any folders present named "CSS", "Scripts" or "Assets"? AddToManifest(manifest, Path.Combine(sourcePath, "CSS"), webRootPath); AddToManifest(manifest, Path.Combine(sourcePath, "Scripts"), webRootPath); AddToManifest(manifest, Path.Combine(sourcePath, "Assets"), webRootPath); } // Save the manifest as "pageexport.nuspec" in the temp folder string basePath = packageDirectory.FullName; string manifestPath = Path.Combine(basePath, "pageexport.nuspec"); using (Stream fileStream = File.Create(manifestPath)) { manifest.Save(fileStream); } // Create a NuGet package from the manifest and 'save' it to a memory stream for the consumer... // BTW - don't use anything older than nuget 2.1 due to Manifest bug (http://nuget.codeplex.com/workitem/2813) // which will cause the PackageBuilder constructor to fail due to <Files> vs <files> being in the manifest. PackageBuilder packageBuilder = new PackageBuilder(manifestPath, basePath, NullPropertyProvider.Instance, false); var outputStream = new MemoryStream(); packageBuilder.Save(outputStream); // Clean up staging area packageDirectory.Delete(recursive: true); return(outputStream); }
public void Compile() { using (var stream = Manifest.OpenText()) { string line = null; while ((line = stream.ReadLine()) != null) { var splitLine = line.Split(','); var tileType = splitLine[0]; if (tileType == _tileType_monster) { MonsterCompiler.CompileOne(splitLine); } else if (tileType == _tileType_object) { ObjectCompiler.CompileOne(splitLine); } else if (tileType == _tileType_artifact) { ArtifactCompiler.CompileOne(splitLine); } else if (tileType == _tileType_cmap) { CmapCompiler.CompileOne(splitLine); } else if (tileType == _tileType_misc) { MiscCompiler.CompileOne(splitLine); } else if (tileType == _tileType_player) { PlayerCompiler.CompileOne(splitLine); } else if (tileType == _tileType_cmap_variation) { CmapVariationCompiler.CompileOne(splitLine); } else if (tileType == _tileType_UI) { UICompiler.CompileOne(splitLine); } else if (tileType == _tileType_animation) { AnimationCompiler.CompileOne(splitLine); } else if (tileType == _tileType_enlargement) { EnlargementCompiler.CompileOne(splitLine); } else if (tileType == _tileType_replacement) { ReplacementCompiler.CompileOne(splitLine); } else if (tileType == _tileType_broken_cmap) { BrokenCmapCompiler.CompileOne(splitLine); } else if (tileType == _tileType_broken_cmap_variation) { BrokenCmapVariationCompiler.CompileOne(splitLine); } else { throw new Exception(string.Format("Unknown tile type '{0}' in line '{1}'.", tileType, line)); } } // Close Manifest Steram stream.Close(); } }
/// <summary> /// Downloads an AssetBundle or returns a cached AssetBundle if it has already been downloaded. /// Remember to call <see cref="UnloadBundle(UnityEngine.AssetBundle,bool)" /> for every bundle you download once you /// are done with it. /// </summary> /// <param name="bundleName">Name of the bundle to download.</param> /// <param name="onComplete">Action to perform when the bundle has been successfully downloaded.</param> /// <param name="downloadSettings"> /// Tell the function to use a previously downloaded version of the bundle if available. /// Important! If the bundle is currently "active" (it has not been unloaded) then the active bundle will be used /// regardless of this setting. If it's important that a new version is downloaded then be sure it isn't active. /// </param> public void GetBundle(string bundleName, Action <AssetBundle> onComplete, DownloadSettings downloadSettings) { if (Initialized == false) { Debug.LogError("AssetBundleManager must be initialized before you can get a bundle."); onComplete(null); return; } if (useHash) { bundleName = GetHashedBundleName(bundleName); } AssetBundleContainer active; if (activeBundles.TryGetValue(bundleName, out active)) { active.References++; onComplete(active.AssetBundle); return; } DownloadInProgressContainer inProgress; if (downloadsInProgress.TryGetValue(bundleName, out inProgress)) { inProgress.References++; inProgress.OnComplete += onComplete; return; } downloadsInProgress.Add(bundleName, new DownloadInProgressContainer(onComplete)); var mainBundle = new AssetBundleDownloadCommand { BundleName = bundleName, Hash = downloadSettings == DownloadSettings.UseCacheIfAvailable ? Manifest.GetAssetBundleHash(bundleName) : default(Hash128), OnComplete = bundle => OnDownloadComplete(bundleName, bundle) }; var dependencies = Manifest.GetDirectDependencies(bundleName); var dependenciesToDownload = new List <string> (); for (int i = 0; i < dependencies.Length; i++) { if (activeBundles.TryGetValue(dependencies [i], out active)) { active.References++; } else { dependenciesToDownload.Add(dependencies [i]); } } if (dependenciesToDownload.Count > 0) { var dependencyCount = dependenciesToDownload.Count; Action <AssetBundle> onDependenciesComplete = dependency => { if (--dependencyCount == 0) { handler.Handle(mainBundle); } }; for (int i = 0; i < dependenciesToDownload.Count; i++) { var dependencyName = dependenciesToDownload [i]; GetBundle(dependencyName, onDependenciesComplete); } } else { handler.Handle(mainBundle); } }
public static void WriteManifest(Manifest manifest, string path) { }