/// <summary>
 /// Initializes a new instance of the <see cref="PackageSessionAnalysis" /> class.
 /// </summary>
 /// <param name="packageSession">The package session.</param>
 /// <param name="parameters">The parameters.</param>
 public PackageSessionAnalysis(PackageSession packageSession, PackageAnalysisParameters parameters)
     : base(packageSession)
 {
     if (parameters == null) throw new ArgumentNullException("parameters");
     this.parameters = (PackageAnalysisParameters)parameters.Clone();
     this.parameters.IsPackageCheckDependencies = true;
 }
        /// <inheritdoc/>
        public override IEnumerable<string> Select(PackageSession packageSession, IContentIndexMap contentIndexMap)
        {
            // Check if we need to create or regenerate regex.
            bool needGenerateRegex = false;
            if (regexes == null || regexes.Length != Paths.Count)
            {
                needGenerateRegex = true;
            }
            else
            {
                // Check used pattern
                for (int i = 0; i < Paths.Count; ++i)
                {
                    if (Paths[i] != regexes[i].Key)
                    {
                        needGenerateRegex = true;
                        break;
                    }
                }
            }

            // Transform gitignore patterns to regex.
            if (needGenerateRegex)
                regexes = Paths.Select(x => new KeyValuePair<string, Regex>(x, new Regex(TransformToRegex(x)))).ToArray();

            return contentIndexMap.GetMergedIdMap()
                .Select(asset => asset.Key) // Select url
                .Where(assetUrl => regexes.Any(regex => regex.Value.IsMatch(assetUrl))); // Check if any Regex matches
        }
        public void TestUpdateAssetUrl()
        {
            var projectDir = new UFile(Path.Combine(Environment.CurrentDirectory, "testxk"));
            
            // Create a project with an asset reference a raw file
            var project = new Package { FullPath = projectDir };
            var assetItem = new AssetItem("test", new AssetObjectTest() { Reference =  new AssetReference<AssetObjectTest>(Guid.Empty, "good/location")});
            project.Assets.Add(assetItem);
            var goodAsset = new AssetObjectTest();
            project.Assets.Add(new AssetItem("good/location", goodAsset));

            // Add the project to the session to make sure analysis will run correctly
            var session = new PackageSession(project);

            // Create a session with this project
            var analysis = new PackageAnalysis(project,
                new PackageAnalysisParameters()
                    {
                        IsProcessingAssetReferences = true,
                        ConvertUPathTo = UPathType.Absolute,
                        IsProcessingUPaths = true
                    });
            var result = analysis.Run();
            Assert.IsFalse(result.HasErrors);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].ToString().Contains("changed"));

            var asset = (AssetObjectTest)assetItem.Asset;
            Assert.AreEqual(goodAsset.Id, asset.Reference.Id);
            Assert.AreEqual("good/location", asset.Reference.Location);
        }
Beispiel #4
0
        /// <inheritdoc/>
        public override bool UpgradeAfterAssetsLoaded(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, PackageVersionRange dependencyVersionBeforeUpdate)
        {
            if (dependencyVersionBeforeUpdate.MinVersion < new PackageVersion("1.3.0-alpha02"))
            {
                // Add everything as root assets (since we don't know what the project was doing in the code before)
                foreach (var assetItem in dependentPackage.Assets)
                {
                    if (!AssetRegistry.IsAssetTypeAlwaysMarkAsRoot(assetItem.Asset.GetType()))
                    {
                        dependentPackage.RootAssets.Add(new AssetReference <Asset>(assetItem.Id, assetItem.Location));
                    }
                }
            }

            if (dependencyVersionBeforeUpdate.MinVersion < new PackageVersion("1.6.0-beta"))
            {
                // Mark all assets dirty to force a resave
                foreach (var assetItem in dependentPackage.Assets)
                {
                    if (!(assetItem.Asset is SourceCodeAsset))
                    {
                        assetItem.IsDirty = true;
                    }
                }
            }

            return(true);
        }
Beispiel #5
0
        private static PackageSession GenerateNewGame(string outputFolder)
        {
            // Find the game template description for a new game
            var template = TemplateManager.FindTemplates().FirstOrDefault(matchTemplate => matchTemplate.Id == NewGameTemplateGenerator.TemplateId);

            Assert.NotNull(template);

            var result = new LoggerResult();

            var session = new PackageSession();

            session.SolutionPath = Path.Combine(outputFolder, @"NewGame.sln");
            var parameters = new SessionTemplateGeneratorParameters
            {
                Description     = template,
                Logger          = result,
                Name            = "NewGame",
                OutputDirectory = outputFolder,
                Session         = session,
                Unattended      = true,
            };

            NewGameTemplateGenerator.SetParameters(parameters, AssetRegistry.SupportedPlatforms.Where(x => x.Type == Core.PlatformType.Windows).Select(x => new SelectedSolutionPlatform(x, null)));

            var templateGenerator = TemplateManager.FindTemplateGenerator(parameters);

            templateGenerator.PrepareForRun(parameters);
            templateGenerator.Run(parameters);

            return(session);
        }
 public override IEnumerable<string> Select(PackageSession packageSession, IContentIndexMap contentIndexMap)
 {
     return packageSession.Packages
         .SelectMany(package => package.Assets) // Select all assets
         .Where(assetItem => assetItem.Asset.Tags.Any(tag => Tags.Contains(tag))) // Matches tags
         .Select(x => x.Location.FullPath); // Convert to string;
 }
Beispiel #7
0
        /// <summary>
        /// Finds all template descriptions.
        /// </summary>
        /// <returns>A sequence containing all registered template descriptions.</returns>
        public static IEnumerable <TemplateDescription> FindTemplates(PackageSession session = null)
        {
            var packages = session?.Packages.Concat(ExtraPackages) ?? ExtraPackages;

            // TODO this will not work if the same package has different versions
            return(packages.SelectMany(package => package.Templates).OrderBy(tpl => tpl.Order).ThenBy(tpl => tpl.Name).ToList());
        }
        public void CompilerVisitRuntimeType()
        {
            var package = new Package();
            // ReSharper disable once UnusedVariable - we need a package session to compile
            var packageSession = new PackageSession(package);
            var otherAssets    = new List <AssetItem>
            {
                new AssetItem("contentRB", new MyAssetContentType(0), package),
                new AssetItem("contentRA", new MyAssetContentType(1), package),
                new AssetItem("content0B", new MyAssetContentType(2), package),
                new AssetItem("content0M", new MyAssetContentType(3), package),
                new AssetItem("content0A", new MyAssetContentType(4), package),
                new AssetItem("content1B", new MyAssetContentType(5), package),
                new AssetItem("content1M", new MyAssetContentType(6), package),
                new AssetItem("content1A", new MyAssetContentType(7), package),
                new AssetItem("content2B", new MyAssetContentType(8), package),
                new AssetItem("content2M", new MyAssetContentType(9), package),
                new AssetItem("content2A", new MyAssetContentType(10), package),
                new AssetItem("content3B", new MyAssetContentType(11), package),
                new AssetItem("content3M", new MyAssetContentType(12), package),
                new AssetItem("content3A", new MyAssetContentType(13), package),
                new AssetItem("content4B", new MyAssetContentType(14), package),
                new AssetItem("content4M", new MyAssetContentType(15), package),
                new AssetItem("content4A", new MyAssetContentType(16), package),
            };

            var assetToVisit = new MyAsset1();

            assetToVisit.Before = AttachedReferenceManager.CreateProxyObject <MyContentType>(otherAssets[0].Id, otherAssets[0].Location);
            assetToVisit.Zafter = AttachedReferenceManager.CreateProxyObject <MyContentType>(otherAssets[1].Id, otherAssets[1].Location);
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[2], otherAssets[3], otherAssets[4]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[5], otherAssets[6], otherAssets[7]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[8], otherAssets[9], otherAssets[10]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[11], otherAssets[12], otherAssets[13]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[14], otherAssets[15], otherAssets[16]));
            assetToVisit.RuntimeTypes[0].A = assetToVisit.RuntimeTypes[1];
            assetToVisit.RuntimeTypes[0].B = assetToVisit.RuntimeTypes[2];
            assetToVisit.RuntimeTypes[1].A = assetToVisit.RuntimeTypes[3];
            assetToVisit.RuntimeTypes[1].B = assetToVisit.RuntimeTypes[4];

            otherAssets.ForEach(x => package.Assets.Add(x));
            var assetItem = new AssetItem("asset", assetToVisit, package);

            package.Assets.Add(assetItem);
            package.RootAssets.Add(new AssetReference(assetItem.Id, assetItem.Location));

            // Create context
            var context = new AssetCompilerContext {
                CompilationContext = typeof(AssetCompilationContext)
            };

            // Builds the project
            var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));

            context.Properties.Set(BuildAssetNode.VisitRuntimeTypes, true);
            var assetBuildResult = assetBuilder.Prepare(context);

            Assert.AreEqual(16, assetBuildResult.BuildSteps.Count);
        }
        public void TestInheritance()
        {
            // -----------------------------------------------------------
            // Tests inheritance
            // -----------------------------------------------------------
            // 4 assets
            // [asset1] is referencing [asset2]
            // [asset2]
            // [asset3] is inheriting  [asset1]
            // We create a [project1] with [asset1, asset2, asset3]
            // Check direct inherit dependencies for [asset3]: [asset1]
            // -----------------------------------------------------------

            var asset1 = new AssetObjectTest();
            var asset2 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            var assetItem2 = new AssetItem("asset-2", asset2);

            var asset3 = assetItem1.CreateChildAsset();
            var assetItem3 = new AssetItem("asset-3", asset3);

            asset1.Reference = new AssetReference<AssetObjectTest>(assetItem2.Id, assetItem2.Location);

            var project = new Package();
            project.Assets.Add(assetItem1);
            project.Assets.Add(assetItem2);
            project.Assets.Add(assetItem3);

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Verify inheritance
                {
                    var assets = dependencyManager.FindAssetsInheritingFrom(asset1.Id);
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset3.Id, assets[0].Id);
                }

                // Remove the inheritance
                var copyBase = asset3.Base;
                asset3.Base = null;
                assetItem3.IsDirty = true;
                {
                    var assets = dependencyManager.FindAssetsInheritingFrom(asset1.Id);
                    Assert.AreEqual(0, assets.Count);
                }

                // Add back the inheritance
                asset3.Base = copyBase;
                assetItem3.IsDirty = true;
                {
                    var assets = dependencyManager.FindAssetsInheritingFrom(asset1.Id);
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset3.Id, assets[0].Id);
                }
            }
        }
 public IEnumerable <IReference> EnumerateCompileTimeDependencies(PackageSession session)
 {
     foreach (var shapeDesc in ColliderShapes.OfType <ConvexHullColliderShapeDesc>())
     {
         var reference = AttachedReferenceManager.GetAttachedReference(shapeDesc.Model);
         yield return(new AssetReference(reference.Id, reference.Url));
     }
 }
 /// <summary>
 /// Collects all references of an asset dynamically.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="packageSession">The package session.</param>
 /// <param name="isRecursive">if set to <c>true</c> [is recursive].</param>
 /// <param name="keepParents">Indicate if the parent of the provided <paramref name="result"/> should be kept or not</param>
 /// <exception cref="System.ArgumentNullException">packageSession</exception>
 private static void CollectDynamicOutReferences(AssetDependencies result, PackageSession packageSession, bool isRecursive, bool keepParents)
 {
     if (packageSession == null)
     {
         throw new ArgumentNullException(nameof(packageSession));
     }
     CollectDynamicOutReferences(result, packageSession.FindAsset, isRecursive, keepParents);
 }
Beispiel #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TemplateGeneratorContext"/> class.
 /// </summary>
 /// <param name="session">The session.</param>
 public TemplateGeneratorContext(PackageSession session)
 {
     if (session == null)
     {
         throw new ArgumentNullException("session");
     }
     Session = session;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageSessionAnalysis" /> class.
 /// </summary>
 /// <param name="packageSession">The package session.</param>
 /// <exception cref="System.ArgumentNullException">packageSession</exception>
 protected PackageSessionAnalysisBase(PackageSession packageSession)
 {
     if (packageSession == null)
     {
         throw new ArgumentNullException("packageSession");
     }
     this.packageSession = packageSession;
 }
Beispiel #14
0
        public IEnumerable <IReference> EnumerateCompileTimeDependencies(PackageSession session)
        {
            var gameSettings = session.CurrentPackage?.Assets.Find(GameSettingsAsset.GameSettingsLocation);

            if (gameSettings != null)
            {
                yield return(new AssetReference(gameSettings.Id, gameSettings.Location));
            }
        }
Beispiel #15
0
        /// <summary>
        ///   Creates a build step that will build all shaders from system packages.
        /// </summary>
        /// <param name="session">The session used to retrieve currently used system packages.</param>
        /// <returns>A <see cref="ListBuildStep"/> containing the steps to build all shaders from system packages.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> is a <c>null</c> reference.</exception>
        public ListBuildStep CreateSystemShaderBuildSteps(SessionViewModel session)
        {
            if (session is null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            // Check if there are any new system projects to preload
            // TODO: PDX-1251: For now, allow non-system project as well (which means they will be loaded only once at startup)
            // Later, they should be imported depending on what project the currently previewed/built asset is
            var systemPackages = session.AllPackages.Where(project => /*project.IsSystem &&*/ !systemProjectsLoaded.Contains(project.Package.Meta.Name)).ToList();

            if (systemPackages.Count == 0)
            {
                return(null);
            }

            var importShadersRootProject    = new StandalonePackage(new Package());
            var importShadersProjectSession = new PackageSession();

            importShadersProjectSession.Projects.Add(importShadersRootProject);

            foreach (var package in systemPackages)
            {
                var mapPackage = new Package {
                    FullPath = package.PackagePath
                };
                foreach (var asset in package.Assets)
                {
                    if (typeof(EffectShaderAsset).IsAssignableFrom(asset.AssetType))
                    {
                        mapPackage.Assets.Add(new AssetItem(asset.Url, asset.Asset)
                        {
                            SourceFolder = asset.AssetItem.SourceFolder, AlternativePath = asset.AssetItem.AlternativePath
                        });
                    }
                }

                importShadersProjectSession.Projects.Add(new StandalonePackage(mapPackage));
                importShadersRootProject.FlattenedDependencies.Add(new Dependency(mapPackage));
            }

            // Compile the fake project (create the build steps)
            var assetProjectCompiler = new PackageCompiler(new PackageAssetEnumerator(importShadersRootProject.Package));
            var context = new AssetCompilerContext {
                CompilationContext = typeof(AssetCompilationContext)
            };
            var dependenciesCompileResult = assetProjectCompiler.Prepare(context);

            context.Dispose();

            var buildSteps = dependenciesCompileResult.BuildSteps;

            buildSteps?.Add(new UpdateImportShaderCacheBuildStep(systemProjectsLoaded, systemPackages.Select(x => x.Package.Meta.Name).ToList()));

            return(buildSteps);
        }
Beispiel #16
0
        /// <summary>
        /// Finds all template descriptions.
        /// </summary>
        /// <returns>A sequence containing all registered template descriptions.</returns>
        public static IEnumerable <TemplateDescription> FindTemplates(PackageSession session = null)
        {
            var packages = session?.Packages ?? new PackageCollection {
                PackageStore.Instance.DefaultPackage
            };

            // TODO this will not work if the same package has different versions
            return(packages.SelectMany(package => package.Templates).OrderBy(tpl => tpl.Order).ThenBy(tpl => tpl.Name));
        }
 public PackageAssetsCompiler(PackageSession session)
     : base(assetCompilerRegistry)
 {
     if (session == null)
     {
         throw new ArgumentNullException("session");
     }
     this.session = session;
 }
        public void TestRuntime()
        {
            var package = new Package();
            // ReSharper disable once UnusedVariable - we need a package session to compile
            var packageSession = new PackageSession(package);
            var otherAssets    = new List <AssetItem>
            {
                new AssetItem("asset11", new MyAsset11(), package),
                new AssetItem("asset12", new MyAsset12(), package),
                new AssetItem("asset13", new MyAsset13(), package),
            };

            otherAssets.ForEach(x => package.Assets.Add(x));

            var compileAssetReference = new MyAsset4
            {
                CompileAssetReference   = CreateRef <MyContent11>(otherAssets[0]),
                CompileContentReference = CreateRef <MyContent12>(otherAssets[1]),
                CompileRuntimeReference = CreateRef <MyContent13>(otherAssets[2]),
            };
            var assetItem = new AssetItem("asset4", compileAssetReference, package);

            package.Assets.Add(assetItem);

            var asset = new MyAsset1 {
                CompileAssetReference = CreateRef <MyContent2>(assetItem)
            };

            assetItem = new AssetItem("asset1", asset, package);
            package.Assets.Add(assetItem);
            package.RootAssets.Add(new AssetReference(assetItem.Id, assetItem.Location));

            // Create context
            var context = new AssetCompilerContext {
                CompilationContext = typeof(AssetCompilationContext)
            };

            // Builds the project
            Exception ex = null;

            MyAsset1Compiler.AssertFunc = (url, ass, pkg) =>
            {
                AssertInThread(ref ex, () => Assert.AreEqual(1, TestCompilerBase.CompiledAssets.Count));
                AssertInThread(ref ex, () => Assert.AreEqual(compileAssetReference.Id, TestCompilerBase.CompiledAssets.First().Id));
            };

            var assetBuilder     = new PackageCompiler(new RootPackageAssetEnumerator(package));
            var assetBuildResult = assetBuilder.Prepare(context);

            // Since MyAsset4 is a Runtime reference, it should be compiled, so we should have 2 asset (MyAsset1 and MyAsset4) to compile.
            Assert.AreEqual(2, assetBuildResult.BuildSteps.Count);
            var builder = new Builder(GlobalLogger.GetLogger("Test"), "", "", "");

            builder.Root.Add(assetBuildResult.BuildSteps);
            builder.Run(Builder.Mode.Build, false);
            RethrowAssertsFromThread(ex);
        }
Beispiel #19
0
        /// <inheritdoc/>
        public IEnumerable <IReference> EnumerateCompileTimeDependencies(PackageSession session)
        {
            var reference = AttachedReferenceManager.GetAttachedReference(Skeleton);

            if (reference != null)
            {
                yield return(new AssetReference <Asset>(reference.Id, reference.Url));
            }
        }
Beispiel #20
0
        private static int Main(string[] args)
        {
            Console.WriteLine(@"Bootstrapping: " + args[0]);

            var xenkoDir     = Environment.GetEnvironmentVariable("SiliconStudioXenkoDir");
            var xenkoPkgPath = UPath.Combine(xenkoDir, new UFile("Xenko.xkpkg"));

            var session = PackageSession.Load(xenkoPkgPath);

            var generator = TemplateSampleGenerator.Default;

            var logger = new LoggerResult();

            var parameters = new TemplateGeneratorParameters {
                Session = session.Session
            };

            var outputPath = UPath.Combine(new UDirectory(xenkoDir), new UDirectory("samplesGenerated"));

            outputPath = UPath.Combine(outputPath, new UDirectory(args[0]));

            var xenkoTemplates = session.Session.Packages.First().Templates;

            parameters.Description     = xenkoTemplates.First(x => x.Group.StartsWith("Samples") && x.Id == new Guid(args[1]));
            parameters.Name            = args[0];
            parameters.Namespace       = args[0];
            parameters.OutputDirectory = outputPath;
            parameters.Logger          = logger;

            generator.Generate(parameters);

            var updaterTemplate = xenkoTemplates.First(x => x.FullPath.ToString().EndsWith("UpdatePlatforms.xktpl"));

            parameters.Description = updaterTemplate;

            var updater = UpdatePlatformsTemplateGenerator.Default;

            var gameSettingsAsset = session.Session.Packages.Last().GetGameSettingsAsset();
            var renderingSettings = gameSettingsAsset.Get <RenderingSettings>();

            var updateParams = new GameTemplateParameters
            {
                Common = parameters,
                ForcePlatformRegeneration = true,
                GraphicsProfile           = renderingSettings.DefaultGraphicsProfile,
                IsHDR       = false,
                Orientation = (DisplayOrientation)renderingSettings.DisplayOrientation,
                Platforms   = AssetRegistry.SupportedPlatforms.ToList()
            };

            updater.Generate(updateParams);

            Console.WriteLine(logger.ToText());

            return(logger.HasErrors ? 1 : 0);
        }
Beispiel #21
0
            public static bool Upgrade(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, IList <PackageLoadingAssetFile> assetFiles)
            {
                var packageSharedProfile = dependentPackage.Profiles.FindSharedProfile();

                // Only do something if there is a default scene defined
                if (packageSharedProfile != null && packageSharedProfile.Properties.ContainsKey(DefaultScene))
                {
                    var defaultScene = Get(packageSharedProfile.Properties, DefaultScene);

                    var defaultGraphicsProfile = Get(packageSharedProfile.Properties, DefaultGraphicsProfile);

                    // If available, use graphics profile from Windows platform
                    foreach (var profile in dependentPackage.Profiles)
                    {
                        if (profile.Platform == PlatformType.Windows && profile.Properties.ContainsKey(DefaultGraphicsProfile))
                        {
                            defaultGraphicsProfile = Get(profile.Properties, DefaultGraphicsProfile);
                        }
                    }

                    // Create asset
                    var gameSettingsAsset = new GameSettingsAsset
                    {
                        DefaultScene = AttachedReferenceManager.CreateSerializableVersion <Scene>(defaultScene.Id, defaultScene.Location)
                    };

                    var renderingSettings = gameSettingsAsset.Get <RenderingSettings>();
                    renderingSettings.DisplayOrientation      = (RequiredDisplayOrientation)Get(packageSharedProfile.Properties, DisplayOrientation);
                    renderingSettings.ColorSpace              = ColorSpace.Linear;
                    renderingSettings.DefaultBackBufferWidth  = Get(packageSharedProfile.Properties, BackBufferWidth);
                    renderingSettings.DefaultBackBufferHeight = Get(packageSharedProfile.Properties, BackBufferHeight);
                    renderingSettings.DefaultGraphicsProfile  = defaultGraphicsProfile;

                    // Add asset
                    using (var memoryStream = new MemoryStream())
                    {
                        AssetSerializer.Save(memoryStream, gameSettingsAsset, log);
                        assetFiles.Add(new PackageLoadingAssetFile(dependentPackage, GameSettingsLocation + FileExtension, null)
                        {
                            AssetContent = memoryStream.ToArray()
                        });
                    }

                    // Clean properties
                    foreach (var profile in dependentPackage.Profiles)
                    {
                        profile.Properties.Remove(DefaultScene.Name);
                        profile.Properties.Remove(BackBufferWidth.Name);
                        profile.Properties.Remove(BackBufferHeight.Name);
                        profile.Properties.Remove(DefaultGraphicsProfile.Name);
                        profile.Properties.Remove(DisplayOrientation.Name);
                    }
                }

                return(true);
            }
Beispiel #22
0
        public void TestCompileAsset()
        {
            var package = new Package();
            // ReSharper disable once UnusedVariable - we need a package session to compile
            var packageSession = new PackageSession(package);
            var otherAssets    = new List <AssetItem>
            {
                new AssetItem("asset5", new MyAsset5(), package),
                new AssetItem("asset6", new MyAsset6(), package),
                new AssetItem("asset7", new MyAsset7(), package),
            };

            otherAssets.ForEach(x => package.Assets.Add(x));

            var compileAssetReference = new MyAsset2
            {
                CompileAssetReference   = CreateRef <MyContent5>(otherAssets[0]),
                CompileContentReference = CreateRef <MyContent6>(otherAssets[1]),
                CompileRuntimeReference = CreateRef <MyContent7>(otherAssets[2]),
            };
            var assetItem = new AssetItem("asset2", compileAssetReference, package);

            package.Assets.Add(assetItem);

            var asset = new MyAsset1 {
                CompileAssetReference = CreateRef <MyContent2>(assetItem)
            };

            assetItem = new AssetItem("asset1", asset, package);
            package.Assets.Add(assetItem);
            package.RootAssets.Add(new AssetReference(assetItem.Id, assetItem.Location));

            // Create context
            var context = new AssetCompilerContext {
                CompilationContext = typeof(AssetCompilationContext)
            };
            // Builds the project
            Exception ex = null;

            MyAsset1Compiler.AssertFunc = (url, ass, pkg) =>
            {
                // Nothing must have been compiled before
                AssertInThread(ref ex, () => Assert.Empty(TestCompilerBase.CompiledAssets));
            };

            var assetBuilder     = new PackageCompiler(new RootPackageAssetEnumerator(package));
            var assetBuildResult = assetBuilder.Prepare(context);

            // Since MyAsset2 is a CompileAsset reference, it should not be compiled, so we should have only 1 asset (MyAsset1) to compile.
            Assert.Equal(1, assetBuildResult.BuildSteps.Count);
            var builder = new Builder(GlobalLogger.GetLogger("Test"), "", "");

            builder.Root.Add(assetBuildResult.BuildSteps);
            builder.Run(Builder.Mode.Build, false);
            RethrowAssertsFromThread(ex);
        }
Beispiel #23
0
        public async Task <LoggerResult> SaveProject()
        {
            if (PackageSession == null)
            {
                throw new InvalidOperationException("Cannot save the project before it was loaded.");
            }

            // TODO: check asset consistency

            // TODO: read more about Stride.Core.Assets.Editor.PackageViewModel
            //// Prepare packages to be saved by setting their dirty flag correctly
            //foreach (var package in LocalPackages)
            //{
            //    package.PreparePackageForSaving();
            //}

            var viewUpdater = Services.GetService <IViewUpdater>();

            PackageSessionResult sessionResult = await SetupResultProgress(viewUpdater, SaveProjectScope);

            // TODO: display a dialog with save progress

            // Force PackageSession.Save to be executed on the thread pool
            // otherwise it would block execution and we want this process to be async
            using (var scope = new TimedScope(SaveProjectScope, TimedScope.Status.Success))
            {
                await Task.Run(() =>
                {
                    try
                    {
                        var saveParameters = PackageSaveParameters.Default();

                        // TODO: read more about Stride.Core.Assets.Editor.AssetViewModel
                        // AllAssets.ForEach(x => x.PrepareSave(sessionResult));
                        PackageSession.Save(sessionResult, saveParameters);
                    }
                    catch (Exception e)
                    {
                        sessionResult.Error(string.Format("There was a problem saving the solution. {0}", e.Message), e);
                        scope.Result = TimedScope.Status.Failure;
                    }
                });

                if (sessionResult.HasErrors)
                {
                    scope.Result = TimedScope.Status.Failure;
                }
            }

            EditorViewModel.LoadingStatus = null;
            await viewUpdater.UpdateView();

            ProjectSaved?.Invoke(sessionResult);

            return(sessionResult);
        }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageSessionAnalysis" /> class.
 /// </summary>
 /// <param name="packageSession">The package session.</param>
 /// <param name="parameters">The parameters.</param>
 public PackageSessionAnalysis(PackageSession packageSession, PackageAnalysisParameters parameters)
     : base(packageSession)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     this.parameters = (PackageAnalysisParameters)parameters.Clone();
     this.parameters.IsPackageCheckDependencies = true;
 }
Beispiel #25
0
        public void TestWithPackage()
        {
            var inputs = new List <AssetItem>();

            var asset = new AssetObjectTest();

            var package = new Package();

            package.Assets.Add(new AssetItem("0", asset));
            var session = new PackageSession(package);

            for (int i = 0; i < 10; i++)
            {
                var newAsset = new AssetObjectTest()
                {
                    Id = asset.Id, Reference = new AssetReference(asset.Id, "bad")
                };
                inputs.Add(new AssetItem("0", newAsset));
            }

            // Tries to use existing ids
            var outputs = new List <AssetItem>();

            AssetCollision.Clean(null, inputs, outputs, AssetResolver.FromPackage(package), true, false);

            // Make sure we are generating exactly the same number of elements
            Assert.Equal(inputs.Count, outputs.Count);

            // Make sure that asset has been cloned
            Assert.NotEqual(inputs[0], outputs[0]);

            // First Id should not change
            Assert.NotEqual(inputs[0].Id, outputs[0].Id);

            // Make sure that all ids are different
            var ids = new HashSet <AssetId>(outputs.Select(item => item.Id));

            Assert.Equal(inputs.Count, ids.Count);

            // Make sure that all locations are different
            var locations = new HashSet <UFile>(outputs.Select(item => item.Location));

            Assert.Equal(inputs.Count, locations.Count);

            // Reference location "bad"should be fixed to "0_1" pointing to the first element
            foreach (var output in outputs)
            {
                // Make sure of none of the locations are using "0"
                Assert.NotEqual((UFile)"0", output.Location);

                var assetRef = ((AssetObjectTest)output.Asset).Reference;
                Assert.Equal("0 (2)", assetRef.Location);
                Assert.Equal(outputs[0].Id, assetRef.Id);
            }
        }
        public PackageAssetTemplatingAnalysis(Package package, ILogger log)
        {
            if (package == null) throw new ArgumentNullException(nameof(package));
            if (log == null) throw new ArgumentNullException(nameof(log));
            assetsToProcess = new Dictionary<Guid, AssetItem>();
            assetsProcessed = new Dictionary<Guid, AssetItem>();

            this.package = package;
            session = package.Session;
            this.log = log;
        }
Beispiel #27
0
        static void Main()
        {
            var clock = Stopwatch.StartNew();

            for (int i = 0; i < 10; i++)
            {
                var session = PackageSession.Load(@"E:\Code\SengokuRun\SengokuRun\WindowsLauncher\GameAssets\Assets.xkpkg");
            }
            var elapsed = clock.ElapsedMilliseconds;

            Console.WriteLine("{0}ms", elapsed);
        }
Beispiel #28
0
        public IEnumerable <IReference> EnumerateCompileTimeDependencies(PackageSession session)
        {
            if (Prefab != null)
            {
                // Return the prefab itself
                yield return(Prefab);

                // Then we need to return used models and materials because they affects how the meshes are generated
                var prefab = session.FindAsset(Prefab.Location)?.Asset as PrefabAsset;
                if (prefab != null)
                {
                    // Use a dictionary to ensure each reference is yielded only once
                    var references = new Dictionary <Guid, IReference>();
                    foreach (var entity in prefab.Hierarchy.Parts)
                    {
                        // Gather all entities with a model component and a valid model
                        var modelComponent = entity.Entity.Get <ModelComponent>();
                        if (modelComponent?.Model != null)
                        {
                            var modelReference = AttachedReferenceManager.GetAttachedReference(modelComponent.Model);
                            var model          = session.FindAsset(modelReference.Url)?.Asset as IModelAsset;
                            if (model != null)
                            {
                                // Build the list of material for this model
                                var materialList = model.Materials.Select(x => x.MaterialInstance.Material).ToList();
                                for (var i = 0; i < modelComponent.Materials.Count && i < materialList.Count; i++)
                                {
                                    // Apply any material override from the model component
                                    var material = modelComponent.Materials[i];
                                    if (material != null)
                                    {
                                        materialList[i] = material;
                                    }
                                }

                                // Add the model and the related materials to the list of reference
                                references[modelReference.Id] = modelReference;
                                foreach (var material in materialList)
                                {
                                    var materialReference = AttachedReferenceManager.GetAttachedReference(material);
                                    references[materialReference.Id] = materialReference;
                                }
                            }
                        }
                    }
                    // Finally return all the referenced models and materials
                    foreach (var reference in references.Values)
                    {
                        yield return(reference);
                    }
                }
            }
        }
Beispiel #29
0
        public void TestBasicPackageCreateSaveLoad()
        {
            PackageSessionPublicHelper.FindAndSetMSBuildVersion();

            var dirPath = DirectoryTestBase + @"TestBasicPackageCreateSaveLoad";

            string testGenerated1 = Path.Combine(dirPath, "TestPackage_TestBasicPackageCreateSaveLoad_Generated1.sdpkg");

            // Force the PackageId to be the same each time we run the test
            // Usually the PackageId is unique and generated each time we create a new project
            var project = new Package {
                FullPath = testGenerated1
            };

            project.AssetFolders.Clear();
            project.AssetFolders.Add(new AssetFolder("."));

            var session = new PackageSession(project);

            // Write the solution when saving
            session.SolutionPath = Path.Combine(dirPath, "TestPackage_TestBasicPackageCreateSaveLoad_Generated1.sln");

            // Delete the solution before saving it
            if (File.Exists(session.SolutionPath))
            {
                File.Delete(session.SolutionPath);
            }

            var result = new LoggerResult();

            session.Save(result);
            Assert.False(result.HasErrors);

            // Reload the raw package and if UFile and UDirectory were saved relative
            var rawPackage      = AssetFileSerializer.Load <Package>(testGenerated1).Asset;
            var rawSourceFolder = rawPackage.AssetFolders.FirstOrDefault();

            Assert.NotNull(rawSourceFolder);
            Assert.Equal(".", (string)rawSourceFolder.Path);

            // Reload the package directly from the sdpkg
            var project2Result = PackageSession.Load(testGenerated1);

            AssertResult(project2Result);
            var project2 = project2Result.Session.LocalPackages.FirstOrDefault();

            Assert.NotNull(project2);
            Assert.True(project2.AssetFolders.Count > 0);
            var sourceFolder = project.AssetFolders.First().Path;

            Assert.Equal(sourceFolder, project2.AssetFolders.First().Path);
        }
        public override bool UpgradeBeforeAssembliesLoaded(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage)
        {
            if (dependency.Version.MinVersion < new PackageVersion("1.4.0-alpha01"))
            {
                UpgradeCode(dependentPackage, log, new RenameToXenkoCodeUpgrader());
            }
            else if (dependency.Version.MinVersion < new PackageVersion("1.6.0-beta"))
            {
                UpgradeCode(dependentPackage, log, new NewComponentsCodeUpgrader());
            }

            return(true);
        }
Beispiel #31
0
        /// <summary>
        ///   Finds all the template descriptions.
        /// </summary>
        /// <param name="session">The session for which to find template descriptions.</param>
        /// <returns>An enumeration of all the registered template descriptions.</returns>
        public static IEnumerable <TemplateDescription> FindTemplates(PackageSession session = null)
        {
            var packages = session?.Packages
                           .Concat(ExtraPackages)
                           .Distinct(DistinctPackagePathComparer.Default)
                           ?? ExtraPackages;

            // TODO: This will not work if the same package has different versions
            return(packages.SelectMany(package => package.Templates)
                   .OrderBy(template => template.Order)
                   .ThenBy(template => template.Name)
                   .ToList());
        }
 public AssetSourceTrackerViewModel(IViewModelServiceProvider serviceProvider, PackageSession packageSession, SessionViewModel session)
     : base(serviceProvider)
 {
     this.session     = packageSession;
     sessionViewModel = session;
     UpdateSelectedAssetsFromSourceCommand    = new AnonymousTaskCommand(ServiceProvider, UpdateSelectedAssetsFromSource);
     UpdateAllAssetsWithModifiedSourceCommand = new AnonymousTaskCommand(ServiceProvider, UpdateAllAssetsWithModifiedSource)
     {
         IsEnabled = false
     };
     // This task will listen to the AssetSourceTracker for source file change notifications and collect them
     Dispatcher.InvokeTask(PullSourceFileChanges);
 }
Beispiel #33
0
        private static void CompileSample(LoggerResult logger, string sampleName, PackageSession session)
        {
            var project = session.Projects.OfType <SolutionProject>().First(x => x.Platform == Core.PlatformType.Windows);

            var buildResult = VSProjectHelper.CompileProjectAssemblyAsync(null, project.FullPath, logger, extraProperties: new Dictionary <string, string> {
                { "StrideAutoTesting", "true" }
            }).BuildTask.Result;

            if (logger.HasErrors)
            {
                throw new InvalidOperationException($"Error compiling sample {sampleName}:\r\n{logger.ToText()}");
            }
        }
Beispiel #34
0
        public void TestPackageLoadingWithAssets()
        {
            var basePath    = Path.Combine(DirectoryTestBase, @"TestPackage");
            var projectPath = Path.Combine(basePath, "TestPackageLoadingWithAssets.pdxpkg");

            var sessionResult = PackageSession.Load(projectPath);

            AssertResult(sessionResult);
            var session = sessionResult.Session;

            var rootPackageId = new Guid("4102BF96-796D-4800-9983-9C227FAB7BBD");

            var project = session.Packages.Find(rootPackageId);

            Assert.IsNotNull(project);
            Assert.AreEqual(3, project.Assets.Count, "Invalid number of assets loaded");

            Assert.AreEqual(1, project.LocalDependencies.Count, "Expecting subproject");

            Assert.AreNotEqual(Guid.Empty, project.Assets.First().Id);

            // Check for UPathRelativeTo
            var profile = project.Profiles.FirstOrDefault();

            Assert.NotNull(profile);
            var folder = profile.AssetFolders.FirstOrDefault();

            Assert.NotNull(folder);
            Assert.NotNull(folder.Path);
            Assert.NotNull(folder.Path.IsAbsolute);
            var import = folder.RawImports.FirstOrDefault();

            Assert.NotNull(import);
            Assert.IsTrue(import.SourceDirectory != null && import.SourceDirectory.IsRelative);

            // Save project back to disk on a different location
            project.FullPath = Path.Combine(DirectoryTestBase, @"TestPackage2\TestPackage2.pdxpkg");
            var subPackage = session.Packages.Find(Guid.Parse("281321F0-7664-4523-B1DC-3CFC26F80F77"));

            subPackage.FullPath = Path.Combine(DirectoryTestBase, @"TestPackage2\SubPackage\SubPackage.pdxpkg");
            session.Save();

            var project2Result = PackageSession.Load(DirectoryTestBase + @"TestPackage2\TestPackage2.pdxpkg");

            AssertResult(project2Result);
            var project2 = project2Result.Session.Packages.Find(rootPackageId);

            Assert.IsNotNull(project2);
            Assert.AreEqual(3, project2.Assets.Count);
        }
Beispiel #35
0
        public void TestImportWithDuplicateWithinSameSession()
        {
            var          name        = "TestAssetImport";
            var          file        = Path.Combine(Path.GetTempPath(), name + ".tmp");
            const string fileContent = "This is the file content";

            File.WriteAllText(file, fileContent);

            var fileHash = ObjectId.FromBytes(Encoding.UTF8.GetBytes(fileContent));

            // Create a project with an asset reference a raw file
            var project = new Package();

            using (var session = new PackageSession(project))
            {
                var importSession = new AssetImportSession(session);

                // ------------------------------------------------------------------
                // Step 1: Add files to session
                // ------------------------------------------------------------------
                importSession.AddFile(file, project, UDirectory.Empty);
                // Simulate using another importer to duplicate the assets
                importSession.AddFile(file, new CustomImporter(), project, UDirectory.Empty);
                Assert.AreEqual(2, importSession.Imports[0].ByImporters.Count);

                // ------------------------------------------------------------------
                // Step 2: Stage assets
                // ------------------------------------------------------------------
                var stageResult = importSession.Stage();

                //importSession.Imports[0].ByImporters[1].Items[0].SelectedItem = importSession.Imports[0].ByImporters[1].Items[0].Merges[0].PreviousItem;
                // Merge 0 into 1
                importSession.Imports[0].ByImporters[0].Items[0].SelectedItem = importSession.Imports[0].ByImporters[0].Items[0].Merges[0].PreviousItem;

                // ------------------------------------------------------------------
                // Step 4: Merge the asset specified by the previous step
                // ------------------------------------------------------------------
                importSession.Merge();

                Assert.IsTrue(stageResult);

                // ------------------------------------------------------------------
                // Step 3: Import merged asset
                // ------------------------------------------------------------------
                var result = importSession.Import();
                Assert.AreEqual(3, project.Assets.Count);

                // TODO Add more tests
            }
        }
Beispiel #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetDependencyManager" /> class.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <exception cref="System.ArgumentNullException">session</exception>
 internal AssetSourceTracker(PackageSession session)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     this.session = session;
     this.session.Packages.CollectionChanged += Packages_CollectionChanged;
     session.AssetDirtyChanged += Session_AssetDirtyChanged;
     Packages                 = new HashSet <Package>();
     TrackingSleepTime        = 100;
     tokenSourceForImportHash = new CancellationTokenSource();
     threadWatcherEvent       = new ManualResetEvent(false);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetDependencyManager" /> class.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <exception cref="System.ArgumentNullException">session</exception>
 internal AssetDependencyManager(PackageSession session)
 {
     if (session == null) throw new ArgumentNullException(nameof(session));
     this.session = session;
     this.session.Packages.CollectionChanged += Packages_CollectionChanged;
     session.AssetDirtyChanged += Session_AssetDirtyChanged;
     AssetsWithMissingReferences = new Dictionary<AssetId, AssetDependencies>();
     MissingReferencesToParent = new Dictionary<AssetId, HashSet<AssetDependencies>>();
     Packages = new HashSet<Package>();
     Dependencies = new Dictionary<AssetId, AssetDependencies>();
     // If the session has already a root package, then initialize the dependency manager directly
     if (session.LocalPackages.Any())
     {
         Initialize();
     }
 }
Beispiel #38
0
        public override void Initialize()
        {
            base.Initialize();

            TypeFactory = new TypeDescriptorFactory();
            var assetDesc = TypeFactory.Find(typeof(TestAssetUpdate));
            memberMyClass = assetDesc.Members.FirstOrDefault(member => member.Name == "MyClass");

            if (session != null)
            {
                session.Dispose();
                dependencyManager.Dispose();
            }

            package = new Package();
            session = new PackageSession(package);
            dependencyManager = new AssetDependencyManager(session);
            assetUpdater = new AssetUpdater(dependencyManager);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AssetDependencyManager" /> class.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <exception cref="System.ArgumentNullException">session</exception>
        internal AssetDependencyManager(PackageSession session)
        {
            if (session == null) throw new ArgumentNullException("session");
            this.session = session;
            this.session.Packages.CollectionChanged += Packages_CollectionChanged;
            session.AssetDirtyChanged += Session_AssetDirtyChanged;
            AssetsWithMissingReferences = new Dictionary<Guid, AssetDependencies>();
            MissingReferencesToParent = new Dictionary<Guid, HashSet<AssetDependencies>>();
            Packages = new HashSet<Package>();
            Dependencies = new Dictionary<Guid, AssetDependencies>();
            TrackingSleepTime = 100;
            tokenSourceForImportHash = new CancellationTokenSource();
            threadWatcherEvent = new ManualResetEvent(false);

            // If the session has already a root package, then initialize the dependency manager directly
            if (session.LocalPackages.Any())
            {
                Initialize();
            }
        }
        public void TestCachedAssetUpdate()
        {
            // -----------------------------------------------------------
            // Change a property of A0 and see if the version of A0 returned by dependency computation from A1 is valid.
            // -----------------------------------------------------------
            // 2 assets
            // A1 -- inherit from --> A0
            // 
            // -----------------------------------------------------------
            
            var project = new Package();
            var assets = new List<AssetObjectTest>();
            var assetItems = new List<AssetItem>();
            for (int i = 0; i < 2; ++i)
            {
                assets.Add(new AssetObjectTest());
                assetItems.Add(new AssetItem("asset-" + i, assets[i]));
                project.Assets.Add(assetItems[i]);
            }

            assets[1].Base = new AssetBase(assets[0]);

            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                assets[0].RawAsset = "tutu";
                assetItems[0].IsDirty = true;

                var dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                var asset0 = dependencies.GetLinkOut(assetItems[0]);
                Assert.AreEqual(assets[0].RawAsset, ((AssetObjectTest)asset0.Item.Asset).RawAsset);
            }
        }
        public void TestCompositionsInAndOut()
        {
            // -----------------------------------------------------------
            // 3 assets
            // a1 : two parts
            // a2 (baseParts: a1, 2 instances -> 4 parts)
            // a3 (base: a2)
            // -----------------------------------------------------------

            var package = new Package();

            var assetItems = package.Assets;

            var a1 = new TestAssetWithParts();
            a1.Parts.Add(new AssetPartTestItem(Guid.NewGuid()));
            a1.Parts.Add(new AssetPartTestItem(Guid.NewGuid()));
            assetItems.Add(new AssetItem("a1", a1));

            var a2 = new TestAssetWithParts();
            var aPartInstance1 = (TestAssetWithParts)a1.CreateChildAsset("a1");
            var aPartInstance2 = (TestAssetWithParts)a1.CreateChildAsset("a1");
            a2.AddPart(aPartInstance1);
            a2.AddPart(aPartInstance2);
            assetItems.Add(new AssetItem("a2", a2));

            var a3 = a2.CreateChildAsset("a2");
            assetItems.Add(new AssetItem("a3", a3));

            // Create a session with this project
            using (var session = new PackageSession(package))
            {
                var dependencyManager = session.DependencyManager;

                var deps = dependencyManager.FindDependencySet(aPartInstance1.Parts[0].Id);
                Assert.NotNull(deps);

                // The dependencies is the same as the a2 dependencies
                Assert.AreEqual(a2.Id, deps.Id);

                Assert.False(deps.HasMissingDependencies);

                Assert.AreEqual(1, deps.LinksIn.Count()); // a3 inherits from a2
                Assert.AreEqual(1, deps.LinksOut.Count()); // a1 use composition inheritance from a1

                var linkIn = deps.LinksIn.FirstOrDefault();
                Assert.AreEqual(a3.Id, linkIn.Item.Id);
                Assert.AreEqual(ContentLinkType.Reference|ContentLinkType.Inheritance, linkIn.Type);

                var linkOut = deps.LinksOut.FirstOrDefault();
                Assert.AreEqual(a1.Id, linkOut.Item.Id);
                Assert.AreEqual(ContentLinkType.CompositionInheritance, linkOut.Type);
            }
        }
        public void TestCircularAndRecursiveDependencies()
        {
            // -----------------------------------------------------------
            // Tests circular references and dependencies query
            // -----------------------------------------------------------
            // 4 assets
            // [asset1] is referencing [asset2]
            // [asset2] is referencing [asset3]
            // [asset3] is referencing [asset4]
            // [asset4] is referencing [asset1]
            // We create a [project1] with [asset1, asset2, asset3, asset4]
            // Check direct input dependencies for [asset1]: [asset4]
            // Check all all input dependencies for [asset1]: [asset4, asset3, asset2, asset1]
            // Check direct output dependencies for [asset1]: [asset2]
            // Check all all output dependencies for [asset1]: [asset2, asset3, asset4, asset1]
            // -----------------------------------------------------------

            var asset1 = new AssetObjectTest();
            var asset2 = new AssetObjectTest();
            var asset3 = new AssetObjectTest();
            var asset4 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            var assetItem2 = new AssetItem("asset-2", asset2);
            var assetItem3 = new AssetItem("asset-3", asset3);
            var assetItem4 = new AssetItem("asset-4", asset4);
            asset1.Reference = new AssetReference<AssetObjectTest>(assetItem2.Id, assetItem2.Location);
            asset2.Reference = new AssetReference<AssetObjectTest>(assetItem3.Id, assetItem3.Location);
            asset3.Reference = new AssetReference<AssetObjectTest>(assetItem4.Id, assetItem4.Location);
            asset4.Reference = new AssetReference<AssetObjectTest>(assetItem1.Id, assetItem1.Location);

            var project = new Package();
            project.Assets.Add(assetItem1);
            project.Assets.Add(assetItem2);
            project.Assets.Add(assetItem3);
            project.Assets.Add(assetItem4);

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Check internal states
                Assert.AreEqual(1, dependencyManager.Packages.Count); // only one project
                Assert.AreEqual(4, dependencyManager.Dependencies.Count); // asset1, asset2, asset3, asset4
                Assert.AreEqual(0, dependencyManager.AssetsWithMissingReferences.Count);
                Assert.AreEqual(0, dependencyManager.MissingReferencesToParent.Count);

                // Check direct input references
                var dependenciesFirst = dependencyManager.Find(assetItem1);
                Assert.AreEqual(1, dependenciesFirst.LinksIn.Count());
                var copyItem = dependenciesFirst.LinksIn.FirstOrDefault();
                Assert.NotNull(copyItem.Element);
                Assert.AreEqual(assetItem4.Id, copyItem.Item.Id);

                // Check direct output references
                Assert.AreEqual(1, dependenciesFirst.LinksOut.Count());
                copyItem = dependenciesFirst.LinksOut.FirstOrDefault();
                Assert.NotNull(copyItem.Element);
                Assert.AreEqual(assetItem2.Id, copyItem.Item.Id);

                // Calculate full recursive references
                var dependencies = dependencyManager.ComputeDependencies(assetItem1);

                // Check all input references (recursive)
                var asset1RecursiveInputs = dependencies.LinksIn.OrderBy(item => item.Element.Location).ToList();
                Assert.AreEqual(4, dependencies.LinksOut.Count());
                Assert.AreEqual(assetItem1.Id, asset1RecursiveInputs[0].Item.Id);
                Assert.AreEqual(assetItem2.Id, asset1RecursiveInputs[1].Item.Id);
                Assert.AreEqual(assetItem3.Id, asset1RecursiveInputs[2].Item.Id);
                Assert.AreEqual(assetItem4.Id, asset1RecursiveInputs[3].Item.Id);

                // Check all output references (recursive)
                var asset1RecursiveOutputs = dependencies.LinksOut.OrderBy(item => item.Element.Location).ToList();
                Assert.AreEqual(4, asset1RecursiveOutputs.Count);
                Assert.AreEqual(assetItem1.Id, asset1RecursiveInputs[0].Element.Id);
                Assert.AreEqual(assetItem2.Id, asset1RecursiveInputs[1].Element.Id);
                Assert.AreEqual(assetItem3.Id, asset1RecursiveInputs[2].Element.Id);
                Assert.AreEqual(assetItem4.Id, asset1RecursiveInputs[3].Element.Id);
            }
        }
        public void TestInheritFrom()
        {
            // -----------------------------------------------------------
            // Add dependencies of several types and check the InheritingFrom result
            // -----------------------------------------------------------
            // 8 assets
            // A1 -- inherit from --> A0
            // A2 -- inherit from --> A1
            // A3 -- inherit from --> A2
            // A8 -- inherit from --> A1
            // A1 -- reference --> A5
            // A4 -- reference --> A1
            // A1 -- compose --> A7
            // A2 -- compose --> A1
            // A6 -- compose --> A1
            // 
            // Results expected on A1:
            // - Inherit: A2, A8
            // - Composition: A2, A6
            // - All: A2, A6, A8
            // -----------------------------------------------------------

            var project = new Package();
            var assets = new List<AssetObjectTest>();
            var assetItems = new List<AssetItem>();
            for (int i = 0; i < 9; ++i)
            {
                assets.Add(new AssetObjectTest());
                assetItems.Add(new AssetItem("asset-" + i, assets[i]));
                project.Assets.Add(assetItems[i]);
            }

            assets[1].Base = new AssetBase(assets[0]);
            assets[2].Base = new AssetBase(assets[1]);
            assets[3].Base = new AssetBase(assets[2]);
            assets[8].Base = new AssetBase(assets[1]);
            assets[1].Reference = CreateAssetReference(assetItems[5]);
            assets[4].Reference = CreateAssetReference(assetItems[1]);
            assets[1].BaseParts = new List<AssetBase>() { new AssetBase(assetItems[7].Location, assetItems[7].Asset) };
            assets[2].BaseParts = new List<AssetBase>() { new AssetBase(assetItems[1].Location, assetItems[1].Asset) };
            assets[6].BaseParts = new List<AssetBase>() { new AssetBase(assetItems[1].Location, assetItems[1].Asset) };

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                var children = dependencyManager.FindAssetsInheritingFrom(assets[1].Id, AssetInheritanceSearchOptions.Base);
                Assert.AreEqual(2, children.Count);
                Assert.IsTrue(children.Any(x=>x.Id == assets[2].Id));
                Assert.IsTrue(children.Any(x => x.Id == assets[8].Id));

                var compositionChildren = dependencyManager.FindAssetsInheritingFrom(assets[1].Id, AssetInheritanceSearchOptions.Composition);
                Assert.AreEqual(2, compositionChildren.Count);
                Assert.IsTrue(compositionChildren.Any(x => x.Id == assets[2].Id));
                Assert.IsTrue(compositionChildren.Any(x => x.Id == assets[6].Id));

                var all = dependencyManager.FindAssetsInheritingFrom(assets[1].Id, AssetInheritanceSearchOptions.All);
                Assert.AreEqual(3, all.Count);
                Assert.IsTrue(all.Any(x => x.Id == assets[2].Id));
                Assert.IsTrue(all.Any(x => x.Id == assets[6].Id));
                Assert.IsTrue(all.Any(x => x.Id == assets[8].Id));
            }
        }
        public void TestLinkTypeProgressive()
        {
            // -----------------------------------------------------------
            // Progressively add dependencies between elements and check the link types
            // -----------------------------------------------------------
            //
            // 3 assets:
            // A1 -- inherit from --> A0
            // A2 -- inherit from --> A1
            // A1 -- compose --> A0
            // A2 -- compose --> A1
            // A1 -- reference --> A0
            // A2 -- reference --> A1
            // 
            // ---------------------------------------------------------

            var project = new Package();
            var assets = new List<AssetObjectTest>();
            var assetItems = new List<AssetItem>();
            for (int i = 0; i < 3; ++i)
            {
                assets.Add(new AssetObjectTest());
                assetItems.Add(new AssetItem("asset-" + i, assets[i]));
                project.Assets.Add(assetItems[i]);
            }

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                AssetDependencies dependencies;
                var dependencyManager = session.DependencyManager;

                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(0, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                
                assets[1].Reference = CreateAssetReference(assetItems[0]);
                assetItems[1].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[2].Reference = CreateAssetReference(assetItems[1]);
                assetItems[2].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[1].Base = new AssetBase(assets[0]);
                assetItems[1].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.Inheritance, dependencies.GetLinkOut(assetItems[0]).Type);
                
                assets[2].Base = new AssetBase(assets[1]);
                assetItems[2].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.Inheritance, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.Inheritance, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[1].BaseParts = new List<AssetBase> { new AssetBase(assetItems[0].Location, assetItems[0].Asset) };
                assetItems[1].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.Inheritance, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkOut(assetItems[0]).Type);
                
                assets[2].BaseParts = new List<AssetBase> { new AssetBase(assetItems[1].Location, assetItems[1].Asset) };
                assetItems[2].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkOut(assetItems[0]).Type);

                project.Assets.Remove(assetItems[0]);
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(0, dependencies.LinksOut.Count());
                Assert.AreEqual(1, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.All, dependencies.GetBrokenLinkOut(assetItems[0].Id).Type);

                project.Assets.Remove(assetItems[2]);
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(0, dependencies.LinksOut.Count());
                Assert.AreEqual(1, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.All, dependencies.GetBrokenLinkOut(assetItems[0].Id).Type);

                project.Assets.Add(assetItems[0]);
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkOut(assetItems[0]).Type);

                project.Assets.Add(assetItems[2]);
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[2].Base = null;
                assetItems[2].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.CompositionInheritance, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.All, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[1].Base = null;
                assetItems[1].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.CompositionInheritance, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.CompositionInheritance, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[2].BaseParts = null;
                assetItems[2].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.Reference | ContentLinkType.CompositionInheritance, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[1].BaseParts = null;
                assetItems[1].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(1, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[2].Reference = null;
                assetItems[2].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(1, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkOut(assetItems[0]).Type);

                assets[1].Reference = null;
                assetItems[1].IsDirty = true;
                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);
                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(0, dependencies.LinksOut.Count());
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());
            }
        }
        public void TestLinkType()
        {
            // -----------------------------------------------------------
            // Add dependencies of several types and check the links
            // -----------------------------------------------------------
            // 7 assets
            // A1 -- inherit from --> A0
            // A2 -- inherit from --> A1
            // A3 -- compose --> A1
            // A1 -- compose --> A4
            // A5 -- reference --> A1
            // A1 -- reference --> A6
            // 
            // Expected links on A1:
            // - In: A2(Inheritance), A3(Composition), A5(Reference)
            // - Out: A0(Inheritance), A4(Composition), A6(Reference)
            // - BrokenOut: 
            //
            // ------------------------------------
            // Remove all items except A1 and check missing reference types
            // -----------------------------------------------------------
            //
            // Expected broken out links
            // - BrokenOut: A0(Inheritance), A4(Composition), A6(Reference)
            //
            // ---------------------------------------------------------

            var project = new Package();
            var assets = new List<AssetObjectTest>();
            var assetItems = new List<AssetItem>();
            for (int i = 0; i < 7; ++i)
            {
                assets.Add(new AssetObjectTest());
                assetItems.Add(new AssetItem("asset-" + i, assets[i]));
                project.Assets.Add(assetItems[i]);
            }

            assets[1].Base = new AssetBase(assets[0]);
            assets[2].Base = new AssetBase(assets[1]);
            assets[3].BaseParts = new List<AssetBase>() { new AssetBase(assetItems[1].Location, assetItems[1].Asset) };
            assets[1].BaseParts = new List<AssetBase>() { new AssetBase(assetItems[4].Location, assetItems[4].Asset) };
            assets[5].Reference = CreateAssetReference(assetItems[1]);
            assets[1].Reference = CreateAssetReference(assetItems[6]);

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                var dependencies = dependencyManager.ComputeDependencies(assetItems[1]);

                Assert.AreEqual(3, dependencies.LinksIn.Count());
                Assert.AreEqual(ContentLinkType.Inheritance | ContentLinkType.Reference, dependencies.GetLinkIn(assetItems[2]).Type);
                Assert.AreEqual(ContentLinkType.CompositionInheritance, dependencies.GetLinkIn(assetItems[3]).Type);
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkIn(assetItems[5]).Type);

                Assert.AreEqual(3, dependencies.LinksOut.Count());
                Assert.AreEqual(ContentLinkType.Inheritance | ContentLinkType.Reference, dependencies.GetLinkOut(assetItems[0]).Type);
                Assert.AreEqual(ContentLinkType.CompositionInheritance, dependencies.GetLinkOut(assetItems[4]).Type);
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetLinkOut(assetItems[6]).Type);
                
                Assert.AreEqual(0, dependencies.BrokenLinksOut.Count());

                var count = assets.Count;
                for (int i = 0; i < count; i++)
                {
                    if (i != 1)
                        project.Assets.Remove(assetItems[i]);
                }

                dependencies = dependencyManager.ComputeDependencies(assetItems[1]);

                Assert.AreEqual(0, dependencies.LinksIn.Count());
                Assert.AreEqual(0, dependencies.LinksOut.Count());

                Assert.AreEqual(3, dependencies.BrokenLinksOut.Count());
                Assert.AreEqual(ContentLinkType.Inheritance | ContentLinkType.Reference, dependencies.GetBrokenLinkOut(assetItems[0].Id).Type);
                Assert.AreEqual(ContentLinkType.CompositionInheritance, dependencies.GetBrokenLinkOut(assetItems[4].Id).Type);
                Assert.AreEqual(ContentLinkType.Reference, dependencies.GetBrokenLinkOut(assetItems[6].Id).Type);
            }
        }
Beispiel #46
0
        public void TestImportWithDuplicateWithinSameSession()
        {
            var name = "TestAssetImport";
            var file = Path.Combine(Path.GetTempPath(), name + ".tmp");
            const string fileContent = "This is the file content";
            File.WriteAllText(file, fileContent);

            var fileHash = ObjectId.FromBytes(Encoding.UTF8.GetBytes(fileContent));

            // Create a project with an asset reference a raw file
            var project = new Package();
            using (var session = new PackageSession(project))
            {
                var importSession = new AssetImportSession(session);

                // ------------------------------------------------------------------
                // Step 1: Add files to session
                // ------------------------------------------------------------------
                importSession.AddFile(file, project, UDirectory.Empty);
                // Simulate using another importer to duplicate the assets
                importSession.AddFile(file, new CustomImporter(), project, UDirectory.Empty);
                Assert.AreEqual(2, importSession.Imports[0].ByImporters.Count);

                // ------------------------------------------------------------------
                // Step 2: Stage assets
                // ------------------------------------------------------------------
                var stageResult = importSession.Stage();

                //importSession.Imports[0].ByImporters[1].Items[0].SelectedItem = importSession.Imports[0].ByImporters[1].Items[0].Merges[0].PreviousItem;
                // Merge 0 into 1
                importSession.Imports[0].ByImporters[0].Items[0].SelectedItem = importSession.Imports[0].ByImporters[0].Items[0].Merges[0].PreviousItem;

                // ------------------------------------------------------------------
                // Step 4: Merge the asset specified by the previous step
                // ------------------------------------------------------------------
                importSession.Merge();

                Assert.IsTrue(stageResult);

                // ------------------------------------------------------------------
                // Step 3: Import merged asset
                // ------------------------------------------------------------------
                var result = importSession.Import();
                Assert.AreEqual(3, project.Assets.Count);

                // TODO Add more tests
            }
        }
        public void TestAssetChanged()
        {
            // -----------------------------------------------------------
            // Case where an asset is changing is referencing
            // -----------------------------------------------------------
            // 2 assets [asset1, asset2]
            // Change [asset1] referencing [asset2]
            // Notify the session to mark asset1 dirty
            // 
            // -----------------------------------------------------------

            var asset1 = new AssetObjectTest();
            var asset2 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            var assetItem2 = new AssetItem("asset-2", asset2);

            var project = new Package();
            project.Assets.Add(assetItem1);
            project.Assets.Add(assetItem2);

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Check internal states
                Assert.AreEqual(1, dependencyManager.Packages.Count); // only one project
                Assert.AreEqual(2, dependencyManager.Dependencies.Count); // asset1, asset2
                Assert.AreEqual(0, dependencyManager.AssetsWithMissingReferences.Count);
                Assert.AreEqual(0, dependencyManager.MissingReferencesToParent.Count);

                asset1.Reference = new AssetReference<AssetObjectTest>(assetItem2.Id, assetItem2.Location);

                // Mark the asset dirty
                assetItem1.IsDirty = true;

                var dependencies1 = dependencyManager.FindDependencySet(asset1.Id);
                var copyItem = dependencies1.LinksOut.FirstOrDefault();
                Assert.NotNull(copyItem.Element);
                Assert.AreEqual(assetItem2.Id, copyItem.Element.Id);

                var dependencies2 = dependencyManager.FindDependencySet(asset2.Id);
                copyItem = dependencies2.LinksIn.FirstOrDefault();
                Assert.NotNull(copyItem.Element);
                Assert.AreEqual(assetItem1.Id, copyItem.Element.Id);
            }
        }
        public void TestPackageAnalysis()
        {
            var package = new Package();

            var baseAsset = new TestDiffAsset() { Name = "Red", Value = 1 };
            var baseItem = new AssetItem("base", baseAsset);

            var childAsset = (TestDiffAsset)baseItem.CreateChildAsset();
            var childItem = new AssetItem("child", childAsset);

            var newBaseAsset = (TestDiffAsset)AssetCloner.Clone(baseAsset);
            newBaseAsset.Name = "Green";
            var newBaseItem = new AssetItem("base", newBaseAsset);

            package.Assets.Add(newBaseItem);
            package.Assets.Add(childItem);

            var session = new PackageSession();
            session.Packages.Add(package);

            var result = new LoggerResult();
            var analysis = new PackageAssetTemplatingAnalysis(package, result);
            analysis.Run();

            Assert.False(result.HasErrors);

            var assetModified = (TestDiffAsset)package.Assets.Find("child").Asset;
            Assert.AreEqual("Green", assetModified.Name);
        }
 /// <summary>
 /// Collects all references of an asset dynamically.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <param name="packageSession">The package session.</param>
 /// <param name="isRecursive">if set to <c>true</c> [is recursive].</param>
 /// <param name="keepParents">Indicate if the parent of the provided <paramref name="result"/> should be kept or not</param>
 /// <exception cref="System.ArgumentNullException">packageSession</exception>
 private static void CollectDynamicOutReferences(AssetDependencies result, PackageSession packageSession, bool isRecursive, bool keepParents)
 {
     if (packageSession == null) throw new ArgumentNullException("packageSession");
     CollectDynamicOutReferences(result, packageSession.FindAsset, isRecursive, keepParents);
 }
Beispiel #50
0
        public void TestBasicPackageCreateSaveLoad()
        {
            var dirPath = DirectoryTestBase + @"TestBasicPackageCreateSaveLoad";

            string testGenerated1 = Path.Combine(dirPath, "TestPackage_TestBasicPackageCreateSaveLoad_Generated1.pdxpkg");
            string testGenerated2 = Path.Combine(dirPath,"TestPackage_TestBasicPackageCreateSaveLoad_Generated2.pdxpkg");
            string referenceFilePath = Path.Combine(dirPath,"TestPackage_TestBasicPackageCreateSaveLoad_Reference.pdxpkg");

            // Force the PackageId to be the same each time we run the test
            // Usually the PackageId is unique and generated each time we create a new project
            var project = new Package { Id = Guid.Empty, FullPath = testGenerated1 };
            var sharedProfile = new PackageProfile("Shared", new AssetFolder("."));
            project.Profiles.Add(sharedProfile);
            var projectReference = new ProjectReference(Guid.Empty, Path.Combine(dirPath, "test.csproj"), ProjectType.Executable);
            sharedProfile.ProjectReferences.Add(projectReference);

            var session = new PackageSession(project);
            // Write the solution when saving
            session.SolutionPath = Path.Combine(dirPath, "TestPackage_TestBasicPackageCreateSaveLoad_Generated1.sln");

            // Delete the solution before saving it 
            if (File.Exists(session.SolutionPath))
            {
                File.Delete(session.SolutionPath);
            }

            var result = session.Save();
            Assert.IsFalse(result.HasErrors);

            // Reload the raw package and if UFile and UDirectory were saved relative
            var rawPackage = (Package)AssetSerializer.Load(testGenerated1);
            var rawPackageSharedProfile = rawPackage.Profiles.FirstOrDefault();
            Assert.IsNotNull(rawPackageSharedProfile);
            var rawSourceFolder = rawPackage.Profiles.First().AssetFolders.FirstOrDefault();
            Assert.IsNotNull(rawSourceFolder);
            Assert.AreEqual(".", (string)rawSourceFolder.Path);
            Assert.AreEqual("test.csproj", (string)rawPackageSharedProfile.ProjectReferences[0].Location);

            // Reload the package directly from the pdxpkg
            var project2Result = PackageSession.Load(testGenerated1);
            AssertResult(project2Result);
            var project2 = project2Result.Session.LocalPackages.FirstOrDefault();
            Assert.IsNotNull(project2);
            Assert.AreEqual(project.Id, project2.Id);
            Assert.IsTrue(project2.Profiles.Count > 0);
            Assert.IsTrue(project2.Profiles.First().AssetFolders.Count > 0);
            var sourceFolder = project.Profiles.First().AssetFolders.First().Path;
            Assert.AreEqual(sourceFolder, project2.Profiles.First().AssetFolders.First().Path);

            // Reload the package from the sln
            var sessionResult = PackageSession.Load(session.SolutionPath);
            Assert.IsFalse(sessionResult.HasErrors);

            var sessionReload = sessionResult.Session;
            Assert.AreEqual(1, sessionReload.LocalPackages.Count());
            Assert.AreEqual(project.Id, sessionReload.LocalPackages.First().Id);
            Assert.AreEqual(1, sessionReload.LocalPackages.First().Profiles.Count);

            var sharedProfileReload = sessionReload.LocalPackages.First().Profiles.First();
            Assert.AreEqual(1, sharedProfileReload.ProjectReferences.Count);
            Assert.AreEqual(projectReference, sharedProfileReload.ProjectReferences[0]);
        }
        public void TestAssetPart()
        {
            var project = new Package();
            var assets = new List<TestAssetWithParts>();
            var assetItems = new List<AssetItem>();
            for (int i = 0; i < 2; ++i)
            {
                assets.Add(new TestAssetWithParts() { Parts =
                {
                        new AssetPartTestItem(Guid.NewGuid()),
                        new AssetPartTestItem(Guid.NewGuid())
                }
                });
                assetItems.Add(new AssetItem("asset-" + i, assets[i]));
                project.Assets.Add(assetItems[i]);
            }

            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Check that part asset is accessible from the dependency manager

                var innerAssetId = assets[0].Parts[0].Id;
                var dependencySet = dependencyManager.FindDependencySet(innerAssetId);
                Assert.NotNull(dependencySet);

                // Check that dependencies are the same than container asset.
                var containerDependencySet = dependencyManager.FindDependencySet(assets[0].Id);
                Assert.AreEqual(containerDependencySet.Id, dependencySet.Id, "DependencySet must be the same for part and container");

                // Check that inners are all there
                Assert.AreEqual(2, dependencySet.Parts.Count());

                // Check that part asset is correctly stored into the dependencies
                AssetPart part;
                Assert.IsTrue(dependencySet.TryGetAssetPart(innerAssetId, out part));
                Assert.AreEqual(assets[0].Parts[0].Id, part.Id);

                // Remove part asset
                assets[0].Parts.Clear();
                assetItems[0].IsDirty = true;

                Assert.Null(dependencyManager.FindDependencySet(innerAssetId));
            }
        }
        public void TestMissingReferences()
        {
            // -----------------------------------------------------------
            // Tests missing references
            // -----------------------------------------------------------
            // 3 assets
            // [asset1] is referencing [asset2]
            // [asset3] is referencing [asset1]
            // Add asset1. Check dependencies
            // Add asset2. Check dependencies
            // Add asset3. Check dependencies
            // Remove asset1. Check dependencies
            // Add asset1. Check dependencies.
            // Modify reference asset3 to asset1 with fake asset. Check dependencies
            // Revert reference asset3 to asset1. Check dependencies
            // -----------------------------------------------------------

            var asset1 = new AssetObjectTest();
            var asset2 = new AssetObjectTest();
            var asset3 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            var assetItem2 = new AssetItem("asset-2", asset2);
            var assetItem3 = new AssetItem("asset-3", asset3);

            asset1.Reference = new AssetReference<AssetObjectTest>(assetItem2.Id, assetItem2.Location);
            asset3.Reference = new AssetReference<AssetObjectTest>(assetItem1.Id, assetItem1.Location);

            var project = new Package();

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Add asset1
                project.Assets.Add(assetItem1);
                {
                    var assets = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset1.Id, assets[0]);

                    // Check dependencies on asset1
                    var dependencySetAsset1 = dependencyManager.FindDependencySet(asset1.Id);
                    Assert.NotNull(dependencySetAsset1);

                    Assert.AreEqual(0, dependencySetAsset1.LinksOut.Count());
                    Assert.IsTrue(dependencySetAsset1.HasMissingDependencies);
                    Assert.AreEqual(asset2.Id, dependencySetAsset1.BrokenLinksOut.First().Element.Id);
                }

                // Add asset2
                project.Assets.Add(assetItem2);
                {
                    var assets = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(0, assets.Count);

                    // Check dependencies on asset1
                    var dependencySetAsset1 = dependencyManager.FindDependencySet(asset1.Id);
                    Assert.NotNull(dependencySetAsset1);

                    Assert.AreEqual(1, dependencySetAsset1.LinksOut.Count());
                    Assert.AreEqual(0, dependencySetAsset1.LinksIn.Count());
                    Assert.AreEqual(asset2.Id, dependencySetAsset1.LinksOut.First().Element.Id);

                    // Check dependencies on asset2
                    var dependencySetAsset2 = dependencyManager.FindDependencySet(asset2.Id);
                    Assert.NotNull(dependencySetAsset2);

                    Assert.AreEqual(0, dependencySetAsset2.LinksOut.Count());
                    Assert.AreEqual(1, dependencySetAsset2.LinksIn.Count());
                    Assert.AreEqual(asset1.Id, dependencySetAsset2.LinksIn.First().Element.Id);
                }

                // Add asset3
                project.Assets.Add(assetItem3);
                Action checkAllOk = () =>
                {
                    var assets = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(0, assets.Count);

                    // Check dependencies on asset1
                    var dependencySetAsset1 = dependencyManager.FindDependencySet(asset1.Id);
                    Assert.NotNull(dependencySetAsset1);

                    Assert.AreEqual(1, dependencySetAsset1.LinksOut.Count());
                    Assert.AreEqual(1, dependencySetAsset1.LinksIn.Count());
                    Assert.AreEqual(asset2.Id, dependencySetAsset1.LinksOut.First().Element.Id);
                    Assert.AreEqual(asset3.Id, dependencySetAsset1.LinksIn.First().Element.Id);

                    // Check dependencies on asset2
                    var dependencySetAsset2 = dependencyManager.FindDependencySet(asset2.Id);
                    Assert.NotNull(dependencySetAsset2);

                    Assert.AreEqual(0, dependencySetAsset2.LinksOut.Count());
                    Assert.AreEqual(1, dependencySetAsset2.LinksIn.Count());
                    Assert.AreEqual(asset1.Id, dependencySetAsset2.LinksIn.First().Element.Id);

                    // Check dependencies on asset3
                    var dependencySetAsset3 = dependencyManager.FindDependencySet(asset3.Id);
                    Assert.NotNull(dependencySetAsset3);

                    Assert.AreEqual(1, dependencySetAsset3.LinksOut.Count());
                    Assert.AreEqual(0, dependencySetAsset3.LinksIn.Count());
                    Assert.AreEqual(asset1.Id, dependencySetAsset3.LinksOut.First().Element.Id);
                };
                checkAllOk();

                // Remove asset1
                project.Assets.Remove(assetItem1);
                {
                    var assets = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset3.Id, assets[0]);

                    // Check dependencies on asset2
                    var dependencySetAsset2 = dependencyManager.FindDependencySet(asset2.Id);
                    Assert.NotNull(dependencySetAsset2);

                    Assert.AreEqual(0, dependencySetAsset2.LinksOut.Count());
                    Assert.AreEqual(0, dependencySetAsset2.LinksIn.Count());

                    // Check dependencies on asset3
                    var dependencySetAsset3 = dependencyManager.FindDependencySet(asset3.Id);
                    Assert.NotNull(dependencySetAsset3);

                    Assert.AreEqual(0, dependencySetAsset3.LinksOut.Count());
                    Assert.AreEqual(0, dependencySetAsset3.LinksIn.Count());
                    Assert.IsTrue(dependencySetAsset3.HasMissingDependencies);
                    Assert.AreEqual(asset1.Id, dependencySetAsset3.BrokenLinksOut.First().Element.Id);
                }

                // Add asset1
                project.Assets.Add(assetItem1);
                checkAllOk();

                // Modify reference asset3 to asset1 with fake asset
                var previousAsset3ToAsset1Reference = asset3.Reference;
                asset3.Reference = new AssetReference<AssetObjectTest>(Guid.NewGuid(), "fake");
                assetItem3.IsDirty = true;
                {
                    var assets = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset3.Id, assets[0]);

                    // Check dependencies on asset1
                    var dependencySetAsset1 = dependencyManager.FindDependencySet(asset1.Id);
                    Assert.NotNull(dependencySetAsset1);

                    Assert.AreEqual(1, dependencySetAsset1.LinksOut.Count());
                    Assert.AreEqual(0, dependencySetAsset1.LinksIn.Count());
                    Assert.AreEqual(asset2.Id, dependencySetAsset1.LinksOut.First().Element.Id);

                    // Check dependencies on asset2
                    var dependencySetAsset2 = dependencyManager.FindDependencySet(asset2.Id);
                    Assert.NotNull(dependencySetAsset2);

                    Assert.AreEqual(0, dependencySetAsset2.LinksOut.Count());
                    Assert.AreEqual(1, dependencySetAsset2.LinksIn.Count());
                    Assert.AreEqual(asset1.Id, dependencySetAsset2.LinksIn.First().Element.Id);

                    // Check dependencies on asset3
                    var dependencySetAsset3 = dependencyManager.FindDependencySet(asset3.Id);
                    Assert.NotNull(dependencySetAsset3);

                    Assert.AreEqual(0, dependencySetAsset3.LinksOut.Count());
                    Assert.AreEqual(0, dependencySetAsset3.LinksIn.Count());
                    Assert.IsTrue(dependencySetAsset3.HasMissingDependencies);
                    Assert.AreEqual(asset3.Reference.Id, dependencySetAsset3.BrokenLinksOut.First().Element.Id);
                }

                // Revert back reference from asset3 to asset1
                asset3.Reference = previousAsset3ToAsset1Reference;
                assetItem3.IsDirty = true;
                checkAllOk();
            }
        }
        public void TestTrackingPackageWithAssetsAndSave()
        {
            var dirPath = Path.Combine(Environment.CurrentDirectory, DirectoryTestBase + @"TestTracking");
            TryDeleteDirectory(dirPath);

            string testGenerated1 = Path.Combine(dirPath, "TestTracking.xkpkg");

            var project = new Package { FullPath = testGenerated1 };
            project.Profiles.Add(new PackageProfile("Shared", new AssetFolder(".")));
            var asset1 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            project.Assets.Add(assetItem1);

            using (var session = new PackageSession(project))
            {

                var dependencies = session.DependencyManager;
                dependencies.TrackingSleepTime = 10;
                dependencies.EnableTracking = true;

                // Save the session
                {
                    var result = session.Save();
                    Assert.IsFalse(result.HasErrors);

                    // Wait enough time for events
                    Thread.Sleep(100);

                    // Make sure that save is not generating events
                    var events = dependencies.FindAssetFileChangedEvents().ToList();
                    Assert.AreEqual(0, events.Count);

                    // Check tracked directories
                    var directoriesTracked = dependencies.DirectoryWatcher.GetTrackedDirectories();
                    Assert.AreEqual(1, directoriesTracked.Count);
                    Assert.AreEqual(dirPath.ToLowerInvariant(), directoriesTracked[0].ToLowerInvariant());

                    // Simulate multiple change an asset on the disk
                    File.SetLastWriteTime(assetItem1.FullPath, DateTime.Now);
                    Thread.Sleep(100);

                    // Check that we are capturing this event
                    events = dependencies.FindAssetFileChangedEvents().ToList();
                    Assert.AreEqual(1, events.Count);
                    Assert.AreEqual(assetItem1.Location, events[0].AssetLocation);
                    Assert.AreEqual(AssetFileChangedType.Updated, events[0].ChangeType);
                }

                // Save the project to another location
                {
                    var dirPath2 = Path.Combine(Environment.CurrentDirectory, DirectoryTestBase + @"TestTracking2");
                    TryDeleteDirectory(dirPath2);
                    string testGenerated2 = Path.Combine(dirPath2, "TestTracking.xkpkg");

                    project.FullPath = testGenerated2;
                    var result = session.Save();
                    Assert.IsFalse(result.HasErrors);

                    // Wait enough time for events
                    Thread.Sleep(200);

                    // Make sure that save is not generating events
                    var events = dependencies.FindAssetFileChangedEvents().ToList();
                    Assert.AreEqual(0, events.Count);

                    // Check tracked directories
                    var directoriesTracked = dependencies.DirectoryWatcher.GetTrackedDirectories();
                    Assert.AreEqual(1, directoriesTracked.Count);
                    Assert.AreEqual(dirPath2.ToLowerInvariant(), directoriesTracked[0].ToLowerInvariant());
                }

                // Copy file to simulate a new file on the disk (we will not try to load it as it has the same guid 
                {
                    var fullPath = assetItem1.FullPath;
                    var newPath = Path.Combine(Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath) + "2" + Path.GetExtension(fullPath));
                    File.Copy(fullPath, newPath);

                    // Wait enough time for events
                    Thread.Sleep(200);

                    // Make sure that save is not generating events
                    var events = dependencies.FindAssetFileChangedEvents().ToList();
                    Assert.AreEqual(1, events.Count);
                    Assert.IsTrue((events[0].ChangeType & AssetFileChangedType.Added) != 0);
                }
            }
        }
Beispiel #54
0
        public void TestImportSessionSimple()
        {
            var name = "TestAssetImport";
            var file = Path.Combine(Path.GetTempPath(), name + ".tmp");
            const string fileContent = "This is the file content";
            File.WriteAllText(file, fileContent);
            var fileHash = ObjectId.FromBytes(Encoding.UTF8.GetBytes(fileContent));

            // Create a project with an asset reference a raw file
            var project = new Package();
            using (var session = new PackageSession(project))
            {
                var importSession = new AssetImportSession(session);

                // ------------------------------------------------------------------
                // Step 1: Add files to session
                // ------------------------------------------------------------------
                importSession.AddFile(file, project, UDirectory.Empty);

                // ------------------------------------------------------------------
                // Step 2: Stage assets
                // ------------------------------------------------------------------
                var stageResult = importSession.Stage();
                Assert.IsTrue(stageResult);
                Assert.AreEqual(0, project.Assets.Count);

                // ------------------------------------------------------------------
                // Step 3: Import asset directly (we don't try to merge)
                // ------------------------------------------------------------------
                importSession.Import();
                Assert.AreEqual(2, project.Assets.Count);
                var assetItem = project.Assets.FirstOrDefault(item => item.Asset is AssetImport);
                Assert.NotNull(assetItem);
                var importedAsset = (AssetImport)assetItem.Asset;

                Assert.IsInstanceOf<AssetImport>(importedAsset.Base.Asset);
                Assert.AreEqual((string)AssetBase.DefaultImportBase, importedAsset.Base.Location);

                // ------------------------------------------------------------------
                // Reset the import session
                // ------------------------------------------------------------------
                importSession.Reset();

                // Get the list of asset already in the project
                var ids = project.Assets.Select(item => item.Id).ToList();
                ids.Sort();

                // ------------------------------------------------------------------
                // Step 1: Add same file to the session
                // ------------------------------------------------------------------
                importSession.AddFile(file, project, UDirectory.Empty);

                // ------------------------------------------------------------------
                // Step 2: Stage assets
                // ------------------------------------------------------------------
                stageResult = importSession.Stage();

                // Select the previous item so that we will perform a merge
                foreach (var fileToImport in importSession.Imports)
                {
                    foreach (var import in fileToImport.ByImporters)
                    {
                        foreach (var assetImportMergeGroup in import.Items)
                        {
                            Assert.AreEqual(1, assetImportMergeGroup.Merges.Count);

                            // Check that we are matching correctly a previously imported asset
                            var previousItem = assetImportMergeGroup.Merges[0].PreviousItem;
                            Assert.IsTrue(project.Assets.ContainsById(previousItem.Id));

                            // Select the previous asset
                            assetImportMergeGroup.SelectedItem = previousItem;
                        }
                    }
                }

                // ------------------------------------------------------------------
                // Step 3: Merge the asset specified by the previous step
                // ------------------------------------------------------------------
                importSession.Merge();

                Assert.IsTrue(stageResult);
                Assert.AreEqual(2, project.Assets.Count);

                // ------------------------------------------------------------------
                // Step 4: Import merged asset
                // ------------------------------------------------------------------
                importSession.Import();
                Assert.AreEqual(2, project.Assets.Count);

                // Get the list of asset already in the project
                var newIds = project.Assets.Select(item => item.Id).ToList();
                newIds.Sort();

                // Check that we have exactly the same number of assets
                Assert.AreEqual(ids, newIds);

                // Check that new AssetObjectTestRaw.Value is setup to the new value (1, was previously 0)
                var assetRaw = project.Assets.Select(item => item.Asset).OfType<AssetObjectTestSub>().FirstOrDefault();
                Assert.IsNotNull(assetRaw);
                Assert.IsNotNull(assetRaw.Base);
                Assert.IsInstanceOf<AssetObjectTestSub>(assetRaw.Base.Asset);

                var assetRawBase = (AssetObjectTestSub)assetRaw.Base.Asset;
                Assert.AreEqual(1, assetRaw.Value);
                Assert.AreEqual(1, assetRawBase.Value);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageSessionAnalysis" /> class.
 /// </summary>
 /// <param name="packageSession">The package session.</param>
 /// <exception cref="System.ArgumentNullException">packageSession</exception>
 protected PackageSessionAnalysisBase(PackageSession packageSession)
 {
     if (packageSession == null) throw new ArgumentNullException("packageSession");
     this.packageSession = packageSession;
 }
        public void TestFullSession()
        {
            // -----------------------------------------------------------
            // This is a more complex test mixing several different cases:
            // -----------------------------------------------------------
            // 4 assets
            // [asset1] is referencing [asset2]
            // [asset3] is referencing [asset4]
            // We create a [project1] with [asset1, asset2, asset3]
            // Start to evaluate the dependencies 
            // Check the dependencies for this project, [asset4] is missing
            // We create a [project2] and add it to the session
            // We add [asset4] to the [project2]
            // All depedencies should be fine
            // Remove [project2] from session
            // Check the dependencies for this project, [asset4] is missing
            // -----------------------------------------------------------

            var asset1 = new AssetObjectTest();
            var asset2 = new AssetObjectTest();
            var asset3 = new AssetObjectTest();
            var asset4 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            var assetItem2 = new AssetItem("asset-2", asset2);
            var assetItem3 = new AssetItem("asset-3", asset3);
            var assetItem4 = new AssetItem("asset-4", asset4);
            asset1.Reference = new AssetReference<AssetObjectTest>(assetItem2.Id, assetItem2.Location);
            asset3.Reference = new AssetReference<AssetObjectTest>(assetItem4.Id, assetItem4.Location);

            var project = new Package();
            project.Assets.Add(assetItem1);
            project.Assets.Add(assetItem2);
            project.Assets.Add(assetItem3);

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Check internal states
                Action checkState1 = () =>
                {
                    Assert.AreEqual(1, dependencyManager.Packages.Count); // only one project
                    Assert.AreEqual(3, dependencyManager.Dependencies.Count); // asset1, asset2, asset3
                    Assert.AreEqual(1, dependencyManager.AssetsWithMissingReferences.Count); // asset3 => asset4
                    Assert.AreEqual(1, dependencyManager.MissingReferencesToParent.Count); // asset4 => [asset3]

                    // Check missing references for asset3 => X asset4
                    var assetItemWithMissingReferences = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(1, assetItemWithMissingReferences.Count);
                    Assert.AreEqual(assetItem3.Id, assetItemWithMissingReferences[0]);

                    // Check missing reference
                    var missingReferences = dependencyManager.FindMissingReferences(assetItem3).ToList();
                    Assert.AreEqual(1, missingReferences.Count);
                    Assert.AreEqual(asset4.Id, missingReferences[0].Id);

                    // Check references for: asset1 => asset2
                    var referencesFromAsset1 = dependencyManager.ComputeDependencies(assetItem1);
                    Assert.AreEqual(1, referencesFromAsset1.LinksOut.Count());
                    var copyItem = referencesFromAsset1.LinksOut.FirstOrDefault();
                    Assert.NotNull(copyItem.Element);
                    Assert.AreEqual(assetItem2.Id, copyItem.Element.Id);
                };
                checkState1();

                {
                    // Add new project (must be tracked by the dependency manager)
                    var project2 = new Package();
                    session.Packages.Add(project2);

                    // Check internal states
                    Assert.AreEqual(2, dependencyManager.Packages.Count);

                    // Add missing asset4
                    project2.Assets.Add(assetItem4);
                    var assetItemWithMissingReferences = dependencyManager.FindAssetsWithMissingReferences().ToList();
                    Assert.AreEqual(0, assetItemWithMissingReferences.Count);

                    // Check internal states
                    Assert.AreEqual(4, dependencyManager.Dependencies.Count); // asset1, asset2, asset3, asse4
                    Assert.AreEqual(0, dependencyManager.AssetsWithMissingReferences.Count);
                    Assert.AreEqual(0, dependencyManager.MissingReferencesToParent.Count);

                    // Try to remove the project and double check
                    session.Packages.Remove(project2);

                    checkState1();
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TemplateGeneratorContext"/> class.
 /// </summary>
 /// <param name="session">The session.</param>
 public TemplateGeneratorContext(PackageSession session)
 {
     if (session == null) throw new ArgumentNullException("session");
     Session = session;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetBaseAnalysis"/> class.
 /// </summary>
 /// <param name="packageSession">The package session.</param>
 public AssetBaseAnalysis(PackageSession packageSession)
     : base(packageSession)
 {
 }