public ReferenceIntegrityCheckReport Report(ProjectReference reference)
        {
            const string identity = "ContainsReferencedProjectsCheck";

            if (this.IsSatisfiedBy(reference))
            {
                return ReferenceIntegrityCheckReport.Ok(identity, reference);
            }

            ReportMessage message;

            if (!ContainsInSolution(this.projectsInSolution, reference))
            {
                string solutionName = this.projectsInSolution.First().Referrer;
                message = ReportMessage.Error("The solution '{0}' doesn't contain project '{1}'.", solutionName, reference.Name);
                return ReferenceIntegrityCheckReport.NotOk(message, identity, reference);
            }

            ProjectReference[] projectReferences = this.parser.ParseProjectReferences(reference.FullPath);

            string missingReferenceNames = string.Join(", ", projectReferences
                .Where(r => !ContainsInSolution(this.projectsInSolution ,r))
                .Select(r => r.Name));

            message = ReportMessage.Error("The solution '{0}' doesn't contain '{1}', but '{2}' requires it to be.",
                reference.Referrer, missingReferenceNames,
                reference.Name);

            return ReferenceIntegrityCheckReport.NotOk(message, identity, reference);
        }
 public void ProjectReferenceQuestion()
 {
     var optionValue = new ProjectReference( "ProjPath", new Guid( "76606c7b-5bf1-497c-9b0f-9695a6a8788d" ), "ProjectName", new XElement( "ProjectReference" ) );
       var option = new UserQuestionLiteralWithDescriptionOption<ProjectReference>( "A", "Option A", optionValue, "WasNull" );
       Assert.That( option.GetQuestionText(), Is.EqualTo( "(A) Option A:\r\nName: ProjectName\r\nKey: 76606c7b-5bf1-497c-9b0f-9695a6a8788d\r\nPath: ProjPath\r\n" ) );
       Assert.That( option.GetValue(), Is.EqualTo( optionValue ) );
 }
 public AddMissingReferenceCodeAction(Project project, string title, ProjectReference projectReferenceToAdd, AssemblyIdentity missingAssemblyIdentity)
 {
     _project = project;
     Title = title;
     _projectReferenceToAdd = projectReferenceToAdd;
     _missingAssemblyIdentity = missingAssemblyIdentity;
 }
		public override void LoadProject (IProgressMonitor monitor, SolutionEntityItem item, MSBuildProject msproject)
		{
			base.LoadProject (monitor, item, msproject);

			var dnp = item as DotNetProject;
			if (dnp == null)
				return;

			// Convert .projitems imports into project references

			foreach (var sp in msproject.Imports.Where (im => im.Label == "Shared" && im.Project.EndsWith (".projitems"))) {
				var projitemsFile = sp.Project;
				if (!string.IsNullOrEmpty (projitemsFile)) {
					projitemsFile = MSBuildProjectService.FromMSBuildPath (item.ItemDirectory, projitemsFile);
					projitemsFile = Path.Combine (Path.GetDirectoryName (msproject.FileName), projitemsFile);
					if (File.Exists (projitemsFile)) {
						MSBuildSerializer iser = Handler.CreateSerializer ();
						iser.SerializationContext.BaseFile = projitemsFile;
						iser.SerializationContext.ProgressMonitor = monitor;
						MSBuildProject p = new MSBuildProject ();
						p.Load (projitemsFile);
						Handler.LoadProjectItems (p, iser, ProjectItemFlags.Hidden | ProjectItemFlags.DontPersist);
						var r = new ProjectReference (ReferenceType.Project, Path.GetFileNameWithoutExtension (projitemsFile));
						r.Flags = ProjectItemFlags.DontPersist;
						r.SetItemsProjectPath (projitemsFile);
						dnp.References.Add (r);
					}
				}
			}
		}
Esempio n. 5
0
        public Task AddReferenceAsync(ProjectReference reference, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (reference == null) {
                return MakeExceptionTask(new ArgumentNullException("reference"));
            }

            EnsureInstanceDb();

            switch (reference.Kind) {
                case ProjectReferenceKind.ExtensionModule:
                    if (_references == null) {
                        _references = new HashSet<ProjectReference>();
                    }
                    _references.Add(reference);
                    string filename;
                    try {
                        filename = Path.GetFileNameWithoutExtension(reference.Name);
                    } catch (Exception e) {
                        return MakeExceptionTask(e);
                    }

                    return _typeDb.LoadExtensionModuleAsync(_factory,
                        filename,
                        reference.Name,
                        cancellationToken).ContinueWith(RaiseModulesChanged);
            }

            return Task.Factory.StartNew(EmptyTask);
        }
        internal static bool TryGetReference(
            Solution solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference)
        {
            // if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always.
            MetadataOnlyReferenceSet referenceSet;
            if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out referenceSet))
            {
                reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
                return true;
            }

            // okay, now use version based cache that can live multiple compilation as long as there is no semantic changes.

            // get one for the branch
            if (TryGetReferenceFromBranch(solution.BranchId, projectReference, finalOrDeclarationCompilation, version, out reference))
            {
                return true;
            }

            // see whether we can use primary branch one
            var primaryBranchId = solution.Workspace.PrimaryBranchId;
            if (solution.BranchId != primaryBranchId &&
                TryGetReferenceFromBranch(primaryBranchId, projectReference, finalOrDeclarationCompilation, version, out reference))
            {
                return true;
            }

            // noop, we don't have any
            reference = null;
            return false;
        }
        private SerializableProjectReference(SerializationInfo info, StreamingContext context)
        {
            var projectId = ((SerializableProjectId)info.GetValue("projectId", typeof(SerializableProjectId))).ProjectId;
            var aliases = ImmutableArray.Create((string[])info.GetValue("aliases", typeof(string[])));
            var embedInteropTypes = info.GetBoolean("embedInteropTypes");

            _projectReference = new ProjectReference(projectId, aliases, embedInteropTypes);
        }
        public SerializableProjectReference(ProjectReference projectReference)
        {
            if (projectReference == null)
            {
                throw new ArgumentNullException(nameof(projectReference));
            }

            _projectReference = projectReference;
        }
        internal static MetadataReference GetOrBuildReference(
            Solution solution,
            ProjectReference projectReference,
            Compilation finalCompilation,
            VersionStamp version,
            CancellationToken cancellationToken)
        {
            MetadataReference reference;
            if (TryGetReference(solution, projectReference, finalCompilation, version, out reference))
            {
                return reference;
            }

            // okay, we don't have one. so create one now.

            // first, prepare image
            // * NOTE * image is cancellable, do not create it inside of conditional weak table.
            var service = solution.Workspace.Services.GetService<ITemporaryStorageService>();
            var image = MetadataOnlyImage.Create(service, finalCompilation, cancellationToken);
            if (image.IsEmpty)
            {
                // unfortunately, we couldn't create one. do best effort
                if (TryGetReference(solution, projectReference, finalCompilation, VersionStamp.Default, out reference))
                {
                    // we have one from previous compilation!!, it might be out-of-date big time, but better than nothing.
                    // re-use it
                    return reference;
                }
            }

            // okay, proceed with whatever image we have

            // now, remove existing set
            var mapFromBranch = s_cache.GetValue(solution.BranchId, s_createReferenceSetMap);
            mapFromBranch.Remove(projectReference.ProjectId);

            // create new one
            var newReferenceSet = new MetadataOnlyReferenceSet(version, image);
            var referenceSet = s_snapshotCache.GetValue(finalCompilation, _ => newReferenceSet);
            if (newReferenceSet != referenceSet)
            {
                // someone else has beaten us. 
                // let image go eagerly. otherwise, finalizer in temporary storage will take care of it
                image.Cleanup();

                // return new reference
                return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
            }

            // record it to version based cache as well. snapshot cache always has a higher priority. we don't need to check returned set here
            // since snapshot based cache will take care of same compilation for us.
            mapFromBranch.GetValue(projectReference.ProjectId, _ => referenceSet);

            // return new reference
            return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
        }
        public void creating_a_project_references_from_a_project_copies_attributes()
        {
            var sourceProject = new CsProjFile(@"Solution1\harness\SlickGridHarness.csproj");
            var targetProject = new CsProjFile(@"Solution1\docs\FubuMVC.SlickGrid.Docs.csproj");
            var projectReference = new ProjectReference(targetProject, sourceProject);

            projectReference.Include.ShouldEqual(@"..\harness\SlickGridHarness.csproj");
            projectReference.ProjectGuid.ShouldEqual(sourceProject.ProjectGuid);
            projectReference.ProjectName.ShouldEqual(sourceProject.ProjectName);
        }
            public Given_a_project_with_a_reference_for_a_project_not_existing_in_solution()
            {
                var projectsInSolution = new[] { ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithoutReferences, ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithReferences };
                var parserMock = new Mock<IProjectParser>();
                parserMock
                    .Setup(p => p.ParseProjectReferences(ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithReferences.FullPath))
                    .Returns(new[] { ProjectReferenceTestSample.ReferenceFromProjectToAProjectWithSameName });

                this.check = new ProjectReferenceExistsInSolutionCheck(projectsInSolution, parserMock.Object);
                this.reference = ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithReferences;
            }
 private AssemblyDefinition ReadAssembly(ProjectReference projectReference)
 {
     AssemblyDefinition assemblyDefinition = null;
     if (!m_cache.TryGetValue(projectReference, out assemblyDefinition))
     {
         assemblyDefinition = ReadAssembly(
             projectReference.Location, Path.GetDirectoryName(projectReference.Location));
         if (assemblyDefinition != null)
             m_cache[projectReference] = assemblyDefinition;
     }
     return assemblyDefinition;
 }
            public Given_a_reference_with_path_which_does_not_exist()
            {
                this.reference = new ProjectReference
                {
                    Name = "what", 
                    Path = "what.csproj",
                    Referrer = "project",
                    SourceType = ReferenceSourceType.Project
                };

                this.check = new SolutionIntegrityCheck(
                    new MockFileSystem(new Dictionary<string, MockFileData>
                    {
                        { "any.csproj", new MockFileData(String.Empty) }
                    }), new ProjectReference[0], Mock.Of<IProjectParser>());
            }
            public Given_a_project_with_a_reference_which_does_not_exist_in_solution()
            {
                var projectsInSolution = new[] { ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithReferences };
                
                var parserMock = new Mock<IProjectParser>();
                parserMock
                    .Setup(p => p.ParseProjectReferences(ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithReferences.FullPath))
                    .Returns(new[] { ProjectReferenceTestSample.ReferenceFromProjectToAProjectWithSameName });

                var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
                {
                    {Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "testB.csproj")), new MockFileData(String.Empty)}
                });

                this.reference = ProjectReferenceTestSample.ReferenceFromSolutionToProjectWithReferences;
                this.check = new SolutionIntegrityCheck(fileSystem, projectsInSolution, parserMock.Object);
            }
 private static bool IsEquals(AssemblyNameReference name, ProjectReference projectReference)
 {
     var result =
         string.
             Equals(name.Name, projectReference.Name, StringComparison.InvariantCultureIgnoreCase) &&
         string.
             Equals(name.Culture, projectReference.Culture, StringComparison.InvariantCultureIgnoreCase);
     if (result)
     {
         var token = (name.PublicKeyToken == null || name.PublicKeyToken.Length == 0)
             ? string.Empty
             : Helper.PublicKeyTokenConvertFrom(name.PublicKeyToken);
         result = string.
             Equals(token, projectReference.PublicKeyToken, StringComparison.InvariantCultureIgnoreCase);
     }
     return result;
 }
Esempio n. 16
0
        internal void TryProjectConversionForIntroducedOutputPath(string binPath, AbstractProject projectToReference)
        {
            AssertIsForeground();

            if (this.CanConvertToProjectReferences)
            {
                // We should not already have references for this, since we're only introducing the path for the first time
                Contract.ThrowIfTrue(HasMetadataFileNameToConvertedProjectReference(binPath));

                var metadataReference = TryGetCurrentMetadataReference(binPath);
                if (metadataReference != null)
                {
                    var projectReference = new ProjectReference(
                        projectToReference.Id,
                        metadataReference.Properties.Aliases,
                        metadataReference.Properties.EmbedInteropTypes);

                    if (CanAddProjectReference(projectReference))
                    {
                        RemoveMetadataReferenceCore(metadataReference, disposeReference: true);
                        AddProjectReference(projectReference);

                        AddMetadataFileNameToConvertedProjectReference(binPath, projectReference);
                    }
                }
            }
        }
Esempio n. 17
0
 private void UpdateMetadataFileNameToConvertedProjectReference(string filePath, ProjectReference projectReference)
 {
     lock (_gate)
     {
         _metadataFileNameToConvertedProjectReference[filePath] = projectReference;
     }
 }
Esempio n. 18
0
 private void AddMetadataFileNameToConvertedProjectReference(string filePath, ProjectReference projectReference)
 {
     lock (_gate)
     {
         _metadataFileNameToConvertedProjectReference.Add(filePath, projectReference);
     }
 }
Esempio n. 19
0
        protected void RemoveProjectReference(ProjectReference projectReference)
        {
            AssertIsForeground();

            lock (_gate)
            {
                Contract.ThrowIfFalse(_projectReferences.Remove(projectReference));
            }

            if (_pushingChangesToWorkspaceHosts)
            {
                this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectReferenceRemoved(this.Id, projectReference));
            }
        }
Esempio n. 20
0
        public override void OnNodeDrop(object dataObject, DragOperation operation)
        {
            // It allows dropping either project references or projects.
            // Dropping a project creates a new project reference to that project

            DotNetProject project = dataObject as DotNetProject;

            if (project != null)
            {
                ProjectReference pr = new ProjectReference(project);
                DotNetProject    p  = CurrentNode.GetParentDataItem(typeof(DotNetProject), false) as DotNetProject;
                // Circular dependencies are not allowed.
                if (HasCircularReference(project, p.Name))
                {
                    return;
                }

                // If the reference already exists, bail out
                if (ProjectReferencesProject(p, project.Name))
                {
                    return;
                }
                p.References.Add(pr);
                IdeApp.ProjectOperations.Save(p);
                return;
            }

            // It's dropping a ProjectReference object.

            ProjectReference pref = dataObject as ProjectReference;
            ITreeNavigator   nav  = CurrentNode;

            if (operation == DragOperation.Move)
            {
                NodePosition pos = nav.CurrentPosition;
                nav.MoveToObject(dataObject);
                DotNetProject p = nav.GetParentDataItem(typeof(DotNetProject), true) as DotNetProject;
                nav.MoveToPosition(pos);
                DotNetProject p2 = nav.GetParentDataItem(typeof(DotNetProject), true) as DotNetProject;

                p.References.Remove(pref);

                // Check if there is a cyclic reference after removing from the source project
                if (pref.ReferenceType == ReferenceType.Project)
                {
                    DotNetProject pdest = p.ParentSolution.FindProjectByName(pref.Reference) as DotNetProject;
                    if (pdest == null || ProjectReferencesProject(pdest, p2.Name))
                    {
                        // Restore the dep
                        p.References.Add(pref);
                        return;
                    }
                }

                p2.References.Add(pref);
                IdeApp.ProjectOperations.Save(p);
                IdeApp.ProjectOperations.Save(p2);
            }
            else
            {
                nav.MoveToParent(typeof(DotNetProject));
                DotNetProject p = nav.DataItem as DotNetProject;

                // Check for cyclic referencies
                if (pref.ReferenceType == ReferenceType.Project)
                {
                    DotNetProject pdest = p.ParentSolution.FindProjectByName(pref.Reference) as DotNetProject;
                    if (pdest == null)
                    {
                        return;
                    }
                    if (HasCircularReference(pdest, p.Name))
                    {
                        return;
                    }

                    // The reference is already there
                    if (ProjectReferencesProject(p, pdest.Name))
                    {
                        return;
                    }
                }
                p.References.Add((ProjectReference)pref.Clone());
                IdeApp.ProjectOperations.Save(p);
            }
        }
Esempio n. 21
0
        static bool UpgradeMonoGameProject(MonoDevelop.Core.ProgressMonitor monitor, DotNetProjectExtension extension, MSBuildProject project)
        {
            bool needsSave    = false;
            bool containsMGCB = project.ItemGroups.Any(x => x.Items.Any(i => System.IO.Path.GetExtension(i.Include) == ".mgcb"));
            bool isMonoGame   = project.PropertyGroups.Any(x => x.GetProperties().Any(p => p.Name == "MonoGamePlatform")) ||
                                project.ItemGroups.Any(x => x.Items.Any(i => i.Name == "Reference" && i.Include == "MonoGame.Framework")) ||
                                containsMGCB;
            bool isDesktopGL   = project.ItemGroups.Any(x => x.Items.Any(i => i.Include.EndsWith("SDL2.dll")));
            bool isApplication = project.PropertyGroups.Any(x => x.GetProperties().Any(p => p.Name == "OutputType" && p.Value == "Exe"))
                                 | project.PropertyGroups.Any(x => x.GetProperties().Any(p => p.Name == "AndroidApplication" && string.Compare(p.Value, bool.TrueString, true) == 0));
            bool isShared          = project.PropertyGroups.Any(x => x.GetProperties().Any(p => p.Name == "HasSharedItems" && p.Value == "true"));
            bool absoluteReferenes = false;
            var  type = extension.Project.GetType().Name;

            monitor.Log.WriteLine("Found {0}", type);
            monitor.Log.WriteLine("Found {0}", project.GetType().Name);
            var platform = isDesktopGL ? "DesktopGL" : "Windows";
            var path     = MonoGameExtensionsPath;

            if (extension.Project.FlavorGuids.Contains("{FEACFBD2-3405-455C-9665-78FE426C6842}"))
            {
                platform = "iOS";
            }
            if (extension.Project.FlavorGuids.Contains("{06FA79CB-D6CD-4721-BB4B-1BD202089C55}"))
            {
                platform = "tvOS";
            }
            if (extension.Project.FlavorGuids.Contains("{EFBA0AD7-5A72-4C68-AF49-83D382785DCF}"))
            {
                platform = "Android";
            }
            if (extension.Project.FlavorGuids.Contains("{948B3504-5B70-4649-8FE4-BDE1FB46EC69}"))
            {
                platform = "MacOSX";
                // MonoMac Classic does not use MSBuild so we need to absolute path.
                path = MonoGameExtensionsAbsolutePath;
                absoluteReferenes = true;
            }
            if (extension.Project.FlavorGuids.Contains("{42C0BBD9-55CE-4FC1-8D90-A7348ABAFB23}"))
            {
                platform = "DesktopGL";
                // Xamarin.Mac Classic does not use MSBuild so we need to absolute path.
                path = MonoGameExtensionsAbsolutePath;
                absoluteReferenes = true;
            }
            if (extension.Project.FlavorGuids.Contains("{A3F8F2AB-B479-4A4A-A458-A89E7DC349F1}"))
            {
                platform = "DesktopGL";
            }
            monitor.Log.WriteLine("Platform = {0}", platform);
            monitor.Log.WriteLine("Path = {0}", path);
            monitor.Log.WriteLine("isMonoGame {0}", isMonoGame);
            if (isMonoGame)
            {
                var ritems = new List <MSBuildItem> ();
                foreach (var ig in project.ItemGroups)
                {
                    foreach (var i in ig.Items.Where(x => x.Name == "Reference" && x.Include == "MonoGame.Framework"))
                    {
                        var metaData = i.Metadata;
                        if (!metaData.HasProperty("HintPath"))
                        {
                            monitor.Log.WriteLine("Fixing {0} to be MonoGameContentReference", i.Include);
                            metaData.SetValue("HintPath", string.Format(path, platform, "MonoGame.Framework.dll"));
                            needsSave = true;
                        }
                    }
                    foreach (var i in ig.Items.Where(x => x.Name == "Reference" && x.Include == "Tao.Sdl"))
                    {
                        var metaData = i.Metadata;
                        if (!metaData.HasProperty("HintPath"))
                        {
                            monitor.Log.WriteLine("Fixing {0} to be Tao.Sdl", i.Include);
                            metaData.SetValue("HintPath", string.Format(path, platform, "Tao.Sdl.dll"));
                            needsSave = true;
                        }
                    }
                    foreach (var i in ig.Items.Where(x => x.Name == "Reference" && x.Include.StartsWith("OpenTK") &&
                                                     (platform != "iOS" && platform != "Android")))
                    {
                        var metaData = i.Metadata;
                        if (!metaData.HasProperty("HintPath"))
                        {
                            monitor.Log.WriteLine("Fixing {0} to be OpenTK", i.Include);
                            metaData.SetValue("HintPath", string.Format(path, platform, "OpenTK.dll"));
                            metaData.SetValue("SpecificVersion", "true");
                            needsSave = true;
                        }
                    }
                }
                foreach (var a in ritems)
                {
                    project.RemoveItem(a);
                }
                var dotNetProject = extension.Project;
                if (dotNetProject != null && absoluteReferenes)
                {
                    var items    = new List <ProjectReference> ();
                    var newitems = new List <ProjectReference> ();
                    foreach (var reference in dotNetProject.References)
                    {
                        if (reference.Reference == "MonoGame.Framework" && string.IsNullOrEmpty(reference.HintPath))
                        {
                            items.Add(reference);
                            newitems.Add(ProjectReference.CreateCustomReference(ReferenceType.Assembly, reference.Reference, string.Format(path, platform, "MonoGame.Framework.dll")));
                        }
                        if (reference.Reference.StartsWith("OpenTK", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(reference.HintPath))
                        {
                            items.Add(reference);
                            newitems.Add(ProjectReference.CreateCustomReference(ReferenceType.Assembly, reference.Reference, string.Format(path, platform, "OpenTK.dll")));
                        }
                        if (reference.Reference == "Tao.Sdl" && string.IsNullOrEmpty(reference.HintPath))
                        {
                            items.Add(reference);
                            newitems.Add(ProjectReference.CreateCustomReference(ReferenceType.Assembly, reference.Reference, string.Format(path, platform, "Tao.Sdl.dll")));
                        }
                    }
                    dotNetProject.References.RemoveRange(items);
                    dotNetProject.References.AddRange(newitems);
                }
            }
            if (isMonoGame && containsMGCB && (isApplication || isShared))
            {
                if (!project.PropertyGroups.Any(x => x.GetProperties().Any(p => p.Name == "MonoGamePlatform")) && !isShared)
                {
                    monitor.Log.WriteLine("Adding MonoGamePlatform {0}", platform == "tvOS" ? "iOS" : platform);
                    project.PropertyGroups.First().SetValue("MonoGamePlatform", platform == "tvOS" ? "iOS" : platform, true);
                    needsSave = true;
                }
                if (!project.Imports.Any(x => x.Project.StartsWith(MonoGameCommonProps, StringComparison.OrdinalIgnoreCase)) && !isShared)
                {
                    monitor.Log.WriteLine("Adding MonoGame.Common.props Import");
                    project.AddNewImport(MonoGameCommonProps, string.Format("Exists('{0}')", MonoGameCommonProps), project.PropertyGroups.First());
                    needsSave = true;
                }
                if (containsMGCB)
                {
                    var ritems = new List <MSBuildItem> ();
                    foreach (var ig in project.ItemGroups)
                    {
                        foreach (var i in ig.Items.Where(x => System.IO.Path.GetExtension(x.Include) == ".mgcb"))
                        {
                            if (i.Name != "MonoGameContentReference" && i.Name == "None")
                            {
                                monitor.Log.WriteLine("Fixing {0} to be MonoGameContentReference", i.Include);
                                ig.AddNewItem("MonoGameContentReference", i.Include);
                                ritems.Add(i);
                                needsSave = true;
                            }
                        }
                    }
                    foreach (var a in ritems)
                    {
                        project.RemoveItem(a);
                    }
                }
                if (!project.Imports.Any(x => x.Project.StartsWith(MonoGameContentBuildTargets, StringComparison.OrdinalIgnoreCase)) && !isShared)
                {
                    monitor.Log.WriteLine("Adding MonoGame Content Builder .targets");
                    project.AddNewImport(MonoGameContentBuildTargets);
                    needsSave = true;
                }
            }
            return(needsSave);
        }
Esempio n. 22
0
 /// <summary>
 /// Constructs a new client wrapping the given <see cref="BigqueryService"/>.
 /// </summary>
 /// <remarks>
 /// Care should be taken when constructing the service: if the default serializer settings are used,
 /// result values which can be parsed as date/time values can cause problems. Where possible, either use
 /// <see cref="BigQueryClient.Create(string, Apis.Auth.OAuth2.GoogleCredential)"/> or construct a service
 /// using serializer settings from <see cref="BigQueryClient.CreateJsonSerializersSettings"/>.
 /// </remarks>
 /// <param name="projectReference">A fully-qualified identifier for the project. Must not be null.</param>
 /// <param name="service">The service to wrap. Must not be null.</param>
 public BigQueryClientImpl(ProjectReference projectReference, BigqueryService service)
     : this(projectReference, service, null)
 {
 }
Esempio n. 23
0
        public void InitializeItem(SolutionItem policyParent, ProjectCreateInformation projectCreateInformation, string defaultLanguage, SolutionEntityItem item)
        {
            MonoDevelop.Projects.Project project = item as MonoDevelop.Projects.Project;

            if (project == null)
            {
                MessageService.ShowError(GettextCatalog.GetString("Can't create project with type: {0}", type));
                return;
            }

            // Set the file before setting the name, to make sure the file extension is kept
            project.FileName = Path.Combine(projectCreateInformation.ProjectBasePath, projectCreateInformation.ProjectName);
            project.Name     = projectCreateInformation.ProjectName;

            var dnp = project as DotNetProject;

            if (dnp != null)
            {
                if (policyParent.ParentSolution != null && !policyParent.ParentSolution.FileFormat.SupportsFramework(dnp.TargetFramework))
                {
                    SetClosestSupportedTargetFramework(policyParent.ParentSolution.FileFormat, dnp);
                }
                var substitution = new string[, ] {
                    { "ProjectName", GetProjectNameForSubstitution(projectCreateInformation) }
                };
                foreach (var desc in references)
                {
                    if (!projectCreateInformation.ShouldCreate(desc.CreateCondition))
                    {
                        continue;
                    }
                    if (desc.ProjectReference.ReferenceType == ReferenceType.Project)
                    {
                        string referencedProjectName = StringParserService.Parse(desc.ProjectReference.Reference, substitution);
                        var    parsedReference       = ProjectReference.RenameReference(desc.ProjectReference, referencedProjectName);
                        dnp.References.Add(parsedReference);
                    }
                    else
                    {
                        dnp.References.Add(desc.ProjectReference);
                    }
                }
            }

            foreach (SingleFileDescriptionTemplate resourceTemplate in resources)
            {
                try {
                    if (!projectCreateInformation.ShouldCreate(resourceTemplate.CreateCondition))
                    {
                        continue;
                    }
                    var projectFile = new ProjectFile(resourceTemplate.SaveFile(policyParent, project, defaultLanguage, project.BaseDirectory, null));
                    projectFile.BuildAction = BuildAction.EmbeddedResource;
                    project.Files.Add(projectFile);
                } catch (Exception ex) {
                    if (!IdeApp.IsInitialized)
                    {
                        throw;
                    }
                    MessageService.ShowError(GettextCatalog.GetString("File {0} could not be written.", resourceTemplate.Name), ex);
                }
            }

            foreach (FileDescriptionTemplate fileTemplate in files)
            {
                try {
                    if (!projectCreateInformation.ShouldCreate(fileTemplate.CreateCondition))
                    {
                        continue;
                    }
                    fileTemplate.SetProjectTagModel(projectCreateInformation.Parameters);
                    fileTemplate.AddToProject(policyParent, project, defaultLanguage, project.BaseDirectory, null);
                } catch (Exception ex) {
                    if (!IdeApp.IsInitialized)
                    {
                        throw;
                    }
                    MessageService.ShowError(GettextCatalog.GetString("File {0} could not be written.", fileTemplate.Name), ex);
                } finally {
                    fileTemplate.SetProjectTagModel(null);
                }
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Constructs a new client wrapping the given <see cref="BigqueryService"/>, with a specified default location
 /// for location-specific operations.
 /// </summary>
 /// <remarks>
 /// Care should be taken when constructing the service: if the default serializer settings are used,
 /// result values which can be parsed as date/time values can cause problems. Where possible, either use
 /// <see cref="BigQueryClient.Create(string, Apis.Auth.OAuth2.GoogleCredential)"/> or construct a service
 /// using serializer settings from <see cref="BigQueryClient.CreateJsonSerializersSettings"/>.
 /// </remarks>
 /// <param name="projectReference">A fully-qualified identifier for the project. Must not be null.</param>
 /// <param name="service">The service to wrap. Must not be null.</param>
 /// <param name="defaultLocation">The default location to use for location-specific operations. May be null.</param>
 public BigQueryClientImpl(ProjectReference projectReference, BigqueryService service, string defaultLocation)
     : this(GaxPreconditions.CheckNotNull(projectReference, nameof(projectReference)).ProjectId, service, defaultLocation)
 {
 }
Esempio n. 25
0
 public void OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
 {
 }
Esempio n. 26
0
 public void OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
 {
 }
 public void AddProjectReference(ProjectId projectId, ProjectReference projectReference)
 {
     OnProjectReferenceAdded(projectId, projectReference);
 }
 public void RemoveProjectReference(ProjectId projectId, ProjectReference projectReference)
 {
     OnProjectReferenceRemoved(projectId, projectReference);
 }
        public override void OnNodeRemoved(object dataObject)
        {
            ProjectReference pref = (ProjectReference)dataObject;

            pref.StatusChanged -= ReferenceStatusChanged;
        }
Esempio n. 30
0
        public void can_write_and_read_project_references()
        {
            var include = @"..\OtherProject\OtherProject.csproj";

            var project = CsProjFile.CreateAtSolutionDirectory("MyProj", "myproj");
            var reference1 = new ProjectReference(include)
            {
                ProjectName = "OtherProject",
                ProjectGuid = Guid.NewGuid()
            };

            project.Add(reference1);

            project.Save();

            var project2 = CsProjFile.LoadFrom(project.FileName);

            var reference2 = project2.Find<ProjectReference>(reference1.Include);

            var all = project2.All<ProjectReference>();

            reference2.ShouldNotBeNull();
            reference2.ProjectName.ShouldEqual(reference1.ProjectName);
            reference2.ProjectGuid.ShouldEqual(reference1.ProjectGuid);
        }
        public override bool HasChildNodes(MonoDevelop.Ide.Gui.Components.ITreeBuilder builder, object dataObject)
        {
            ProjectReference pref = (ProjectReference)dataObject;

            return(!pref.IsValid);
        }
            /// <summary>
            /// Attempts to get (without waiting) a metadata reference to a possibly in progress
            /// compilation. Actual compilation references are preferred over skeletal assembly
            /// references.  Could potentially return null if nothing can be provided.
            /// </summary>
            internal MetadataReference GetPartialMetadataReference(Solution solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken)
            {
                var state = this.ReadState();

                // get compilation in any state it happens to be in right now.
                Compilation compilation;
                if (state.Compilation.TryGetValue(out compilation)
                    && compilation != null
                    && this.ProjectState.LanguageServices == fromProject.LanguageServices)
                {
                    // if we have a compilation and its the correct language, use a simple compilation reference
                    return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
                }

                return null;
            }
Esempio n. 33
0
        Task EnsureAnalysisDocumentIsOpen()
        {
            if (analysisDocument != null)
            {
                Microsoft.CodeAnalysis.Document doc;
                try {
                    doc = RoslynWorkspace.CurrentSolution.GetDocument(analysisDocument);
                } catch (Exception) {
                    doc = null;
                }
                if (doc != null)
                {
                    return(Task.CompletedTask);
                }
            }
            if (Editor == null)
            {
                UnsubscribeAnalysisDocument();
                return(Task.CompletedTask);
            }
            if (Project != null && !IsUnreferencedSharedProject(Project))
            {
                lock (analysisDocumentLock) {
                    UnsubscribeRoslynWorkspace();
                    RoslynWorkspace = TypeSystemService.GetWorkspace(this.Project.ParentSolution);
                    if (RoslynWorkspace == null)                     // Solution not loaded yet
                    {
                        return(Task.CompletedTask);
                    }
                    SubscribeRoslynWorkspace();
                    analysisDocument = FileName != null?TypeSystemService.GetDocumentId(this.Project, this.FileName) : null;

                    if (analysisDocument != null)
                    {
                        TypeSystemService.InformDocumentOpen(analysisDocument, Editor);
                        return(Task.CompletedTask);
                    }
                }
            }
            lock (adhocProjectLock) {
                var token = analysisDocumentSrc.Token;
                if (adhocProject != null)
                {
                    return(Task.CompletedTask);
                }

                if (Editor != null)
                {
                    var node = TypeSystemService.GetTypeSystemParserNode(Editor.MimeType, BuildAction.Compile);
                    if (Editor.MimeType == "text/x-csharp" || node?.Parser.CanGenerateAnalysisDocument(Editor.MimeType, BuildAction.Compile, new string[0]) == true)
                    {
                        var newProject = Services.ProjectService.CreateDotNetProject("C#");

                        this.adhocProject = newProject;

                        newProject.Name = "InvisibleProject";
                        newProject.References.Add(ProjectReference.CreateAssemblyReference("mscorlib"));
                        newProject.References.Add(ProjectReference.CreateAssemblyReference("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
                        newProject.References.Add(ProjectReference.CreateAssemblyReference("System.Core"));

                        newProject.FileName = "test.csproj";
                        if (!Window.ViewContent.IsUntitled)
                        {
                            adHocFile = Editor.FileName;
                        }
                        else
                        {
                            adHocFile = (Platform.IsWindows ? "C:\\" : "/") + Window.ViewContent.UntitledName + ".cs";
                        }

                        newProject.Files.Add(new ProjectFile(adHocFile, BuildAction.Compile));

                        adhocSolution = new Solution();
                        adhocSolution.AddConfiguration("", true);
                        adhocSolution.DefaultSolutionFolder.AddItem(newProject);
                        return(TypeSystemService.Load(adhocSolution, new ProgressMonitor(), token, false).ContinueWith(task => {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            UnsubscribeRoslynWorkspace();
                            RoslynWorkspace = task.Result.FirstOrDefault();                              // 1 solution loaded ->1 workspace as result
                            SubscribeRoslynWorkspace();
                            analysisDocument = RoslynWorkspace.CurrentSolution.Projects.First().DocumentIds.First();
                            TypeSystemService.InformDocumentOpen(RoslynWorkspace, analysisDocument, Editor);
                        }));
                    }
                }
            }
            return(Task.CompletedTask);
        }
 public ProjectReferenceDescriptor(ProjectReference pref)
 {
     this.pref = pref;
 }
Esempio n. 35
0
        public void TestAddP2PReference1()
        {
            using (var workspace = CreateWorkspace())
            {
                var solution = workspace.CurrentSolution;

                var project1 = new TestHostProject(workspace, name: "project1");
                var project2 = new TestHostProject(workspace, name: "project2");

                workspace.AddTestProject(project1);
                workspace.AddTestProject(project2);

                var reference = new ProjectReference(project2.Id);
                workspace.OnProjectReferenceAdded(project1.Id, reference);

                var snapshot = workspace.CurrentSolution;
                var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
                var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;

                Assert.True(snapshot.GetProject(id1).ProjectReferences.Contains(reference), "ProjectReferences did not contain project2");
            }
        }
 void LogRemovedReferenceFromProject(ProjectReference referenceProjectItem)
 {
     LogRemovedReferenceFromProject(referenceProjectItem.Reference, ProjectName);
 }
            /// <summary>
            /// Get a metadata reference to this compilation info's compilation with respect to
            /// another project. For cross language references produce a skeletal assembly. If the
            /// compilation is not available, it is built. If a skeletal assembly reference is
            /// needed and does not exist, it is also built.
            /// </summary>
            internal async Task<MetadataReference> GetMetadataReferenceAsync(
                Solution solution,
                ProjectState fromProject,
                ProjectReference projectReference,
                CancellationToken cancellationToken)
            {
                Compilation compilation;

                // if we already have the compilation and its right kind then use it.
                if (this.ProjectState.LanguageServices == fromProject.LanguageServices
                    && this.TryGetCompilation(out compilation))
                {
                    return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
                }

                // If same language then we can wrap the other project's compilation into a compilation reference
                if (this.ProjectState.LanguageServices == fromProject.LanguageServices)
                {
                    // otherwise, base it off the compilation by building it first.
                    compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false);
                    return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
                }
                else
                {
                    // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it.
                    return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false);
                }
            }
 void LogAddedReferenceToProject(ProjectReference referenceProjectItem)
 {
     LogAddedReferenceToProject(referenceProjectItem.Reference, ProjectName);
 }
            /// <summary>
            /// Gets a metadata reference to a the metadata-only-image corresponding to the compilation.
            /// </summary>
            private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync(
                Solution solution, ProjectReference projectReference, CancellationToken cancellationToken)
            {
                using (Logger.LogBlock(FeatureId.SkeletonAssembly, FunctionId.SkeletonAssembly_GetMetadataOnlyImage, cancellationToken))
                {
                    var projectId = this.ProjectState.Id;
                    var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false);

                    // get or build compilation up to decleration state. this compilation will be used to provide live xml doc comment
                    var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution, cancellationToken: cancellationToken).ConfigureAwait(false);

                    MetadataReference reference;
                    if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out reference))
                    {
                        // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation.
                        using (await this.buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
                        {
                            // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly
                            var compilation = await this.GetOrBuildCompilationAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false);
                            reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilation, version, cancellationToken);
                        }
                    }

                    return reference;
                }
            }
Esempio n. 40
0
        protected bool CanAddProjectReference(ProjectReference projectReference)
        {
            if (projectReference.ProjectId == this.Id)
            {
                // cannot self reference
                return false;
            }

            lock (_gate)
            {
                if (_projectReferences.Contains(projectReference))
                {
                    // already have this reference
                    return false;
                }
            }

            var project = this.ProjectTracker.GetProject(projectReference.ProjectId);
            if (project != null)
            {
                // cannot add a reference to a project that references us (it would make a cycle)
                return !project.TransitivelyReferences(this.Id);
            }

            return true;
        }
Esempio n. 41
0
        protected void UpdateProjectReferenceAliases(AbstractProject referencedProject, ImmutableArray<string> aliases)
        {
            AssertIsForeground();

            var projectReference = GetCurrentProjectReferences().Single(r => r.ProjectId == referencedProject.Id);

            var newProjectReference = new ProjectReference(referencedProject.Id, aliases, projectReference.EmbedInteropTypes);

            // Is this a project with converted references? If so, make sure we track it
            string referenceBinPath = referencedProject.BinOutputPath;
            if (referenceBinPath != null && HasMetadataFileNameToConvertedProjectReference(referenceBinPath))
            {
                UpdateMetadataFileNameToConvertedProjectReference(referenceBinPath, newProjectReference);
            }

            // Remove the existing reference first
            RemoveProjectReference(projectReference);

            AddProjectReference(newProjectReference);
        }
Esempio n. 42
0
        private void UpdateProject(ProjectFileInfo projectFileInfo)
        {
            var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId);

            var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id);

            foreach (var file in projectFileInfo.SourceFiles)
            {
                if (unusedDocuments.Remove(file))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                    var id         = DocumentId.CreateNewId(projectFileInfo.WorkspaceId);
                    var version    = VersionStamp.Create();

                    var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));

                    _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                }
            }

            if (projectFileInfo.SpecifiedLanguageVersion.HasValue || projectFileInfo.DefineConstants != null)
            {
                var parseOptions = projectFileInfo.SpecifiedLanguageVersion.HasValue
                    ? new CSharpParseOptions(projectFileInfo.SpecifiedLanguageVersion.Value)
                    : new CSharpParseOptions();
                if (projectFileInfo.DefineConstants != null && projectFileInfo.DefineConstants.Any())
                {
                    parseOptions = parseOptions.WithPreprocessorSymbols(projectFileInfo.DefineConstants);
                }
                _workspace.SetParseOptions(project.Id, parseOptions);
            }

            foreach (var unused in unusedDocuments)
            {
                _workspace.RemoveDocument(unused.Value);
            }

            var unusedProjectReferences = new HashSet <ProjectReference>(project.ProjectReferences);

            foreach (var projectReferencePath in projectFileInfo.ProjectReferences)
            {
                ProjectFileInfo projectReferenceInfo;
                if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo))
                {
                    var reference = new ProjectReference(projectReferenceInfo.WorkspaceId);

                    if (unusedProjectReferences.Remove(reference))
                    {
                        // This reference already exists
                        continue;
                    }

                    _workspace.AddProjectReference(project.Id, reference);
                }
                else
                {
                    _logger.LogWarning($"Unable to resolve project reference '{projectReferencePath}' for '{projectFileInfo}'.");
                }
            }

            foreach (var unused in unusedProjectReferences)
            {
                _workspace.RemoveProjectReference(project.Id, unused);
            }

            var unusedAnalyzers = new Dictionary <string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath));

            foreach (var analyzerPath in projectFileInfo.Analyzers)
            {
                if (!File.Exists(analyzerPath))
                {
                    _logger.LogWarning($"Unable to resolve assembly '{analyzerPath}'");
                }
                else
                {
                    if (unusedAnalyzers.Remove(analyzerPath))
                    {
                        continue;
                    }
#if DNX451
                    var analyzerReference = new AnalyzerFileReference(analyzerPath);
                    project.AddAnalyzerReference(analyzerReference);
#endif
                }
            }

            foreach (var analyzerReference in unusedAnalyzers.Values)
            {
                project.RemoveAnalyzerReference(analyzerReference);
            }

            var unusedReferences = new HashSet <MetadataReference>(project.MetadataReferences);

            foreach (var referencePath in projectFileInfo.References)
            {
                if (!File.Exists(referencePath))
                {
                    _logger.LogWarning($"Unable to resolve assembly '{referencePath}'");
                }
                else
                {
                    var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath);

                    if (unusedReferences.Remove(metadataReference))
                    {
                        continue;
                    }

                    _logger.LogVerbose($"Adding reference '{referencePath}' to '{projectFileInfo.ProjectFilePath}'.");
                    _workspace.AddMetadataReference(project.Id, metadataReference);
                }
            }

            foreach (var reference in unusedReferences)
            {
                _workspace.RemoveMetadataReference(project.Id, reference);
            }
        }
Esempio n. 43
0
 private bool TryGetMetadataFileNameToConvertedProjectReference(string filePath, out ProjectReference projectReference)
 {
     lock (_gate)
     {
         return _metadataFileNameToConvertedProjectReference.TryGetValue(filePath, out projectReference);
     }
 }
 void AddReferenceToProject(ProjectReference assemblyReference)
 {
     project.References.Add(assemblyReference);
     project.Save();
     LogAddedReferenceToProject(assemblyReference);
 }
Esempio n. 45
0
        // Internal for unit testing
        internal void AddProjectReference(ProjectReference projectReference)
        {
            AssertIsForeground();

            // dev11 is sometimes calling us multiple times for the same data
            if (!CanAddProjectReference(projectReference))
            {
                return;
            }

            lock (_gate)
            {
                // always manipulate current state after workspace is told so it will correctly observe the initial state
                _projectReferences.Add(projectReference);
            }

            if (_pushingChangesToWorkspaceHosts)
            {
                // This project is already pushed to listening workspace hosts, but it's possible that our target
                // project hasn't been yet. Get the dependent project into the workspace as well.
                var targetProject = this.ProjectTracker.GetProject(projectReference.ProjectId);
                this.ProjectTracker.StartPushingToWorkspaceAndNotifyOfOpenDocuments(SpecializedCollections.SingletonEnumerable(targetProject));

                this.ProjectTracker.NotifyWorkspaceHosts(host => host.OnProjectReferenceAdded(this.Id, projectReference));
            }
        }
Esempio n. 46
0
        protected void GetReferences(Project project, MonoDevelop.Prj2Make.Schema.Csproj.Reference[] References, ProjectReferenceCollection references, IProgressMonitor monitor)
        {
            if (References == null || References.Length == 0)
            {
                return;
            }

            monitor.BeginTask(null, 5 + References.Length);

            try {
                // Get the GAC path
                string strBasePathMono1_0 = GetPackageDirectory("mono", "mono/1.0");

                monitor.Step(1);

                string strBasePathGtkSharp = GetPackageDirectory("gtk-sharp", "mono/gtk-sharp");

                monitor.Step(1);

                string strBasePathGtkSharp2_0 = GetPackageDirectory("gtk-sharp-2.0", "mono/gtk-sharp-2.0");

                monitor.Step(1);

                string strBasePathGeckoSharp = GetPackageDirectory("gecko-sharp", "mono/gecko-sharp");

                monitor.Step(1);

                string strBasePathGeckoSharp2_0 = GetPackageDirectory("gecko-sharp-2.0", "mono/gecko-sharp-2.0");

                string[] monoLibs = new string [] {
                    strBasePathMono1_0,
                    strBasePathGtkSharp2_0,
                    strBasePathGtkSharp,
                    strBasePathGeckoSharp2_0,
                    strBasePathGeckoSharp
                };

                // Iterate through the reference collection of the csproj file
                foreach (MonoDevelop.Prj2Make.Schema.Csproj.Reference rf in References)
                {
                    monitor.Step(1);

                    ProjectReference rfOut = null;

                    if (rf.Package != null && rf.Package.Length != 0)
                    {
                        rfOut           = new ProjectReference(MonoDevelop.Projects.ReferenceType.Project, Path.GetFileName(rf.Name));
                        rfOut.LocalCopy = true;
                        references.Add(rfOut);
                    }
                    else if (rf.AssemblyName != null)
                    {
                        string rname = rf.AssemblyName;
                        if (rname == "System.XML")
                        {
                            rname = "System.Xml";
                        }

                        string oref = Runtime.SystemAssemblyService.DefaultAssemblyContext.GetAssemblyFullName(rname, fx);
                        if (oref == null)
                        {
                            if (rf.HintPath != null)
                            {
                                string asm = MapPath(project.ItemDirectory, rf.HintPath);
                                if (!System.IO.File.Exists(asm))
                                {
                                    monitor.ReportWarning(GettextCatalog.GetString("Referenced assembly not found: ") + asm);
                                }
                                ProjectReference aref = new ProjectReference(MonoDevelop.Projects.ReferenceType.Assembly, asm);
                                references.Add(aref);
                                continue;
                            }
                            monitor.ReportWarning(GettextCatalog.GetString("Assembly reference could not be imported: ") + rf.AssemblyName);
                            continue;
                        }
                        rfOut           = new ProjectReference(MonoDevelop.Projects.ReferenceType.Package, oref);
                        rfOut.LocalCopy = true;
                        references.Add(rfOut);
                    }
                    else if (rf.HintPath != null)
                    {
                        // HACK - under Unix filenames are case sensitive
                        // Under Windows there's no agreement on Xml vs XML ;-)
                        if (Path.GetFileName(rf.HintPath) == "System.XML.dll")
                        {
                            ProjectReference pref = GetMonoReferece(strBasePathMono1_0, "System.Xml.dll");
                            if (pref != null)
                            {
                                references.Add(pref);
                                continue;
                            }
                        }
                        else
                        {
                            foreach (string libDir in monoLibs)
                            {
                                if (libDir == null)
                                {
                                    continue;
                                }
                                if (rf.HintPath == null)
                                {
                                    continue;
                                }
                                rfOut = GetMonoReferece(libDir, rf.HintPath);
                                if (rfOut != null)
                                {
                                    break;
                                }
                            }

                            if (rfOut == null)
                            {
                                rfOut           = new ProjectReference(MonoDevelop.Projects.ReferenceType.Package, Path.GetFileName(rf.HintPath));
                                rfOut.LocalCopy = true;
                            }
                            references.Add(rfOut);
                        }
                    }
                    else
                    {
                        monitor.ReportWarning(GettextCatalog.GetString("Assembly reference could not be imported: ") + rf.Name);
                    }
                }
            } finally {
                monitor.EndTask();
            }
        }
Esempio n. 47
0
        protected int AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(string filePath, MetadataReferenceProperties properties)
        {
            AssertIsForeground();

            // If this file is coming from a project, then we should convert it to a project reference instead
            if (this.CanConvertToProjectReferences && ProjectTracker.TryGetProjectByBinPath(filePath, out var project))
            {
                var projectReference = new ProjectReference(project.Id, properties.Aliases, properties.EmbedInteropTypes);
                if (CanAddProjectReference(projectReference))
                {
                    AddProjectReference(projectReference);
                    AddMetadataFileNameToConvertedProjectReference(filePath, projectReference);
                    return VSConstants.S_OK;
                }
            }

            // regardless whether the file exists or not, we still record it. one of reason
            // we do that is some cross language p2p references might be resolved
            // after they are already reported as metadata references. since we use bin path
            // as a way to discover them, if we don't previously record the reference ourselves,
            // cross p2p references won't be resolved as p2p references when we finally have
            // all required information.
            //
            // it looks like
            //    1. project system sometimes won't guarantee build dependency for intellisense build
            //       if it is cross language dependency
            //    2. output path of referenced cross language project might be changed to right one
            //       once it is already added as a metadata reference.
            //
            // but this has one consequence. even if a user adds a project in the solution as
            // a metadata reference explicitly, that dll will be automatically converted back to p2p
            // reference.
            //
            // unfortunately there is no way to prevent this using information we have since,
            // at this point, we don't know whether it is a metadata reference added because
            // we don't have enough information yet for p2p reference or user explicitly added it
            // as a metadata reference.
            AddMetadataReferenceCore(this.MetadataReferenceProvider.CreateMetadataReference(this, filePath, properties));

            // here, we change behavior compared to old C# language service. regardless of file being exist or not,
            // we will always return S_OK. this is to support cross language p2p reference better.
            //
            // this should make project system to cache all cross language p2p references regardless
            // whether it actually exist in disk or not.
            // (see Roslyn bug 7315 for history - http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems?_a=edit&id=7315)
            //
            // after this point, Roslyn will take care of non-exist metadata reference.
            //
            // But, this doesn't sovle the issue where actual metadata reference
            // (not cross language p2p reference) is missing at the time project is opened.
            //
            // in that case, msbuild filter those actual metadata references out, so project system doesn't know
            // path to the reference. since it doesn't know where dll is, it can't (or currently doesn't)
            // setup file change notification either to find out when dll becomes available.
            //
            // at this point, user has 2 ways to recover missing metadata reference once it becomes available.
            //
            // one way is explicitly clicking that missing reference from solution explorer reference node.
            // the other is building the project. at that point, project system will refresh references
            // which will discover new dll and connect to us. once it is connected, we will take care of it.
            return VSConstants.S_OK;
        }
Esempio n. 48
0
 public new void OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
 => base.OnProjectReferenceRemoved(projectId, projectReference);
Esempio n. 49
0
        public ProjectState RemoveProjectReference(ProjectReference projectReference)
        {
            Contract.Requires(this.ProjectReferences.Contains(projectReference));

            return this.With(
                projectInfo: this.ProjectInfo.WithProjectReferences(this.ProjectReferences.Remove(projectReference)).WithVersion(this.Version.GetNewerVersion()));
        }
        /// <inheritdoc />
        public override PagedAsyncEnumerable <DatasetList, BigQueryDataset> ListDatasetsAsync(ProjectReference projectReference, ListDatasetsOptions options = null)
        {
            GaxPreconditions.CheckNotNull(projectReference, nameof(projectReference));

            var pageManager = new DatasetPageManager(this);

            return(new RestPagedAsyncEnumerable <ListRequest, DatasetList, BigQueryDataset>(
                       () => CreateListDatasetsRequest(projectReference, options),
                       pageManager));
        }