Example #1
0
 public ProjectOutput([NotNull] Project project, [NotNull] VSLangProj.Reference reference, [NotNull] string binaryTargetDirectory)
     : this(project, Path.GetFileName(reference.Path), binaryTargetDirectory)
 {
     Contract.Requires(project != null);
     Contract.Requires(reference != null);
     Contract.Requires(binaryTargetDirectory != null);
 }
Example #2
0
        static public VSLangProj.Reference AddDllReferenceToProject(Project proj, string dllReference)
        {
            if (proj == null)
            {
                throw new Exception("Invalid  Project parameter");
            }

            if (dllReference.Equals(string.Empty) || dllReference.Equals(""))
            {
                throw new Exception("Invalid  dllReference parameter");
            }

            VSLangProj.Reference reference = null;

            VSLangProj.VSProject vsProject = (VSLangProj.VSProject)proj.Object;

            reference =
                vsProject.References.Find(dllReference);

            if (reference == null)
            {
                try
                {
                    reference =
                        vsProject.References.Add(dllReference);
                }
                catch (Exception ex)
                {
                    //ErrorHandler.HandleException(ex);
                    Logger.LogException(ex);
                }
            }

            return(reference);
        }
Example #3
0
        internal static void copyReferences(AbstractTestFramework testFramework, Project parentProject, Project unitTestProject)
        {
            //Add a unit test dll like nunit.framework.dll ref
            string tvTempUnitTestFolderHolder = testFramework.BinariesDirectory;

            if (!tvTempUnitTestFolderHolder.Equals(string.Empty))
            {
                foreach (string dll in testFramework.FrameworkDlls)
                {
                    VSLangProj.Reference nunitReferance =
                        ProjectManager.AddDllReferenceToProject(unitTestProject, System.IO.Path.Combine(tvTempUnitTestFolderHolder, dll));
                }
            }

            //add original projects outputted dll
            string tvTempOriginalProjectOutputDll =
                UTGManagerAndExaminor.ProjectExaminar.GetProjectOutputFullAssemblyName(parentProject);

            ProjectManager.AddDllReferenceToProject(unitTestProject, tvTempOriginalProjectOutputDll);

            //add original projects refs
            VSLangProj.References references = ProjectManager.GetProjectReferences(parentProject);

            ProjectManager.AddReferencesToProject(references, unitTestProject);
        }
Example #4
0
        private void ResolveProjectReferences(VSLangProj.VSProject project,
                                              Dictionary <string, ReferenceModel> availableReplaceReferences, Dictionary <string, ReferenceModel> referencesThanMustBeAdded)
        {
            this.Worker.ReportProgress(50, GetAction(() => { this.Info.DoOnProjectModifyingStart(project); }));

            VSLangProj.References               existingRefs = project.References;
            List <VSLangProj.Reference>         refsToRemove;
            Dictionary <string, ReferenceModel> refsToAdd;

            this.GetReferencesToAddAndRemove(existingRefs, availableReplaceReferences, referencesThanMustBeAdded, out refsToRemove, out refsToAdd);

            for (int i = 0; i < refsToRemove.Count; i++)
            {
                VSLangProj.Reference refToRemove      = refsToRemove[i];
                ReferenceModel       refModelToRemove = new ReferenceModel(refToRemove.Name, refToRemove.Path);
                refToRemove.Remove();
                this.Worker.ReportProgress(50, GetAction(() => { this.Info.DoOnReferenceRemoved(refModelToRemove); }));
            }

            foreach (KeyValuePair <string, ReferenceModel> refToAdd in refsToAdd)
            {
                existingRefs.Add(refToAdd.Value.Path);
                this.Worker.ReportProgress(50, GetAction(() => { this.Info.DoOnReferenceAdded(refToAdd.Value); }));
            }

            this.Worker.ReportProgress(50, GetAction(() => { this.Info.DoOnProjectModifyingEnd(project); }));
        }
Example #5
0
        public void AddAssemblyReference(VSLangProj.Reference reference)
        {
            var assemblyInfo = SystemTypeController.LoadAssembly(reference);

            _AssemblyReferences.Add(assemblyInfo);
            assemblyInfo.AddProject(this);
        }
Example #6
0
        private static bool IsSystemReference(VSLangProj.Reference reference)
        {
            var path = Path.GetFileNameWithoutExtension(reference.Path);

            return(path.StartsWith("System.", StringComparison.OrdinalIgnoreCase) || path.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase) ||
                   String.Compare(path, "mscorlib", true) == 0 || String.Compare(path, "system", true) == 0);
        }
 private static string GetFullName(VSLangProj.Reference reference)
 {
     return(string.Format("{0}, Version={1}.{2}.{3}.{4}, Culture={5}, PublicKeyToken={6}",
                          reference.Name,
                          reference.MajorVersion, reference.MinorVersion, reference.BuildNumber, reference.RevisionNumber,
                          DefaultIfNull(reference.Culture, "neutral"),
                          DefaultIfNull(reference.PublicKeyToken, "null")));
 }
Example #8
0
        public ReferenceEventArgs(IVsHierarchy hierarchy, uint itemId, VSLangProj.Reference reference)
        {
            ErrorHelper.ThrowIsNull(hierarchy, nameof(hierarchy));

            Hierarchy = hierarchy;
            ItemId    = itemId;
            Reference = reference;
        }
Example #9
0
        public AssemblyReferenceExtender(EnvDTE.IExtenderSite extenderSite, int cookie, VSLangProj.Reference reference, IVsBuildPropertyStorage storage, uint itemId)
        {
            _extenderSite = extenderSite;
            _cookie       = cookie;
            _storage      = storage;
            _itemid       = itemId;

            Reference = reference;
        }
Example #10
0
        public ProjectReference([NotNull] Solution solution, [NotNull] VSLangProj.Reference reference)
        {
            Contract.Requires(solution != null);
            Contract.Requires(reference != null);
            Contract.Requires(reference.SourceProject != null);

            _solution  = solution;
            _reference = reference;
        }
Example #11
0
    public ReferenceEventArgs(IVsHierarchy hierarchy, uint itemId, VSLangProj.Reference reference)
    {
      ErrorHelper.ThrowIsNull(hierarchy, nameof(hierarchy));
      ErrorHelper.ThrowIsNull(reference, nameof(reference));

      Hierarchy = hierarchy;
      ItemId    = itemId;
      Reference = reference;
    }
        public static AssemblyInfo LoadAssembly(VSLangProj.Reference reference)
        {
            string path = reference.Path;

            if (String.IsNullOrEmpty(path))
            {
                return(new AssemblyInfo(reference));
            }
            return(LoadAssembly(path));
        }
Example #13
0
 /// <summary>
 /// When a reference is removed/changed, let the provider know
 /// </summary>
 /// <param name="reference">Reference being removed</param>
 void ReferencesEvents_ReferenceRemoved(VSLangProj.Reference reference)
 {
     // Because our provider only has a AddReference method and no way to
     // remove them, we end up having to recreate it.
     //provider = new IronPython.CodeDom.PythonProvider();
     //foreach (VSLangProj.Reference currentReference in vsproject.References)
     //{
     //    provider.AddReference(currentReference.Path);
     //}
 }
Example #14
0
 public static EnvDTE.Project?GetSourceProject(this VSLangProj.Reference reference)
 {
     try
     {
         return(reference.SourceProject);
     }
     catch (Exception)
     {
         return(null);
     }
 }
 static Project FindProject(DTE2 envDte, string path, VSLangProj.Reference reference)
 {
     foreach (Project item in envDte.Solution.Projects)
     {
         string assemblyName = item.GetAssemblyName();
         if (Path.GetFileNameWithoutExtension(reference.Path).Equals(assemblyName))
         {
             return(item);
         }
     }
     return(null);
 }
Example #16
0
        /// <summary>
        /// Adds an assembly reference to a visual studio project.
        /// </summary>
        /// <param name="vsProject">The project to add the reference to.</param>
        /// <param name="path">The path to the assembly for which the reference is to be added.</param>
        private static void AddAssemblyReference(VSLangProj80.VSProject2 vsProject, string path)
        {
            bool   isSelfReference   = false;
            string referenceFileName = Path.GetFileName(path);

            // Decide if this is a self-reference
            foreach (EnvDTE.Configuration c in vsProject.Project.ConfigurationManager)
            {
                foreach (EnvDTE.OutputGroup og in c.OutputGroups)
                {
                    if (og.CanonicalName == "Built")
                    {
                        foreach (string str in (Array)og.FileNames)
                        {
                            if (str == referenceFileName)
                            {
                                isSelfReference = true;
                                break;
                            }
                        }
                    }

                    if (isSelfReference)
                    {
                        break;
                    }
                }

                if (isSelfReference)
                {
                    break;
                }
            }

            // Add reference, unless it is a self-reference
            if (!isSelfReference)
            {
                string referenceName           = Path.GetFileNameWithoutExtension(path);
                VSLangProj.Reference reference = vsProject.References.Item(referenceName);
                if (reference == null)
                {
                    Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Adding reference to {0}", path));
                    reference = vsProject.References.Add(path);
                }

                reference.CopyLocal = true;
            }
            else
            {
                Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Reference to {0} was determined to be a self reference and has not been added as a reference to the test project", path));
            }
        }
Example #17
0
        private static string GetSourceProjectFullName([NotNull] VSLangProj.Reference reference)
        {
            try
            {
                return(reference.SourceProject?.FullName);
            }
            catch
            {
                // invalid reference
            }

            return(null);
        }
Example #18
0
 /// <summary>
 /// When a reference is removed/changed, let the provider know
 /// </summary>
 /// <param name="reference">Reference being removed</param>
 void ReferencesEvents_ReferenceRemoved(VSLangProj.Reference reference)
 {
     // Because our provider only has an AddReference method and no way to
     // remove them, we end up having to recreate it.
     provider = new FoxPro.CodeDom.FoxProProvider();
     if (vsproject.References != null)
     {
         foreach (VSLangProj.Reference currentReference in vsproject.References)
         {
             provider.AddReference(currentReference.Path);
         }
     }
 }
Example #19
0
        public static EnvDTE.Project GetSourceProject([NotNull] this VSLangProj.Reference reference)
        {
            Contract.Requires(reference != null);

            try
            {
                return(reference.SourceProject);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        private static string GetSourceProjectFullName([NotNull] VSLangProj.Reference reference)
        {
            Contract.Requires(reference != null);

            try
            {
                return(reference.SourceProject?.FullName);
            }
            catch
            {
            }

            return(null);
        }
Example #21
0
        public static bool GetCopyLocal([CanBeNull] this VSLangProj.Reference reference)
        {
            if (reference == null)
            {
                return(false);
            }

            try
            {
                return(reference.CopyLocal || (reference.ContainingProject != null));
            }
            catch
            {
                return(false);
            }
        }
Example #22
0
        public static bool GetCopyLocal([CanBeNull] this VSLangProj.Reference reference, [CanBeNull] string outputDirectory)
        {
            if (reference == null)
            {
                return(false);
            }

            try
            {
                return(reference.CopyLocal || GetImplicitCopyLocal(reference, outputDirectory));
            }
            catch
            {
                return(GetImplicitCopyLocal(reference, outputDirectory));
            }
        }
Example #23
0
        /// <summary>
        /// <see cref="VSLangProj.Reference.CopyLocal"/> is always FALSE for NuGet packages installed via "PackageRefrence" instead of "Packages.config"
        /// => check if file exists in output directory
        /// </summary>
        private static bool GetImplicitCopyLocal([NotNull] VSLangProj.Reference reference, [CanBeNull] string outputDirectory)
        {
            if (string.IsNullOrEmpty(outputDirectory))
            {
                return(false);
            }

            try
            {
                var fileName = Path.GetFileName(reference.Path);

                return(!string.IsNullOrEmpty(fileName) && File.Exists(Path.Combine(outputDirectory, fileName)));
            }
            catch
            {
                return(false);
            }
        }
Example #24
0
        private void AddProjectReference(Project baseProject, Project projectToReference)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (baseProject.Object is VSLangProj.VSProject vsProject)
            {
                VSLangProj.Reference reference = null;
                try
                {
                    reference = vsProject.References.Find(projectToReference.Name);
                }
                catch (Exception)
                {
                    //reference doesn't exist, good to go
                }

                if (reference != null)
                {
                    throw new InvalidOperationException("Reference already exists.");
                }

                vsProject.References.AddProject(projectToReference);
            }
        }
Example #25
0
        /// <returns>may return null</returns>
        public VsHierarchyItem FindReferenceItemId(VSLangProj.Reference reference)
        {
            var          projectName = reference.ContainingProject.UniqueName;
            IVsHierarchy hierarchy;

            ErrorHandler.ThrowOnFailure(Solution.GetProjectOfUniqueName(projectName, out hierarchy));
            var rootItem       = new VsHierarchyItem(hierarchy);
            var referencesNode = FindReferencesFolderNode(rootItem);
            var child          = referencesNode.GetFirstChild(false);

            while (child != null)
            {
                var browseObject = child.GetBrowseObject();
                if (browseObject == reference)
                {
                    return(child);
                }

                child = child.GetNextSibling(false);
            }

            return(null);
        }
Example #26
0
        private void TestImplicitNestedProjectReload(IServiceProvider sp, ProjectNode project, int dialogAnswer)
        {
            // Save everything.
            IVsSolution solutionService = (IVsSolution)sp.GetService(typeof(IVsSolution));

            solutionService.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, project, 0);

            IVsProject3 nestedProject = Utilities.GetNestedHierarchy(project, "ANestedProject") as IVsProject3;

            if (nestedProject == null)
            {
                throw new InvalidOperationException("The nested project has not been loaded corectly");
            }

            string nestedProjectFileName = null;

            nestedProject.GetMkDocument(VSConstants.VSITEMID_ROOT, out nestedProjectFileName);

            if (nestedProjectFileName == null)
            {
                throw new InvalidOperationException("The nested project file name could not been retrieved corectly");
            }

            string resourceText = Utilities.GetResourceStringFromTheProjectAssembly("QueryReloadNestedProject");

            // Create the messageBoxListener Thread. This will bring up the reload of the nested project file.
            // In this scenario we will answer dialogAnswer. Also we rely on the exact messagebox text here.
            string message = String.Format(System.Globalization.CultureInfo.CurrentCulture, resourceText, nestedProjectFileName);

            DialogBoxPurger purger = new DialogBoxPurger(dialogAnswer, message);
            bool            result = false;

            try
            {
                purger.Start();
                this.AddReferenceExternallyToTheProjectFile(nestedProjectFileName);
            }
            finally
            {
                result = purger.WaitForDialogThreadToTerminate();
            }

            if (!result)
            {
                throw new InvalidOperationException("The messagebox for relaoding the nested project file has never popped up");
            }

            // Check to see if the nested project is there.
            EnvDTE.Project     projectDTE = Utilities.GetAutomationObject(project);
            EnvDTE.ProjectItem item       = projectDTE.ProjectItems.Item("ANestedProject");

            Assert.IsNotNull(item, "The nested project has not been loaded correctly.");
            EnvDTE.Project nestedAutomationProject = item.SubProject;

            // Now check to see if we can find the added reference
            VSLangProj.VSProject automationProject = nestedAutomationProject.Object as VSLangProj.VSProject;
            if (nestedAutomationProject == null)
            {
                throw new InvalidOperationException("The nested project is not a vs language project");
            }

            // Get references collection
            VSLangProj.References references = automationProject.References;

            IEnumerator enumerator = references.GetEnumerator();
            bool        found      = false;

            while (enumerator.MoveNext())
            {
                VSLangProj.Reference reference = enumerator.Current as VSLangProj.Reference;
                if (reference.Name == BuildEngineRef)
                {
                    found = true;
                }
            }

            if (dialogAnswer == NativeMethods.IDYES)
            {
                Assert.IsTrue(found, "The nested project file has not been reloaded correctly");
            }
            else
            {
                Assert.IsFalse(found, "The nested project file has been reloaded but was asked not to do that.");
            }
        }
Example #27
0
 public ProjectReference(Solution solution, VSLangProj.Reference reference)
 {
     _solution  = solution;
     _reference = reference;
 }
Example #28
0
 public ProjectOutput([NotNull] Project project, [NotNull] VSLangProj.Reference reference, [NotNull] string binaryTargetDirectory)
 // ReSharper disable once AssignNullToNotNullAttribute
     : this(project, Path.GetFileName(reference.Path), binaryTargetDirectory)
 {
 }
Example #29
0
        /// <summary>
        /// Adds a reference to the selected project.
        /// </summary>
        /// <remarks>
        /// REF=http://www.codeproject.com/KB/macros/EnvDTE.aspx
        /// </remarks>
        /// <param name="project"></param>
        /// <param name="referenceStrIdentity"></param>
        /// <param name="browseUrl"></param>
        public static void AddProjectReference(Project project, string referenceStrIdentity, string browseUrl)
        {
            //browseUrl is either the File Path or the Strong Name
            //(System.Configuration, Version=2.0.0.0, Culture=neutral,
            //                       PublicKeyToken=B03F5F7F11D50A3A)
            string path = "";

            if (!browseUrl.StartsWith(referenceStrIdentity))
            {
                //it is a path
                path = browseUrl;
            }

            if (project.Object is VSLangProj.VSProject)
            {
                VSLangProj.VSProject vsproject = (VSLangProj.VSProject)project.Object;
                VSLangProj.Reference reference = null;
                try
                {
                    reference = vsproject.References.Find(referenceStrIdentity);
                }
                catch (Exception)
                {
                    //it failed to find one, so it must not exist.
                    //But it decided to error for the fun of it. :)
                }
                if (reference == null)
                {
                    if (path == "")
                    {
                        vsproject.References.Add(browseUrl);
                    }
                    else
                    {
                        vsproject.References.Add(path);
                    }
                }
                else
                {
                    throw new Exception("Reference already exists.");
                }
            }
            else if (project.Object is VsWebSite.VSWebSite)
            {
                VsWebSite.VSWebSite         vswebsite = (VsWebSite.VSWebSite)project.Object;
                VsWebSite.AssemblyReference reference = null;
                try
                {
                    foreach (VsWebSite.AssemblyReference r in vswebsite.References)
                    {
                        if (r.Name == referenceStrIdentity)
                        {
                            reference = r;
                            break;
                        }
                    }
                }
                catch (Exception)
                {
                    //it failed to find one, so it must not exist.
                    //But it decided to error for the fun of it. :)
                }
                if (reference == null)
                {
                    if (path == "")
                    {
                        vswebsite.References.AddFromGAC(browseUrl);
                    }
                    else
                    {
                        vswebsite.References.AddFromFile(path);
                    }
                }
                else
                {
                    throw new Exception("Reference already exists.");
                }
            }
            else
            {
                throw new Exception("Currently, system is only set up " +
                                    "to do references for normal projects.");
            }
        }
Example #30
0
        void DoWork()
        {
            string  assemblyName;
            Version assemblyVersion;
            string  assemblyLocation;
            string  typeName;
            int     genericParameterCount;

            GetNecessaryInfo(out assemblyName, out assemblyVersion, out assemblyLocation, out typeName, out genericParameterCount);


            #region Create host
            var host = this._projectTracker.Host;

            if (host == null)
            {
                VSServiceProvider.Current.Logger.WriteToLog("Couldn't create host.");
                return;
            }
            #endregion
            #region Find and load assembly
            IAssembly iAssembly = null;

            if (assemblyName.Equals(host.CoreAssemblySymbolicIdentity.Name.Value, StringComparison.OrdinalIgnoreCase) && assemblyVersion.Equals(host.CoreAssemblySymbolicIdentity.Version))
            {
                iAssembly = host.FindAssembly(host.CoreAssemblySymbolicIdentity);
            }
            else
            {
                var references = _projectTracker.References;
                VSLangProj.Reference reference   = null;
                var assemblyNameWithoutExtension = Path.GetFileNameWithoutExtension(assemblyName);
                for (int i = 1; i <= references.Count; i++)//TODO: Unify this code. This process of looking up a reference from a name is also done in ContractsProvider.TryGetAssemblyReference
                {
                    var    tempRef = references.Item(i);
                    string refName = tempRef.Name;
                    if (refName.Equals(assemblyNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        reference = tempRef;
                        break;
                    }
                }
                if (reference != null)
                {
                    IName   iName    = host.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(reference.Path));
                    string  culture  = reference.Culture;
                    Version version  = new Version(reference.MajorVersion, reference.MinorVersion, reference.BuildNumber, reference.RevisionNumber);
                    string  location = reference.Path;
                    var     tempRef2 = new Microsoft.Cci.Immutable.AssemblyReference(host, new AssemblyIdentity(iName, culture, version, Enumerable <byte> .Empty, location));
                    iAssembly = host.LoadAssembly(tempRef2.AssemblyIdentity);
                }
                else
                {
                    VSServiceProvider.Current.Logger.WriteToLog("Couldn't find reference for metadata file.");
                    return;
                }
            }
            if (iAssembly == null || iAssembly == Dummy.Assembly)
            {
                VSServiceProvider.Current.Logger.WriteToLog("Couldn't get assembly for metadata file.");
                return;
            }
            #endregion
            #region Get contracts provider
            var contractsProvider = host.GetContractExtractor(iAssembly.UnitIdentity);
            if (contractsProvider == null)
            {
                VSServiceProvider.Current.Logger.WriteToLog("Couldn't get contracts provider.");
                return;
            }
            #endregion
            #region Collect contracts
            var type = UnitHelper.FindType(host.NameTable, iAssembly, typeName, genericParameterCount);
            if (type == null || type is Dummy)
            {
                VSServiceProvider.Current.Logger.WriteToLog("Couldn't find metadata type '" + typeName + "' in assembly.");
                return;
            }

            //This dictionaries will map the method/property signature to the contracts for the method/property
            var methodsToContracts = new Dictionary <string, IMethodContract>(type.Methods.Count());
            var gettersToContracts = new Dictionary <string, IMethodContract>();
            var settersToContracts = new Dictionary <string, IMethodContract>();

            //Set the formatting options for property getters and setters
            var propertySignatureFormattingOptions = NameFormattingOptions.OmitContainingNamespace |
                                                     // NameFormattingOptions.ReturnType |
                                                     NameFormattingOptions.TypeParameters |
                                                     NameFormattingOptions.UseTypeKeywords |
                                                     NameFormattingOptions.OmitContainingType;
            //NameFormattingOptions.Visibility;
            //Set the formating options for methods
            var methodSignatureFormattingOptions = NameFormattingOptions.OmitContainingNamespace |
                                                   NameFormattingOptions.ReturnType |
                                                   NameFormattingOptions.ParameterName |
                                                   NameFormattingOptions.ParameterModifiers |
                                                   NameFormattingOptions.TypeParameters |
                                                   NameFormattingOptions.UseTypeKeywords |
                                                   NameFormattingOptions.OmitContainingType |
                                                   //NameFormattingOptions.Modifiers |
                                                   NameFormattingOptions.Signature
                                                   //NameFormattingOptions.Visibility
            ;

            //var sourceEmitterOutput = new SourceEmitterOutputString();//TODO: Use source emitter for all my printing? Instead of the whole NameFormattingOptions ordeal.
            //var csSourceEmitter = new SourceEmitter(sourceEmitterOutput);

            foreach (var method in type.Methods)
            {
                var methodContract = ContractHelper.GetMethodContractForIncludingInheritedContracts(host, method);
                if (methodContract != null && methodContract != ContractDummy.MethodContract)
                {
                    if (IsGetter(method))
                    {
                        if (method.ParameterCount > 0) //We have an indexer!
                        {
                            var indexerSignature = PrintIndexer(method, true);
                            gettersToContracts.Add(indexerSignature, methodContract);
                        }
                        else
                        {
                            var getterSignature = MemberHelper.GetMemberSignature(method, propertySignatureFormattingOptions);//Example: "XmlSchemaSet Schemas.get"
                            getterSignature = getterSignature.Substring(0, getterSignature.LastIndexOf('.'));
                            gettersToContracts.Add(getterSignature, methodContract);
                        }
                    }
                    else if (IsSetter(method))
                    {
                        if (method.ParameterCount > 1) //We have an indexer!
                        {
                            var indexerSignature = PrintIndexer(method, false);
                            settersToContracts.Add(indexerSignature, methodContract);
                        }
                        else
                        {
                            var setterSignature = MemberHelper.GetMemberSignature(method, propertySignatureFormattingOptions);
                            setterSignature = setterSignature.Substring(0, setterSignature.LastIndexOf('.'));
                            settersToContracts.Add(setterSignature, methodContract);
                        }
                    }
                    else
                    {
                        //#region Print method, stolen from CSharpSourceEmitter
                        //csSourceEmitter.PrintMethodDefinitionVisibility(method);
                        //csSourceEmitter.PrintMethodDefinitionModifiers(method);

                        //bool conversion = csSourceEmitter.IsConversionOperator(method);
                        //if (!conversion) {
                        //  csSourceEmitter.PrintMethodDefinitionReturnType(method);
                        //  if (!method.IsConstructor && !csSourceEmitter.IsDestructor(method))
                        //    csSourceEmitter.PrintToken(CSharpToken.Space);
                        //}
                        //csSourceEmitter.PrintMethodDefinitionName(method);
                        //if (conversion)
                        //  csSourceEmitter.PrintMethodDefinitionReturnType(method);

                        //if (method.IsGeneric) {
                        //  csSourceEmitter.Traverse(method.GenericParameters);
                        //}
                        //csSourceEmitter.Traverse(method.Parameters);
                        //#endregion
                        //var methodSignature = sourceEmitterOutput.Data;
                        //sourceEmitterOutput.ClearData();
                        var methodSignature = MemberHelper.GetMemberSignature(method, methodSignatureFormattingOptions);//Example: "XmlAttribute CreateAttribute(string name)"
                        methodsToContracts.Add(methodSignature, methodContract);
                    }
                }
            }
            #endregion

            var hasMethodContracts   = methodsToContracts.Count > 0;
            var hasPropertyContracts = gettersToContracts.Count > 0 || settersToContracts.Count > 0;

            if (!hasMethodContracts && !hasPropertyContracts)
            {
                VSServiceProvider.Current.Logger.WriteToLog("No contracts found.");
                return;
            }

            int propertyCounter = 0; //Counts the number of adornments added for property contracts
            int methodCounter   = 0; //Counts the number of adornments added for method contracts
            foreach (var line in _textView.TextSnapshot.Lines)
            {
                var lineText = line.GetText();

                //Skip lines with comments
                //This assumes that no method/property decelerations in metadata files will have comments in them
                if (lineText.Contains("//"))
                {
                    continue;
                }

                // bail out on nested types
                var typeNameMatch = Regex.Match(lineText, @"(class|struct|interface|enum) (\w+)");
                if (typeNameMatch.Success)
                {
                    if (typeNameMatch.Groups[2].Value == type.Name.Value)
                    {
                        continue;
                    }
                    break;
                }

                if (hasPropertyContracts &&
                    lineText.Contains('{') && (lineText.Contains(" get; ") || lineText.Contains(" set; ")) && lineText.Contains('}')) //Check if line is a property decleration
                {
                    #region Add property contracts
                    //Parse the property decleration to get a signature we can compare to our contract dictionaries
                    //Example of a property decleration: "     public int Build { get; }"
                    int  endOfSig              = lineText.IndexOf('{') - 1;
                    int  startOfSig            = endOfSig - 1;
                    bool hasHitSpace           = false;
                    bool isInPropertyParameter = false;
                    for (int i = startOfSig; i > 0; i--)
                    {
                        char c = lineText[i];
                        if (c == ']')
                        {
                            isInPropertyParameter = true;
                        }
                        else if (c == '[')
                        {
                            isInPropertyParameter = false;
                        }
                        else if (hasHitSpace && c == ' ')
                        {
                            startOfSig = i + 1;
                            break;
                        }
                        else if (!isInPropertyParameter && c == ' ')
                        {
                            startOfSig = i + 1;
                            break; // MAF: ignore return type of properties.
                            //hasHitSpace = true;
                        }
                    }
                    var propertySignature = lineText.Substring(startOfSig, endOfSig - startOfSig); //Example: "int Build"

                    IMethodContract getterContract = null;
                    IMethodContract setterContract = null;
                    if (gettersToContracts.TryGetValue(propertySignature, out getterContract) | // yes eager evaluation!!!
                        settersToContracts.TryGetValue(propertySignature, out setterContract))
                    {
                        var tag = propertySignature.GetHashCode();//We use this to uniquely identify the particular method/property decleration

                        //Find this first non-whitespace character. This is were we'll place the adornment.
                        int firstNonWhitespace = 0;
                        for (int i = 0; i < lineText.Length; i++)
                        {
                            char c = lineText[i];
                            if (c != ' ')
                            {
                                firstNonWhitespace = i;
                                break;
                            }
                        }
                        var span = _textView.TextSnapshot.CreateTrackingSpan(line.Start + firstNonWhitespace, propertySignature.Length, SpanTrackingMode.EdgeExclusive);
                        _vsTextProperties.LineHeight = _textView.LineHeight;
                        var ops       = AdornmentOptionsHelper.GetAdornmentOptions(VSServiceProvider.Current.VSOptionsPage);
                        var adornment = new MetadataContractAdornment(span, _vsTextProperties, VSServiceProvider.Current.Logger, _adornmentManager.QueueRefreshLineTransformer, ops);
                        adornment.SetContracts(getterContract, setterContract, null /* "Contracts from " + typeName + "." */);
                        _adornmentManager.AddAdornment(adornment, tag);
                        propertyCounter++;
                    }
                    #endregion
                    continue;
                }
                if (hasMethodContracts &&
                    lineText.Contains('(') && lineText.Contains(')') && lineText.Contains(';')) //Check if line is a method decleration
                {
                    #region Add method contracts
                    //Parse the method decleration to get a signature we can compare to our contract dictionaries
                    //Example of a method decleration: "      public static Version Parse(string input);"
                    int endOfSig = lineText.LastIndexOf(')') + 1;
                    //int startOfSig = !Char.IsWhiteSpace(lineText[0]) ? 0 : lineText.IndexOf(lineText.First(c => !Char.IsWhiteSpace(c)));
                    //int startOfSig = lineText.IndexOf('(');
                    //bool hitSpace = false;
                    //for (int i = startOfSig; i > 0; i--) {
                    //  char c = lineText[i];
                    //  if (c == ' ' && hitSpace) {
                    //    startOfSig = i + 1;
                    //    break;
                    //  } else if (c == ' ') {
                    //    hitSpace = true;
                    //  }
                    //}
                    var methodSignature = lineText.Substring(0, endOfSig); //Example: "Version Parse(string input)"

                    // remove modifiers
                    methodSignature = Regex.Replace(methodSignature, modifierFilter, "");
                    methodSignature = methodSignature.Trim();
                    if (methodSignature.StartsWith(type.Name.Value + "("))
                    {
                        methodSignature = "void .ctor" + methodSignature.Substring(type.Name.Value.Length);
                    }
                    IMethodContract methodContract;
                    if (methodsToContracts.TryGetValue(methodSignature, out methodContract))
                    {
                        var tag = methodSignature.GetHashCode();//We use this to uniquely identify the particular method/property decleration

                        //Find this first non-whitespace character. This is were we'll place the adornment.
                        int firstNonWhitespace = 0;
                        for (int i = 0; i < lineText.Length; i++)
                        {
                            char c = lineText[i];
                            if (c != ' ')
                            {
                                firstNonWhitespace = i;
                                break;
                            }
                        }
                        var span = _textView.TextSnapshot.CreateTrackingSpan(line.Start + firstNonWhitespace, methodSignature.Length, SpanTrackingMode.EdgeExclusive);
                        _vsTextProperties.LineHeight = _textView.LineHeight;
                        var ops       = AdornmentOptionsHelper.GetAdornmentOptions(VSServiceProvider.Current.VSOptionsPage);
                        var adornment = new MetadataContractAdornment(span, _vsTextProperties, VSServiceProvider.Current.Logger, _adornmentManager.QueueRefreshLineTransformer, ops);
                        adornment.SetContracts(methodContract, "Contracts from " + typeName + ".");
                        _adornmentManager.AddAdornment(adornment, tag);
                        //if (methodContract.IsPure) {
                        //  var purityAdornment = new PurityAdornment(_vsTextProperties, adornment);
                        //  //_adornmentManager.AddAdornment(purityAdornment, null);
                        //}
                        methodCounter++;
                    }
                    #endregion
                    continue;
                }
            }

            #region Add button to collapse all contracts
            if (propertyCounter > 0 || methodCounter > 0)
            {
                var button = new Button();
                button.Content = "Hide all contracts";
                button.Click  += OnCollapseAllClick;
                button.Cursor  = Cursors.Hand;
                var collapseAllAdornment = new StaticAdornment(false, 10d, true, 10d, button);
                _adornmentManager.AddStaticAdornment(collapseAllAdornment);
            }
            #endregion
        }
Example #31
0
        private static string GetReferenceString(VSLangProj.Reference reference)
        {
            if (!reference.StrongName)
            {
                return(reference.Path);
            }

            var name = reference.Name;

            if (name == "mscorlib")
            {
                // mscorlib is always loaded
                return(null);
            }

            return(reference.Path);

#if TODO // TODO: This shouldn't directly depend on GAC, rather we should have some kind of "reference simplifier".
            var possibleGacNames = GlobalAssemblyCache.GetAssemblyIdentities(name).ToArray();
            if (possibleGacNames.Length == 0)
            {
                // no assembly with simple "name" found in GAC, use path to identify the reference:
                return(reference.Path);
            }

            string version        = reference.Version;
            string culture        = reference.Culture;
            string publicKeyToken = reference.PublicKeyToken;

            var fullName = string.Concat(
                name,
                ", Version=",
                version,
                ", Culture=",
                (culture == "") ? "neutral" : culture,
                ", PublicKeyToken=",
                publicKeyToken.ToLowerInvariant());

            AssemblyIdentity identity;
            if (!AssemblyIdentity.TryParseDisplayName(fullName, out identity))
            {
                // ignore invalid names:
                return(null);
            }

            var foundEquivalent    = false;
            var foundNonEquivalent = false;
            foreach (var possibleGacName in possibleGacNames)
            {
                if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, possibleGacName))
                {
                    foundEquivalent = true;
                }
                else
                {
                    foundNonEquivalent = true;
                }

                if (foundEquivalent && foundNonEquivalent)
                {
                    break;
                }
            }

            if (!foundEquivalent)
            {
                // The reference name isn't equivalent to any GAC name.
                // The assembly is strong named but not GAC'd, so we need to load it from path:
                return(reference.Path);
            }

            if (foundNonEquivalent)
            {
                // We found some equivalent assemblies but also some non-equivalent.
                // So simple name doesn't identify the reference uniquely.
                return(fullName);
            }

            // We found a single simple name match that is equivalent to the given reference.
            // We can use the simple name to load the GAC'd assembly.
            return(name);
#endif
        }