private void FindProjectsClassic(XmlNode node)
        {
            XmlNode lstProjectNode = null;

            foreach (XmlNode aNode in node.ChildNodes)
            {
                lstProjectNode = FindParentNode(aNode, "ProjectReference");

                if (lstProjectNode != null)
                {
                    break;
                }
            }

            if (lstProjectNode != null)
            {
                foreach (XmlNode aProject in lstProjectNode.ChildNodes)
                {
                    var projectId   = aProject.ChildNodes[0].InnerText;
                    var projectName = aProject.ChildNodes[1].InnerText;

                    ProjectReferences.Add(new ProjectReference()
                    {
                        Type = ProjectType.Classic,
                        Id   = projectId,
                        Name = projectName,
                    });
                }
            }
        }
        protected void GenerateViews(IDictionary <string, object> templateParameters)
        {
            string[] viewNames = new string[] { MvcViewTemplates.Create, MvcViewTemplates.Delete, MvcViewTemplates.Details, MvcViewTemplates.Edit, "List" };
            if (templateParameters == null)
            {
                throw new ArgumentNullException("templateParameters");
            }

            templateParameters["LayoutPageFile"]           = base.Model.LayoutPageFile ?? string.Empty;
            templateParameters["IsPartialView"]            = base.Model.IsPartialViewSelected;
            templateParameters["IsLayoutPageSelected"]     = base.Model.IsLayoutPageSelected;
            templateParameters["ReferenceScriptLibraries"] = base.Model.IsReferenceScriptLibrariesSelected;
            templateParameters["JQueryVersion"]            = string.Empty;
            templateParameters["MvcVersion"] = ProjectReferences.GetAssemblyVersion(base.Context.ActiveProject, AssemblyVersions.MvcAssemblyName);

            if (base.Model.ModelType == null)
            {
                templateParameters["ViewDataTypeName"] = string.Empty;
            }
            else
            {
                CodeType codeType = base.Model.ModelType.CodeType;
                templateParameters["ViewDataTypeName"]      = codeType.FullName;
                templateParameters["ViewDataTypeShortName"] = codeType.Name;
                templateParameters["ViewDataType"]          = codeType;
            }

            foreach (var viewName in viewNames)
            {
                templateParameters["ViewName"] = viewName;
                string viewFileName = viewName == "List" ? "Index" : viewName;
                string outputFolder = Path.Combine(Model.AreaRelativePath, "Views", Model.ControllerRootName, viewFileName);
                AddFileFromTemplate(Context.ActiveProject, outputFolder, viewName, templateParameters, true);
            }
        }
示例#3
0
 public void Reload()
 {
     References.Clear();
     ProjectReferences.Clear();
     BuildConfigurations.Clear();
     _parse();
 }
示例#4
0
        public override bool Execute()
        {
            // Log inputs
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            log.LogDebug($"(in) TargetFrameworks '{TargetFrameworks}'");
            log.LogDebug($"(in) ProjectReferences '{string.Join(";", ProjectReferences.Select(p => p.ItemSpec))}'");
            log.LogDebug($"(in) ParentProjectPath '{ParentProjectPath}'");

            var entries = new List <ITaskItem>();

            // Filter obvious duplicates without considering OS case sensitivity.
            // This will be filtered further when creating the spec.
            var seen = new HashSet <string>(StringComparer.Ordinal);

            var parentDirectory = Path.GetDirectoryName(ParentProjectPath);

            foreach (var project in ProjectReferences)
            {
                var refOutput = BuildTasksUtility.GetPropertyIfExists(project, "ReferenceOutputAssembly");

                // Match the same behavior as NuGet.targets
                // ReferenceOutputAssembly == '' OR ReferenceOutputAssembly == 'true'
                if (string.IsNullOrEmpty(refOutput) ||
                    Boolean.TrueString.Equals(refOutput, StringComparison.OrdinalIgnoreCase))
                {
                    // Get the absolute path
                    var referencePath = Path.GetFullPath(Path.Combine(parentDirectory, project.ItemSpec));

                    if (!seen.Add(referencePath))
                    {
                        // Skip already processed projects
                        continue;
                    }

                    var properties = new Dictionary <string, string>();
                    properties.Add("ProjectUniqueName", ProjectUniqueName);
                    properties.Add("Type", "ProjectReference");
                    properties.Add("ProjectPath", referencePath);
                    properties.Add("ProjectReferenceUniqueName", referencePath);

                    if (!string.IsNullOrEmpty(TargetFrameworks))
                    {
                        properties.Add("TargetFrameworks", TargetFrameworks);
                    }

                    BuildTasksUtility.CopyPropertyIfExists(project, properties, "IncludeAssets");
                    BuildTasksUtility.CopyPropertyIfExists(project, properties, "ExcludeAssets");
                    BuildTasksUtility.CopyPropertyIfExists(project, properties, "PrivateAssets");

                    entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties));
                }
            }

            RestoreGraphItems = entries.ToArray();

            return(true);
        }
 public SimpleTestProjectFrameworkContext(
     NuGetFramework framework,
     IEnumerable <SimpleTestPackageContext> packageReferences,
     IEnumerable <SimpleTestProjectContext> projectReferences)
 {
     Framework = framework;
     PackageReferences.AddRange(packageReferences);
     ProjectReferences.AddRange(projectReferences);
 }
示例#6
0
 public SimpleTestProjectFrameworkContext(
     NuGetFramework framework,
     IEnumerable <SimpleTestPackageContext> packageReferences,
     IEnumerable <SimpleTestProjectContext> projectReferences)
 {
     Framework = framework;
     PackageReferences.AddRange(packageReferences);
     ProjectReferences.AddRange(projectReferences);
     TargetAlias = framework.GetShortFolderName();
 }
示例#7
0
        public override bool IsDependencyInstalled(CodeGenerationContext context)
        {
            bool flag = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.ODataAssemblyName);

            context.Items.AddProperty("MVC_IsODataAssemblyReferenced", flag);
            if (base.IsDependencyInstalled(context))
            {
                return(flag);
            }
            return(false);
        }
        public void assemblies_referencing_bin_obj_with_approved_exceptions()
        {
            projectProvider
            .LoadProjectDocument()
            .Returns(XDocument.Parse(Resources.ProjectFileWithBinReference));

            var project  = new ProjectReferences(projectProvider);
            var failures = Convention.GetFailures(new ProjectDoesNotReferenceDllsFromBinOrObjDirectories(), project);

            failures.ShouldMatchApproved();
        }
示例#9
0
        public virtual bool IsDependencyInstalled(CodeGenerationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            bool flag = ProjectReferences.IsAssemblyReferenced(context.ActiveProject, AssemblyVersions.WebApiAssemblyName);

            context.Items.AddProperty("MVC_IsWebApiAssemblyReferenced", flag);
            return(flag);
        }
        public override bool Execute()
        {
            var projectrefs = ProjectReferences?.Select(p => Path.GetDirectoryName(p.GetMetadata("MSBuildSourceProjectFile"))).ToList() ?? new List <string>();
            var baseDir     = Path.GetDirectoryName(BasePath);
            var srv         = FabricSerializers.ServiceManifestFromFile(Path.Combine(baseDir, "PackageRoot", "ServiceManifest.xml"));
            var ver         = srv.SetGitVersion(UpdateBaseVersion ? BaseVersion : srv.Version, baseDir, TargetDir, CheckIndividualPackages, projectrefs, MaxHashLength, SkipHash);

            File.WriteAllText(Path.Combine(baseDir, "pkg", Configuration, "Version.txt"), ver.version + " " + ver.date.Ticks);
            File.WriteAllText(Path.Combine(baseDir, "pkg", Configuration, "Diff.txt"), ver.diff);
            FabricSerializers.SaveServiceManifest(Path.Combine(baseDir, "pkg", Configuration, "ServiceManifest.xml"), srv);
            return(true);
        }
示例#11
0
        public override string ToString()
        {
            var result = new StringBuilder("[" + GetType().FullName + "]\n");

            result.AppendLine("ProjectFile: " + ProjectFile);
            result.AppendLine("ProjectRoot: " + ProjectRoot);
            result.AppendLine("ParseResult: " + ParseResult);
            result.AppendLine("TargetFrameworkVersion: " + TargetFrameworkVersion);
            result.AppendLine("Platform: " + Platform);
            result.AppendLine("PlatformTarget: " + PlatformTarget);
            result.AppendLine("OutputPathProjectFile: " + OutputPath);
            result.AppendLine("AssemblyName: " + AssemblyName);
            result.AppendLine("Valid: " + GetValidationMessage());
            result.AppendLine("CompileItems: " + CompileItems.Count);

            result.AppendLine("ProjectReferences: ");
            if (ProjectReferences != null)
            {
                foreach (var item in ProjectReferences.OrderBy(x => x))
                {
                    result.AppendLine("    " + item);
                }
            }

            if (DllReferences != null)
            {
                result.AppendLine("DllReferences: ");
                foreach (var item in DllReferences.OrderBy(x => x.Assembly))
                {
                    if (item.Assembly.ToUpper().StartsWith("FILMTRACK"))
                    {
                        result.AppendLine("*   " + item);
                    }
                    else
                    {
                        //result.AppendLine("    " + item);
                        result.Append(Indent.IndentString(item.ToString(), 4));
                    }
                }
            }

            //result.AppendLine("CompileItems: ");
            //foreach (var item in CompileItems)
            //{
            //    result.AppendLine("    " + item);
            //}

            //result.AppendLine("Items: ");
            //result.AppendLine(Items);
            //result.AppendLine("");

            return(result.ToString());
        }
示例#12
0
        public virtual void RemoveProjectReference(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            var remove = ProjectReferences.FirstOrDefault(e => e.GetInclude().EqualsIgnoreCase(filePath));

            if (remove != null)
            {
                remove.ParentNode.RemoveChild(remove);
            }
        }
示例#13
0
        /// <summary>
        /// Get a project reference with a specified id
        /// </summary>
        ///
        /// <exception cref="ArgumentException">
        /// No project with specified <paramref name="id"/> in solution
        /// </exception>
        ///
        public VisualStudioSolutionProjectReference GetProjectReference(string id)
        {
            Guard.NotNull(id, nameof(id));

            var project = ProjectReferences.SingleOrDefault(p => p.Id == id);

            if (project == null)
            {
                throw new ArgumentException(
                          StringExtensions.FormatInvariant("No project with Id {0} in solution", id),
                          "id");
            }

            return(project);
        }
        private void FindProjectsSdk(XmlNode node)
        {
            XmlNode lstProjectNode = null;

            foreach (XmlNode aNode in node.ChildNodes)
            {
                lstProjectNode = FindParentNode(aNode, "ProjectReference");

                if (lstProjectNode != null)
                {
                    break;
                }
            }

            if (lstProjectNode != null)
            {
                foreach (XmlNode aProject in lstProjectNode.ChildNodes)
                {
                    var link = aProject.Attributes["Include"];

                    if (link != null)
                    {
                        var projLink = link.InnerText;

                        var basePath = System.IO.Path.GetDirectoryName(_path);

                        var projPath = Path.Combine(basePath, projLink);

                        var fileInfo = new FileInfo(projPath);

                        var path = fileInfo.FullName;

                        var name = Path.GetFileNameWithoutExtension(path);

                        ProjectReferences.Add(new ProjectReference()
                        {
                            Type     = ProjectType.SDK,
                            FullPath = path,
                            Name     = name,
                        });
                    }
                }
            }
        }
示例#15
0
        public EmitResult CompileAssembly(string assemblyName, IEnumerable <string> csFiles, Stream stream, Stream streamForPdb)
        {
            var syntaxTrees = new List <SyntaxTree>();

            foreach (var csFile in csFiles)
            {
                var source     = File.ReadAllText(csFile);
                var syntaxTree = SyntaxFactory.ParseSyntaxTree(source, ParseOptions, csFile, System.Text.Encoding.UTF8);
                syntaxTrees.Add(syntaxTree);
            }
            var references         = ProjectReferences.Select(referencePath => MetadataReference.CreateFromFile(referencePath));
            var compilationOptions = new CSharpCompilationOptions(OutputKind)
                                     .WithOverflowChecks(true)
                                     .WithOptimizationLevel(OptimizationLevel)
                                     .WithUsings(Namespaces);
            var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, references, compilationOptions);

            return(compilation.Emit(stream, streamForPdb));
        }
示例#16
0
        public CompilerResults Compile()
        {
            var csc = new CSharpCodeProvider(
                new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            });

            var referencedAssemblies =
                AssemblyReferences
                .Union(ProjectReferences.Select(p => p.Compile().PathToAssembly))
                .ToArray();

            var parameters = new CompilerParameters(
                referencedAssemblies);

            return(csc.CompileAssemblyFromSource(
                       parameters,
                       MockSourceFiles.Select(x => x.RenderFile()).ToArray()));
        }
示例#17
0
 public override bool Execute()
 {
     try
     {
         var buildSnapshot = new BuildSnapshot(ProjectReferences.Select(projectReference => projectReference.GetMetadata("FullPath")).ToList(), FilesToCompile);
         buildSnapshot.ProjectConfigProperties[DictionaryTags.EnableUnitTesting]     = false;
         buildSnapshot.ProjectConfigProperties[DictionaryTags.TreatWarningsAsErrors] = false;
         buildSnapshot.ProjectConfigProperties[DictionaryTags.WarningLevel]          = WarningLevel;
         return(Compile(buildSnapshot));
     }
     catch (Exception exception)
     {
         if (exception.IsFatal())
         {
             throw;
         }
         Log.LogErrorFromException(exception, true, true, null);
         return(false);
     }
 }
示例#18
0
        public override bool Execute()
        {
            // Log inputs
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectReferences '{string.Join(";", ProjectReferences.Select(p => p.ItemSpec))}'");
            log.LogDebug($"(in) SolutionFilePath '{SolutionFilePath}'");

            var entries         = new List <ITaskItem>();
            var parentDirectory = Path.GetDirectoryName(SolutionFilePath);

            foreach (var project in ProjectReferences)
            {
                if (string.IsNullOrEmpty(project.ItemSpec))
                {
                    continue;
                }

                var projectPath = Path.GetFullPath(Path.Combine(parentDirectory, project.ItemSpec));

                // Check for the metaproj extension, this is auto generated by solutions instead of
                // the actual project path when build order is set. For the purpose of restore
                // the order is not important so we remove the extension to get the real project path.
                if (projectPath.EndsWith(MetaProjExtension, StringComparison.OrdinalIgnoreCase))
                {
                    // Remove .metaproj from the path.
                    projectPath = projectPath.Substring(0, projectPath.Length - MetaProjExtension.Length);
                }

                // Clone items using the modified path
                var newEntry = new TaskItem(projectPath, project.CloneCustomMetadata());
                entries.Add(newEntry);
            }

            OutputProjectReferences = entries.ToArray();

            return(true);
        }
示例#19
0
        public string RenderFile()
        {
            return(string.Format(
                       @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <Project ToolsVersion=""12.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
                      <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
                      <PropertyGroup>
                        <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>
                        <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>
                        <ProjectGuid>{0}</ProjectGuid>
                        <OutputType>Library</OutputType>
                        <AppDesignerFolder>Properties</AppDesignerFolder>
                        <RootNamespace>{1}</RootNamespace>
                        <AssemblyName>{1}</AssemblyName>
                        <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
                        <FileAlignment>512</FileAlignment>
                        <DesignTimeBuild>true</DesignTimeBuild>
                      </PropertyGroup>
                      <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">
                        <PlatformTarget>AnyCPU</PlatformTarget>
                        <DebugSymbols>true</DebugSymbols>
                        <DebugType>full</DebugType>
                        <Optimize>false</Optimize>
                        <OutputPath>bin\Debug\</OutputPath>
                        <DefineConstants>DEBUG;TRACE</DefineConstants>
                        <ErrorReport>prompt</ErrorReport>
                        <WarningLevel>4</WarningLevel>
                      </PropertyGroup>
                      <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">
                        <PlatformTarget>AnyCPU</PlatformTarget>
                        <DebugType>pdbonly</DebugType>
                        <Optimize>true</Optimize>
                        <OutputPath>bin\Release\</OutputPath>
                        <DefineConstants>TRACE</DefineConstants>
                        <ErrorReport>prompt</ErrorReport>
                        <WarningLevel>4</WarningLevel>
                      </PropertyGroup>
                      <PropertyGroup>
                        <StartupObject />
                      </PropertyGroup>
                      <ItemGroup>
                        {2}
                        <Reference Include=""System"" />
                      </ItemGroup>
                      <ItemGroup>
                        {3}
                      </ItemGroup>
                      <ItemGroup>
                        {4}
                      </ItemGroup>
                      <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
                      <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
                           Other similar extension points exist, see Microsoft.Common.targets.
                      <Target Name=""BeforeBuild"">
                      </Target>
                      <Target Name=""AfterBuild"">
                      </Target>
                      -->
                    </Project>",
                       Guid,
                       Title,

                       //AssemblyReferences
                       string.Join(
                           Environment.NewLine,
                           AssemblyReferences.Select(
                               r =>
                               string.Format(
                                   @"<Reference Include=""{0}"">
                                    <HintPath>{1}</HintPath>
                                  </Reference>",
                                   Path.GetFileNameWithoutExtension(r),
                                   r)
                               )),

                       //Files
                       string.Join(
                           Environment.NewLine,
                           MockSourceFiles.Select(
                               f =>
                               string.Format(
                                   @"<Compile Include=""{0}"" />",
                                   f.FileName)
                               )),

                       //ProjectReferences
                       string.Join(
                           Environment.NewLine,
                           ProjectReferences.Select(
                               p =>
                               string.Format(
                                   @"<ProjectReference Include=""{0}"">
                                      <Project>{1}</Project>
                                      <Name>{2}</Name>
                                    </ProjectReference>",
                                   p.FileName,
                                   p.Guid,
                                   Path.GetFileNameWithoutExtension(p.FileName.FullPath))
                               ))));
        }
示例#20
0
        private async Task <ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken))
            {
                // Here, we use the _documentStates and _additionalDocumentStates and visit them in order; we ensure that those are
                // sorted by ID so we have a consistent sort.
                var documentChecksumsTasks          = _documentStates.Select(pair => pair.Value.GetChecksumAsync(cancellationToken));
                var additionalDocumentChecksumTasks = _additionalDocumentStates.Select(pair => pair.Value.GetChecksumAsync(cancellationToken));

                var serializer = _solutionServices.Workspace.Services.GetService <ISerializerService>();

                var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken);

                // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed.
                var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null;
                var parseOptionsChecksum       = SupportsCompilation ? ChecksumCache.GetOrCreate(ParseOptions, _ => serializer.CreateChecksum(ParseOptions, cancellationToken)) : Checksum.Null;

                var projectReferenceChecksums  = ChecksumCache.GetOrCreate <ProjectReferenceChecksumCollection>(ProjectReferences, _ => new ProjectReferenceChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
                var metadataReferenceChecksums = ChecksumCache.GetOrCreate <MetadataReferenceChecksumCollection>(MetadataReferences, _ => new MetadataReferenceChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
                var analyzerReferenceChecksums = ChecksumCache.GetOrCreate <AnalyzerReferenceChecksumCollection>(AnalyzerReferences, _ => new AnalyzerReferenceChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));

                var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false);

                var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false);

                return(new ProjectStateChecksums(
                           infoChecksum,
                           compilationOptionsChecksum,
                           parseOptionsChecksum,
                           new DocumentChecksumCollection(documentChecksums),
                           projectReferenceChecksums,
                           metadataReferenceChecksums,
                           analyzerReferenceChecksums,
                           new TextDocumentChecksumCollection(additionalChecksums)));
            }
        }
        /// <summary>
        /// Main task method
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            try
            {
                if (!VerifyProjectReferenceItems(ProjectReferences, true /* treat problems as errors */))
                {
                    return(false);
                }

                ArrayList resolvedReferences   = new ArrayList(ProjectReferences.GetLength(0));
                ArrayList unresolvedReferences = new ArrayList(ProjectReferences.GetLength(0));

                if (!String.IsNullOrEmpty(SolutionConfigurationContents))
                {
                    CacheProjectElementsFromXml(SolutionConfigurationContents);
                }

                if (AddSyntheticProjectReferencesForSolutionDependencies)
                {
                    // The solution may have had project to project dependencies expressed in it, which were passed in with the blob.
                    // Add those to the list of project references as if they were regular project references.
                    AddSyntheticProjectReferences(CurrentProject);
                }

                foreach (ITaskItem projectRef in ProjectReferences)
                {
                    bool      resolveSuccess = false;
                    ITaskItem resolvedReference;

                    resolveSuccess = ResolveProject(projectRef, out resolvedReference);

                    if (resolveSuccess)
                    {
                        resolvedReferences.Add(resolvedReference);

                        Log.LogMessageFromResources(MessageImportance.Low, "AssignProjectConfiguration.ProjectConfigurationResolutionSuccess", projectRef.ItemSpec, resolvedReference.GetMetadata(attrFullConfiguration));
                    }
                    else
                    {
                        // If the reference was unresolved, we want to undefine the Configuration and Platform
                        // global properties, so that the project will build using its default Configuration and
                        // Platform rather than that of its parent.
                        if (ShouldUnsetParentConfigurationAndPlatform)
                        {
                            string globalPropertiesToRemove = projectRef.GetMetadata("GlobalPropertiesToRemove");

                            if (!String.IsNullOrEmpty(globalPropertiesToRemove))
                            {
                                globalPropertiesToRemove += ";";
                            }

                            if (projectRef is ITaskItem2)
                            {
                                ((ITaskItem2)projectRef).SetMetadataValueLiteral("GlobalPropertiesToRemove", globalPropertiesToRemove + "Configuration;Platform");
                            }
                            else
                            {
                                projectRef.SetMetadata("GlobalPropertiesToRemove", EscapingUtilities.Escape(globalPropertiesToRemove + "Configuration;Platform"));
                            }
                        }

                        unresolvedReferences.Add(projectRef);

                        // This is not an error - we pass unresolved references to UnresolvedProjectReferences for further
                        // processing in the .targets file. This means this project was not checked for building in the
                        // active solution configuration.
                        Log.LogMessageFromResources(MessageImportance.Low, "AssignProjectConfiguration.ProjectConfigurationUnresolved", projectRef.ItemSpec);
                    }
                }

                AssignedProjects   = (ITaskItem[])resolvedReferences.ToArray(typeof(ITaskItem));
                UnassignedProjects = (ITaskItem[])unresolvedReferences.ToArray(typeof(ITaskItem));
            }
            catch (XmlException e)
            {
                Log.LogErrorWithCodeFromResources("General.ErrorExecutingTask", this.GetType().Name, e.Message);
                return(false);
            }

            return(true);
        }
示例#22
0
 public bool IsReferencing(Project project)
 {
     return(References.Where(r => r.Name == project.Name).Any() ||
            ProjectReferences.Where(pr => pr.ProjectName == project.Name).Any());
 }
示例#23
0
            private string GetProjectContent()
            {
                if (Language == LanguageNames.VisualBasic)
                {
                    throw new NotImplementedException("Need VB support");
                }

                if (Guid == Guid.Empty)
                {
                    Guid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(OutputType))
                {
                    OutputType = "Library";
                }

                if (string.IsNullOrEmpty(OutputPath))
                {
                    OutputPath = ".";
                }

                var document      = XDocument.Parse(CSharpProjectTemplate);
                var propertyGroup = document.Root.Descendants(XName.Get("PropertyGroup", NS)).First();

                AddXElement(propertyGroup, "ProjectGuid", Guid.ToString("B"));
                AddXElement(propertyGroup, "OutputType", OutputType);
                AddXElement(propertyGroup, "OutputPath", OutputPath);
                AddXElement(propertyGroup, "AssemblyName", Name);

                if (Properties != null)
                {
                    foreach (var property in Properties)
                    {
                        AddXElement(propertyGroup, property.Name, property.Value);
                    }
                }

                var importTargets = document.Root.Elements().Last();

                if (ProjectReferences != null && ProjectReferences.Any())
                {
                    AddItemGroup(
                        importTargets,
                        _ => "ProjectReference",
                        ProjectReferences,
                        i => i.ProjectFileName,
                        (projectReference, xmlElement) =>
                    {
                        if (projectReference.Guid != Guid.Empty)
                        {
                            AddXElement(xmlElement, "Project", projectReference.Guid.ToString("B"));
                        }

                        AddXElement(xmlElement, "Name", Path.GetFileNameWithoutExtension(projectReference.ProjectName));
                    });
                }

                if (Documents != null)
                {
                    AddItemGroup(
                        importTargets,
                        i => i.ItemType,
                        Documents,
                        i => i.FilePath);
                }

                return(document.ToString());
            }
示例#24
0
        private ProjectCollection LoadProjectsAndReferences(IDictionary <string, string> globalProperties)
        {
            // Create an MSBuildProject loader with the same global properties of the project that requested a solution file
            MSBuildProjectLoader projectLoader = new MSBuildProjectLoader(globalProperties, ToolsVersion, BuildEngine, ProjectLoadSettings.IgnoreMissingImports)
            {
                CollectStats = CollectStats
            };

            LogMessageHigh("Loading project references...");

            ProjectCollection projectCollection = projectLoader.LoadProjectsAndReferences(ProjectReferences.Select(i => i.GetMetadata("FullPath")).Concat(new[] { ProjectFullPath }));

            LogMessageNormal($"Loaded {projectCollection.LoadedProjects.Count} project(s)");

            if (CollectStats)
            {
                LogStatistics(projectLoader);
            }

            return(projectCollection);
        }
 /// <summary>
 /// Given the name of a server project file known to be the destination of a RIA Link,
 /// this method returns all the client projects that have a RIA Link to it.
 /// </summary>
 /// <remarks>
 /// Generally there is only one client file in a solution pointing to any given server
 /// project via a RIA link, but we use a collection because it is possible to have many.
 /// </remarks>
 /// <param name="linkedServerProject">Full path to server project file known to be the destination of a RIA Link</param>
 /// <returns>The set of all client project paths that have a RIA link to <paramref name="linkedServerProject"/></returns>
 internal IEnumerable <string> GetLinkedServerProjectSources(string linkedServerProject)
 {
     return(ProjectReferences.Where(s => String.Equals(linkedServerProject, this[s], StringComparison.OrdinalIgnoreCase)));
 }
示例#26
0
        /// <summary>
        /// Main task method
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            // Allow unit tests to inject a non-file system dependent version of this.
            if (GetAssemblyName == null)
            {
                GetAssemblyName = AssemblyName.GetAssemblyName;
            }

            try
            {
                if (!VerifyProjectReferenceItems(ProjectReferences, false /* treat problems as warnings */))
                {
                    return(false);
                }

                ArrayList resolvedPaths        = new ArrayList(ProjectReferences.GetLength(0));
                ArrayList unresolvedReferences = new ArrayList(ProjectReferences.GetLength(0));

                CacheProjectElementsFromXml(PreresolvedProjectOutputs);

                foreach (ITaskItem projectRef in ProjectReferences)
                {
                    bool      resolveSuccess = false;
                    ITaskItem resolvedPath;

                    Log.LogMessageFromResources(MessageImportance.Low, "ResolveNonMSBuildProjectOutput.ProjectReferenceResolutionStarting", projectRef.ItemSpec);

                    resolveSuccess = ResolveProject(projectRef, out resolvedPath);

                    if (resolveSuccess)
                    {
                        if (resolvedPath.ItemSpec.Length > 0)
                        {
                            // VC project system does not look like an MSBuild project type yet because VC do not
                            // yet implement IVSProjectBuildSystem.  So project references to VC managed libraries
                            // need to be recognized as such.
                            // Even after VC implements this IVSProjectBuildSystem, other project types (NMake, NAnt, etc.)
                            // still can generate managed assemblies, in which case we still need to perform this managed
                            // assembly check.
                            try
                            {
                                GetAssemblyName(resolvedPath.ItemSpec);
                                resolvedPath.SetMetadata("ManagedAssembly", "true");
                            }
                            catch (BadImageFormatException)
                            {
                            }

                            resolvedPaths.Add(resolvedPath);

                            Log.LogMessageFromResources(MessageImportance.Low, "ResolveNonMSBuildProjectOutput.ProjectReferenceResolutionSuccess", projectRef.ItemSpec, resolvedPath.ItemSpec);
                        }
                        // If resolved path is empty, log a warning. This means that this reference is not an MSBuild reference,
                        // but could not be resolved in the IDE.
                        else
                        {
                            Log.LogWarningWithCodeFromResources("ResolveNonMSBuildProjectOutput.ProjectReferenceResolutionFailure", projectRef.ItemSpec);
                        }
                    }
                    else
                    {
                        unresolvedReferences.Add(projectRef);

                        // This is not an error - we pass unresolved references to UnresolvedProjectReferences for further
                        // processing in the .targets file.
                        Log.LogMessageFromResources(MessageImportance.Low, "ResolveNonMSBuildProjectOutput.ProjectReferenceUnresolved", projectRef.ItemSpec);
                    }
                }

                ResolvedOutputPaths         = (ITaskItem[])resolvedPaths.ToArray(typeof(ITaskItem));
                UnresolvedProjectReferences = (ITaskItem[])unresolvedReferences.ToArray(typeof(ITaskItem));
            }
            catch (XmlException e)
            {
                Log.LogErrorWithCodeFromResources("General.ErrorExecutingTask", this.GetType().Name, e.Message);
                return(false);
            }

            return(true);
        }
示例#27
0
        private async Task <ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken))
            {
                // get states by id order to have deterministic checksum
                var documentChecksumsTasks          = DocumentIds.Select(id => DocumentStates[id].GetChecksumAsync(cancellationToken));
                var additionalDocumentChecksumTasks = AdditionalDocumentIds.Select(id => AdditionalDocumentStates[id].GetChecksumAsync(cancellationToken));

                var serializer = new Serializer(_solutionServices.Workspace);

                var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken);

                // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed.
                var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null;
                var parseOptionsChecksum       = SupportsCompilation ? ChecksumCache.GetOrCreate(ParseOptions, _ => serializer.CreateChecksum(ParseOptions, cancellationToken)) : Checksum.Null;

                var projectReferenceChecksums  = ChecksumCache.GetOrCreate <ProjectReferenceChecksumCollection>(ProjectReferences, _ => new ProjectReferenceChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
                var metadataReferenceChecksums = ChecksumCache.GetOrCreate <MetadataReferenceChecksumCollection>(MetadataReferences, _ => new MetadataReferenceChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));
                var analyzerReferenceChecksums = ChecksumCache.GetOrCreate <AnalyzerReferenceChecksumCollection>(AnalyzerReferences, _ => new AnalyzerReferenceChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()));

                var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false);

                var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false);

                return(new ProjectStateChecksums(
                           infoChecksum,
                           compilationOptionsChecksum,
                           parseOptionsChecksum,
                           new DocumentChecksumCollection(documentChecksums),
                           projectReferenceChecksums,
                           metadataReferenceChecksums,
                           analyzerReferenceChecksums,
                           new TextDocumentChecksumCollection(additionalChecksums)));
            }
        }
示例#28
0
 /// <summary>Checks whether this project references the given project. </summary>
 /// <param name="project">The project. </param>
 /// <returns>True when the given project is referenced. </returns>
 public bool IsReferencingProject(VsProject project)
 {
     return(ProjectReferences.Any(p => p.IsSameProject(project)));
 }
示例#29
0
 public ProjectReferences()
 {
     I = this;
 }
 public bool HasReferencedProject(Guid projectGuid)
 {
     return(ProjectReferences.Any(p => p == projectGuid));
 }