Exemple #1
0
        private static void Configure(EnvironmentOptions options)
        {
            var settingsRepository = new SettingsRepository();

            EnvironmentName = options.Environment;
            Settings        = settingsRepository.GetEnvironment(options);
        }
        /// <summary>
        /// Builds the requested target framework(s).
        /// </summary>
        /// <param name="targetFrameworks">The set of target frameworks to build.</param>
        /// <param name="environmentOptions">The environment options to use for the build.</param>
        /// <returns>A dictionary of target frameworks to <see cref="AnalyzerResult"/>.</returns>
        public AnalyzerResults Build(string[] targetFrameworks, EnvironmentOptions environmentOptions)
        {
            if (environmentOptions == null)
            {
                throw new ArgumentNullException(nameof(environmentOptions));
            }

            // If the set of target frameworks is empty, just build the default
            if (targetFrameworks == null || targetFrameworks.Length == 0)
            {
                targetFrameworks = new string[] { null };
            }

            // Create a new build envionment for each target
            AnalyzerResults results = new AnalyzerResults();

            foreach (string targetFramework in targetFrameworks)
            {
                BuildEnvironment buildEnvironment = EnvironmentFactory.GetBuildEnvironment(targetFramework, environmentOptions);
                string[]         targetsToBuild   = buildEnvironment.TargetsToBuild;
                Restore(buildEnvironment, ref targetsToBuild);
                results.Add(BuildTargets(buildEnvironment, targetFramework, targetsToBuild, true));
            }

            return(results);
        }
        public EnvironmentSettings GetEnvironment(EnvironmentOptions options)
        {
            var result             = new EnvironmentSettings();
            var settingsRepository = new SettingsRepository();
            var _settings          = settingsRepository.FindEnvironment(options.Environment);

            result.Uri                  = string.IsNullOrEmpty(options.Uri) ? _settings.Uri : options.Uri;
            result.IsNetCore            = options.IsNetCore ?? _settings.IsNetCore;
            result.DeveloperModeEnabled = options.DeveloperModeEnabled ?? _settings.DeveloperModeEnabled;
            result.Login                = string.IsNullOrEmpty(options.Login) ? _settings.Login : options.Login;
            result.Password             = string.IsNullOrEmpty(options.Password) ? _settings.Password : options.Password;
            result.Maintainer           =
                string.IsNullOrEmpty(options.Maintainer) ? _settings.Maintainer : options.Maintainer;
            if (_settings.Safe.HasValue && _settings.Safe.Value)
            {
                Console.WriteLine($"You try to apply the action on the production site {_settings.Uri}");
                Console.Write($"Do you want to continue? [Y/N]:");
                var answer = Console.ReadKey();
                Console.WriteLine();
                if (answer.KeyChar != 'y' && answer.KeyChar != 'Y')
                {
                    Console.WriteLine("Operation was canceled by user");
                    System.Environment.Exit(1);
                }
            }
            return(result);
        }
Exemple #4
0
        public void GetsProjectGuidFromProject([ValueSource(nameof(Preferences))] EnvironmentPreference preference)
        {
            // Given
            const string     projectFile = @"SdkNetCoreProject\SdkNetCoreProject.csproj";
            IProjectAnalyzer analyzer    = new AnalyzerManager()
                                           .GetProject(GetProjectPath(projectFile));
            EnvironmentOptions options = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            DeleteProjectDirectory(projectFile, "obj");
            DeleteProjectDirectory(projectFile, "bin");
            IAnalyzerResults results = analyzer.Build(options);

            // Then
            // The generated GUIDs are based on subpath, so they'll be different from Windows to Linux
            // They can also change between MSBuild versions, so this may need to be updated periodically
#if Is_Windows
            results.First().ProjectGuid.ToString().ShouldBe("432bfde1-4768-5837-8e20-8bb49c9d4734");
#else
            results.First().ProjectGuid.ToString().ShouldBe("c9df4376-d954-5554-bd10-b9976b7afa9d");
#endif
        }
        public void GetsSourceFiles(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            IProjectAnalyzer   analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            IAnalyzerResults results = analyzer.Build(options);

            // Then
            // If this is the multi-targeted project, use the net462 target
            IReadOnlyList <string> sourceFiles = results.Count == 1 ? results.First().SourceFiles : results["net462"].SourceFiles;

            sourceFiles.ShouldNotBeNull(log.ToString());
            new[]
            {
#if Is_Windows
                // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                "AssemblyAttributes",
#endif
                "Class1",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
        }
Exemple #6
0
        /// <summary>
        /// Builds the requested target framework(s).
        /// </summary>
        /// <param name="targetFrameworks">The set of target frameworks to build.</param>
        /// <param name="environmentOptions">The environment options to use for the build.</param>
        /// <returns>A dictionary of target frameworks to <see cref="AnalyzerResult"/>.</returns>
        public AnalyzerResults Build(string[] targetFrameworks, EnvironmentOptions environmentOptions)
        {
            if (environmentOptions == null)
            {
                throw new ArgumentNullException(nameof(environmentOptions));
            }

            // If the set of target frameworks is empty, just build the default
            if (targetFrameworks == null || targetFrameworks.Length == 0)
            {
                targetFrameworks = new string[] { null };
            }

            // Reset the cache before every build in case MSBuild cached something from a project reference build
            Manager.BuildManager.ResetCaches();

            // Create a new build envionment for each target
            AnalyzerResults results = new AnalyzerResults();

            foreach (string targetFramework in targetFrameworks)
            {
                BuildEnvironment buildEnvironment = EnvironmentFactory.GetBuildEnvironment(targetFramework, environmentOptions);
                string[]         targetsToBuild   = buildEnvironment.TargetsToBuild;
                Restore(buildEnvironment, ref targetsToBuild);
                results.Add(BuildTargets(buildEnvironment, targetFramework, targetsToBuild));
            }

            return(results);
        }
Exemple #7
0
        public static AdhocWorkspace GetWorkspaceWithPreventBuildEvent(this AnalyzerManager manager)
        {
            // info article: https://qiita.com/skitoy4321/items/9edfb094549f5167a57f
            var projPath = manager.Projects.First().Value.ProjectFile.Path;
            var tempPath = Path.Combine(new FileInfo(projPath).Directory.FullName, "__buildtemp") + System.IO.Path.DirectorySeparatorChar;

            var envopts = new EnvironmentOptions();

            // "Clean" and "Build" is listed in default
            // Modify to designtime system https://github.com/dotnet/project-system/blob/master/docs/design-time-builds.md#targets-that-run-during-design-time-builds
            // that prevent Pre/PostBuildEvent

            envopts.TargetsToBuild.Clear();
            // Clean should not use(if use pre/post build, dll was deleted).
            // envopts.TargetsToBuild.Add("Clean");
            envopts.TargetsToBuild.Add("ResolveAssemblyReferencesDesignTime");
            envopts.TargetsToBuild.Add("ResolveProjectReferencesDesignTime");
            envopts.TargetsToBuild.Add("ResolveComReferencesDesignTime");
            envopts.TargetsToBuild.Add("Compile");
            envopts.GlobalProperties["IntermediateOutputPath"] = tempPath;
            try
            {
                return(GetWorkspace(manager, envopts));
            }
            finally
            {
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
Exemple #8
0
        public MsBuildExeFixtureResult Execute()
        {
            var analyzer = manager.GetProject(ProjectPath);

            var output = new StringWriter();

            analyzer.AddBuildLogger(new ConsoleLogger(LoggerVerbosity.Normal, output.Write, null, null));

            var environmentOptions = new EnvironmentOptions {
                DesignTime = false
            };

            environmentOptions.TargetsToBuild.Clear();
            environmentOptions.TargetsToBuild.Add(OutputTarget);

            if (environmentVariables != null)
            {
                foreach (var pair in environmentVariables)
                {
                    analyzer.SetEnvironmentVariable(pair.Key, pair.Value);
                }
            }

            var results = analyzer.Build(environmentOptions);

            return(new MsBuildExeFixtureResult(fixture)
            {
                ProjectPath = ProjectPath,
                Output = output.ToString(),
                MsBuild = results
            });
        }
Exemple #9
0
        public VideoProfile(EnvironmentOptions env)
        {
            _env = env;

            CreateMap <Video, VideoDetail>()
            .ForMember(dest => dest.Tags, map => map.MapFrom(v => v.Tags.Select(t => t.Name).ToList()))
            .ForMember(dest => dest.ThumbURL, map => map.MapFrom(v => $"{_env.ApiUrl}/{v.ThumbURL}"));
        }
Exemple #10
0
        public Project Load(string targetFramework, EnvironmentOptions environmentOptions)
        {
            if (environmentOptions == null)
            {
                throw new ArgumentNullException(nameof(environmentOptions));
            }

            return(Load(targetFramework, EnvironmentFactory.GetBuildEnvironment(targetFramework, environmentOptions)));
        }
Exemple #11
0
        public Project Load(EnvironmentOptions environmentOptions)
        {
            if (environmentOptions == null)
            {
                throw new ArgumentNullException(nameof(environmentOptions));
            }

            return(Load(null, EnvironmentFactory.GetBuildEnvironment(environmentOptions)));
        }
        /// <summary>
        /// Builds a specific target framework.
        /// </summary>
        /// <param name="targetFramework">The target framework to build.</param>
        /// <param name="environmentOptions">The environment options to use for the build.</param>
        /// <returns>The result of the build process.</returns>
        public AnalyzerResults Build(string targetFramework, EnvironmentOptions environmentOptions)
        {
            if (environmentOptions == null)
            {
                throw new ArgumentNullException(nameof(environmentOptions));
            }

            return(Build(targetFramework, EnvironmentFactory.GetBuildEnvironment(targetFramework, environmentOptions)));
        }
Exemple #13
0
        private EnvironmentOptions GetEnvironmentOptions(bool requiresNetFramework, string toolsVersion)
        {
            var os = DetermineOSPlatform();
            EnvironmentOptions options = new EnvironmentOptions();

            if (os == OSPlatform.Linux || os == OSPlatform.OSX)
            {
                if (requiresNetFramework)
                {
                    options.EnvironmentVariables.Add(EnvironmentVariables.MSBUILD_EXE_PATH, Constants.MsBuildCommandName);
                }
            }

            //We want to provide the MsBuild path only if it's a framework solution. Buildalyzer automatically builds core solutions using "dotnet"
            if (requiresNetFramework)
            {
                try
                {
                    var msbuildExe = _analyzerConfiguration.BuildSettings.MSBuildPath;
                    if (string.IsNullOrEmpty(msbuildExe))
                    {
                        msbuildExe = _msBuildDetector.GetFirstMatchingMsBuildFromPath(toolsVersion: toolsVersion);
                    }
                    if (!string.IsNullOrEmpty(msbuildExe))
                    {
                        options.EnvironmentVariables.Add(EnvironmentVariables.MSBUILD_EXE_PATH, msbuildExe);
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Build error: Codelyzer wasn't able to retrieve the MSBuild path");
                }
                _analyzerConfiguration.BuildSettings.BuildArguments.ForEach(argument => {
                    options.Arguments.Add(argument);
                });
            }
            options.EnvironmentVariables.Add(Constants.EnableNuGetPackageRestore, Boolean.TrueString.ToLower());

            if (_analyzerConfiguration.MetaDataSettings.GenerateBinFiles)
            {
                options.GlobalProperties.Add(MsBuildProperties.CopyBuildOutputToOutputDirectory, "true");
                options.GlobalProperties.Add(MsBuildProperties.CopyOutputSymbolsToOutputDirectory, "true");
                options.GlobalProperties.Add(MsBuildProperties.UseCommonOutputDirectory, "false");
                options.GlobalProperties.Add(MsBuildProperties.SkipCopyBuildProduct, "false");
                options.GlobalProperties.Add(MsBuildProperties.SkipCompilerExecution, "false");
                if (!requiresNetFramework)
                {
                    options.GlobalProperties.Add(MsBuildProperties.BuildProjectReferences, "true");
                }
            }
            return(options);
        }
Exemple #14
0
        public static string GetEnumDescription(this EnvironmentOptions value)
        {
            var description = value.GetType()
                              .GetMember(value.ToString())
                              .FirstOrDefault()
                              ?.GetCustomAttribute <DescriptionAttribute>()
                              ?.Description;

            return(description);
        }
        public void CompilesProject(EnvironmentPreference preference, string solutionPath, string projectPath)
        {
            // Given
            StringWriter    log     = new StringWriter();
            AnalyzerManager manager = new AnalyzerManager(solutionPath, new AnalyzerManagerOptions
            {
                LogWriter = log
            });
            ProjectAnalyzer    analyzer = manager.GetProject(projectPath);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // Set some enviornment variables to make it seem like we're not in a CI build
            // Sometimes this messes up libraries like SourceLink since we're building as part of a test and not for CI
            options.EnvironmentVariables.Add("APPVEYOR", "False");
            options.EnvironmentVariables.Add("ContinuousIntegrationBuild", null);
            options.EnvironmentVariables.Add("CI", "False");
            options.EnvironmentVariables.Add("CI_LINUX", "False");
            options.EnvironmentVariables.Add("CI_WINDOWS", "False");

            // When
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "obj");
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "bin");
            analyzer.IgnoreFaultyImports = false;

#pragma warning disable 0162
            if (BinaryLog)
            {
                analyzer.AddBinaryLogger($@"E:\Temp\{Path.GetFileNameWithoutExtension(solutionPath)}.{Path.GetFileNameWithoutExtension(analyzer.ProjectFile.Path)}.core.binlog");
            }
#pragma warning restore 0162

#if Is_Windows
            AnalyzerResults results = analyzer.Build(options);
#else
            // On non-Windows platforms we have to remove the .NET Framework target frameworks and only build .NET Core target frameworks
            // See https://github.com/dotnet/sdk/issues/826
            string[] excludedTargetFrameworks = new[] { "net2", "net3", "net4", "portable" };
            string[] targetFrameworks         = analyzer.ProjectFile.TargetFrameworks.Where(x => !excludedTargetFrameworks.Any(y => x.StartsWith(y))).ToArray();
            if (targetFrameworks.Length == 0)
            {
                Assert.Ignore();
            }
            AnalyzerResults results = analyzer.Build(targetFrameworks, options);
#endif

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.OverallSuccess.ShouldBeTrue(log.ToString());
            results.ShouldAllBe(x => x.Succeeded, log.ToString());
        }
Exemple #16
0
        public DefaultIssuerService(
            CertValidationOptions storeOptions,
            EnvironmentOptions environment,
            ILogger <DefaultIssuerService> logger
            )
        {
            _options = storeOptions;
            _logger  = logger;
            _path    = environment.ContentRoot;

            Load();
        }
Exemple #17
0
 public EnvironmentStatePollingSynchronizer(
     ILogger <EnvironmentStatePollingSynchronizer> logger,
     IEnvironmentStateProvider provider,
     IEnvironmentStateRepository repo,
     IOptions <EnvironmentStatePollingSynchronizerOptions> pollingOptions,
     IOptions <EnvironmentOptions> environmentOptions)
 {
     _logger             = logger;
     _provider           = provider;
     _repo               = repo;
     _pollingOptions     = pollingOptions.Value;
     _environmentOptions = environmentOptions.Value;
 }
 public VideoService(IUnitOfWork unitOfWork,
                     IdentityOptions identity,
                     IFileStorageService storage,
                     EnvironmentOptions env,
                     IMapper mapper,
                     ICommentService commentService)
 {
     _unitOfWork     = unitOfWork;
     _identity       = identity;
     _storage        = storage;
     _env            = env;
     _mapper         = mapper;
     _commentService = commentService;
 }
        public void GetsSourceFilesFromBinLogFile(string path, int expectedVersion)
        {
            // Verify this is the expected version
            path = Path.GetFullPath(
                Path.Combine(
                    Path.GetDirectoryName(typeof(SimpleProjectsFixture).Assembly.Location),
                    "..",
                    "..",
                    "..",
                    "..",
                    "binlogs",
                    path))
                   .Replace('\\', Path.DirectorySeparatorChar);
            EnvironmentOptions options = new EnvironmentOptions();

            using (Stream stream = File.OpenRead(path))
            {
                using (GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress))
                {
                    using (BinaryReader reader = new BinaryReader(gzip))
                    {
                        reader.ReadInt32().ShouldBe(expectedVersion);
                    }
                }
            }

            // Given
            StringWriter    log             = new StringWriter();
            AnalyzerManager analyzerManager = new AnalyzerManager(
                new AnalyzerManagerOptions
            {
                LogWriter = log
            });

            // When
            IAnalyzerResults       analyzerResults = analyzerManager.Analyze(path);
            IReadOnlyList <string> sourceFiles     = analyzerResults.First().SourceFiles;

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            new[]
            {
#if Is_Windows
                // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                "AssemblyAttributes",
#endif
                "Class1",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
        }
Exemple #20
0
        public void GetsSourceFilesFromVersion9BinLog()
        {
            // Given
            StringWriter     log      = new StringWriter();
            IProjectAnalyzer analyzer = GetProjectAnalyzer(
                @"SdkNetCore31Project\SdkNetCore31Project.csproj",
                log);
            string             binLogPath = Path.ChangeExtension(Path.GetTempFileName(), ".binlog");
            EnvironmentOptions options    = new EnvironmentOptions();

            options.Arguments.Add("/bl:" + binLogPath); // Tell MSBuild to produce the binlog so we use the latest internal logger

            try
            {
                // When
                analyzer.Build(options);
                using (Stream stream = File.OpenRead(binLogPath))
                {
                    using (GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress))
                    {
                        using (BinaryReader reader = new BinaryReader(gzip))
                        {
                            // Verify this produced a version 9 binlog
                            reader.ReadInt32().ShouldBe(9);
                        }
                    }
                }
                IReadOnlyList <string> sourceFiles = analyzer.Manager.Analyze(binLogPath).First().SourceFiles;

                // Then
                sourceFiles.ShouldNotBeNull(log.ToString());
                new[]
                {
#if Is_Windows
                    // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                    "AssemblyAttributes",
#endif
                    "Class1",
                    "AssemblyInfo"
                }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
            }
            finally
            {
                if (File.Exists(binLogPath))
                {
                    File.Delete(binLogPath);
                }
            }
        }
Exemple #21
0
        private HttpClient CreateUpmClient(IConfiguration configuration)
        {
            var envOptions = new EnvironmentOptions();

            configuration.GetSection("dimensionData:environment").Bind(envOptions);
            IServiceDiscoveryClient serviceDiscoveryClient = new ServiceDiscoveryClient(Options.Create(envOptions));

            string upmKey      = Configuration["dimensionData:ui:keys:upm"];
            var    baseAddress = serviceDiscoveryClient.FindGlobalApiService(upmKey).Result;

            return(new HttpClientBuilder()
                   .SetBaseAddress(baseAddress)
                   .SetRetryPolicy(3, TimeSpan.FromSeconds(1), 2)
                   .Build());
        }
Exemple #22
0
        /// <summary>
        /// Builds all target framework(s) with the specified build environment options.
        /// </summary>
        /// <param name="environmentOptions">The environment options to use for the build.</param>
        /// <returns>A dictionary of target frameworks to <see cref="AnalyzerResult"/>.</returns>
        public AnalyzerResults BuildAllTargetFrameworks(EnvironmentOptions environmentOptions)
        {
            if (environmentOptions == null)
            {
                throw new ArgumentNullException(nameof(environmentOptions));
            }

            // Load the project with the default build environment to get the evaluated target frameworks
            Project project = Load(EnvironmentFactory.GetBuildEnvironment(environmentOptions));

            // Get all evaluated target frameworks from the Project and build them
            // but don't worry about getting a single target framework, it'll build the default
            string[] targetFrameworks = ProjectFile.GetTargetFrameworks(
                new[] { project.GetPropertyValue(ProjectFileNames.TargetFrameworks) }, null, null);

            return(Build(targetFrameworks, environmentOptions));
        }
Exemple #23
0
        public static AdhocWorkspace GetWorkspace(this AnalyzerManager manager, EnvironmentOptions envOptions)
        {
            // Run builds in parallel
            List <AnalyzerResult> results = manager.Projects.Values
                                            .AsParallel()
                                            .Select(p => p.Build(envOptions).FirstOrDefault()) // with envoption
                                            .Where(x => x != null)
                                            .ToList();

            // Add each result to a new workspace
            AdhocWorkspace workspace = new AdhocWorkspace();

            foreach (AnalyzerResult result in results)
            {
                result.AddToWorkspace(workspace);
            }
            return(workspace);
        }
Exemple #24
0
        public NeuroGeneticAlgorithm(IFittnessFunction <Neuron> fittnessFunction, ISelection <Neuron> selection,
                                     ICrossover <Neuron> crossover, IMutation <Neuron> mutation,
                                     ITerminate <Neuron> terminate, NeuralNetwork networkForTeach)
            : base(fittnessFunction, selection, crossover, mutation, terminate)
        {
            NeuralNetwork = networkForTeach;
            Random        = new Random((int)DateTime.Now.Ticks);
            generateNeuroPopulation_();

            var options = new EnvironmentOptions
            {
                AgentsCount = Population.Count,
                FoodCount   = 5,
                FieldWidth  = 200,
                FieldHeight = 200
            };

            TestGameEnvironment = new GameEnvironment(options);
        }
        private EnvironmentOptions GetEnvironmentOptions(IProjectFile projectFile)
        {
            var os = DetermineOSPlatform();
            EnvironmentOptions options = new EnvironmentOptions();

            if (os == OSPlatform.Linux || os == OSPlatform.OSX)
            {
                var requiresNetFramework = false;

                /*
                 *  We need to have this property in a try/catch because there are cases when there are additional Import or LanguageTarget tags
                 *  with unexpected (or missing) attributes. This avoids a NPE in buildalyzer code retrieving this property
                 */
                try
                {
                    requiresNetFramework = projectFile.RequiresNetFramework;
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Error while checking if project is a framework project");
                }
                if (requiresNetFramework)
                {
                    options.EnvironmentVariables.Add(EnvironmentVariables.MSBUILD_EXE_PATH, Constants.MsBuildCommandName);
                }
            }

            options.EnvironmentVariables.Add(Constants.EnableNuGetPackageRestore, Boolean.TrueString.ToLower());

            options.Arguments.Add(Constants.RestorePackagesConfigArgument);
            options.Arguments.Add(Constants.LanguageVersionArgument);

            if (_analyzerConfiguration.MetaDataSettings.GenerateBinFiles)
            {
                options.GlobalProperties.Add(MsBuildProperties.CopyBuildOutputToOutputDirectory, "true");
                options.GlobalProperties.Add(MsBuildProperties.CopyOutputSymbolsToOutputDirectory, "true");
                options.GlobalProperties.Add(MsBuildProperties.UseCommonOutputDirectory, "false");
                options.GlobalProperties.Add(MsBuildProperties.SkipCopyBuildProduct, "false");
                options.GlobalProperties.Add(MsBuildProperties.SkipCompilerExecution, "false");
            }

            return(options);
        }
Exemple #26
0
        public void BuildsProject(string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                DesignTime = false
            };

            // When
            DeleteProjectDirectory(projectFile, "obj");
            DeleteProjectDirectory(projectFile, "bin");
            AnalyzerResults results = analyzer.BuildAllTargetFrameworks(options);

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.First().ProjectInstance.ShouldNotBeNull(log.ToString());
        }
        public void GetsSourceFilesFromBinaryLog(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            IProjectAnalyzer   analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };
            string binLogPath = Path.ChangeExtension(Path.GetTempFileName(), ".binlog");

            analyzer.AddBinaryLogger(binLogPath);

            try
            {
                // When
                analyzer.Build(options);
                IAnalyzerResults results = analyzer.Manager.Analyze(binLogPath);

                // Then
                // If this is the multi-targeted project, use the net462 target
                IReadOnlyList <string> sourceFiles = results.Count == 1 ? results.First().SourceFiles : results["net462"].SourceFiles;
                sourceFiles.ShouldNotBeNull(log.ToString());
                new[]
                {
#if Is_Windows
                    // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                    "AssemblyAttributes",
#endif
                    "Class1",
                    "AssemblyInfo"
                }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
            }
            finally
            {
                if (File.Exists(binLogPath))
                {
                    File.Delete(binLogPath);
                }
            }
        }
        public void GetsProjectGuidFromSolution([ValueSource(nameof(Preferences))] EnvironmentPreference preference)
        {
            // Given
            AnalyzerManager manager = new AnalyzerManager(
                GetProjectPath("TestProjects.sln"));
            IProjectAnalyzer   analyzer = manager.Projects.First(x => x.Key.EndsWith("SdkNetStandardProject.csproj")).Value;
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "obj");
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "bin");
            IAnalyzerResults results = analyzer.Build(options);

            // Then
            results.First().ProjectGuid.ToString().ShouldBe("016713d9-b665-4272-9980-148801a9b88f");
        }
        public IEnumerable <string> EnumerateProjectFilesRelative(string projectPath)
        {
            // Use an environment variable to try to prevent recursively calling this
            // build target when we call .Build below
            const string EnvVar = "_DRWLA_ARM_BUILD";

            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvVar)))
            {
                yield break;
            }
            var manager            = new AnalyzerManager();
            var analyzer           = manager.GetProject(projectPath);
            var environmentOptions = new EnvironmentOptions
            {
                // MUST USE DESIGN TIME BUILD
                // In the .targets definition we have a condition
                // to avoid running the DurwellaAzureArmTestingTarget at Design Time
                // https://github.com/dotnet/project-system/blob/master/docs/design-time-builds.md
                DesignTime           = true,
                EnvironmentVariables = { { EnvVar, "RUNNING" } }
            };
            var results = analyzer.Build(environmentOptions);
            // Returns one result per framework target
            var result = results.First();
            var items  = result.Items;

            foreach (var item in items)
            {
                // Skip keys like ProjectReference that aren't for files
                if (!InlcudedProjectKeys.Contains(item.Key))
                {
                    continue;
                }
                var projectItems = item.Value;
                foreach (var projectItem in projectItems)
                {
                    // The item spec for files will be the path relative to the project directory
                    yield return(projectItem.ItemSpec);
                }
            }
        }
Exemple #30
0
        public void DesignTimeBuildsProject(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            DeleteProjectDirectory(projectFile, "obj");
            DeleteProjectDirectory(projectFile, "bin");
            AnalyzerResults results = analyzer.Build(options);

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.ShouldAllBe(x => x.OverallSuccess, log.ToString());
        }