Exemple #1
0
        /// <summary>
        /// Returns the list of available types.
        /// </summary>
        /// <param name="baseType">The base type to match.  Can be null.</param>
        /// <param name="excludeGlobalTypes">Determines whether types
        /// from all referenced assemblies should be checked.</param>
        public ICollection GetTypes(Type baseType, bool excludeGlobalTypes)
        {
            List <Type> types = new List <Type>();

            if (baseType == null)
            {
                baseType = typeof(object);
            }

            LoggingService.Debug("TypeDiscoveryService.GetTypes for " + baseType.FullName
                                 + "excludeGlobalTypes=" + excludeGlobalTypes.ToString());
            //seek in all assemblies
            //allow to work designers like columns editor in datagridview
            // Searching types can cause additional assemblies to be loaded, so we need to use
            // ToArray to prevent an exception if the collection changes.
            foreach (Assembly asm in TypeResolutionService.DesignerAssemblies.ToArray())
            {
                if (excludeGlobalTypes)
                {
                    if (GacInterop.IsWithinGac(asm.Location))
                    {
                        continue;
                    }
                }
                try {
                    AddDerivedTypes(baseType, asm, types);
                } catch (FileNotFoundException) {
                } catch (FileLoadException) {
                } catch (BadImageFormatException) {
                    // ignore assembly load errors
                }
            }
            LoggingService.Debug("TypeDiscoveryService returns " + types.Count + " types");

            // TODO - Don't look in all assemblies.
            // Should use the current project and its referenced assemblies
            // as well as System.Windows.Forms.

            return(types);
        }
Exemple #2
0
        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void OpenReferenceInILSpyCallback(object sender, EventArgs e)
        {
            var explorer = ((EnvDTE80.DTE2)GetGlobalService(typeof(EnvDTE.DTE))).ToolWindows.SolutionExplorer;
            var items    = (object[])explorer.SelectedItems;

            foreach (EnvDTE.UIHierarchyItem item in items)
            {
                dynamic reference = item.Object;
                string  path      = null;
                if (reference.PublicKeyToken != "")
                {
                    var token = Utils.HexStringToBytes(reference.PublicKeyToken);
                    path = GacInterop.FindAssemblyInNetGac(new AssemblyNameInfo()
                    {
                        Name = reference.Identity, Version = new Version(reference.Version), PublicKeyOrToken = new PublicKeyToken(token), Culture = string.Empty
                    });
                }
                if (path == null)
                {
                    path = reference.Path;
                }
                OpenAssemblyInILSpy(path);
            }
        }
Exemple #3
0
        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void OpenReferenceInILSpyCallback(object sender, EventArgs e)
        {
            var explorer = ((EnvDTE80.DTE2)GetGlobalService(typeof(EnvDTE.DTE))).ToolWindows.SolutionExplorer;
            var items    = (object[])explorer.SelectedItems;

            foreach (EnvDTE.UIHierarchyItem item in items)
            {
                var    reference = GetReference(item.Object);
                string path      = null;
                if (!string.IsNullOrEmpty(reference.PublicKeyToken))
                {
                    var token = Utils.HexStringToBytes(reference.PublicKeyToken);
                    path = GacInterop.FindAssemblyInNetGac(new AssemblyNameReference(reference.Name, reference.Version)
                    {
                        PublicKeyToken = token
                    });
                }
                if (path == null)
                {
                    path = reference.Path;
                }
                OpenAssemblyInILSpy(path);
            }
        }
Exemple #4
0
        protected override void OnExecute(object sender, EventArgs e)
        {
            var explorer = owner.DTE.ToolWindows.SolutionExplorer;
            var item     = ((object[])explorer.SelectedItems).FirstOrDefault() as UIHierarchyItem;

            if (item == null)
            {
                return;
            }
            if (item.Object is Reference reference)
            {
                var project       = reference.ContainingProject;
                var roslynProject = owner.Workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == project.FileName);
                var references    = GetReferences(roslynProject);
                if (references.TryGetValue(reference.Name, out var path))
                {
                    OpenAssembliesInILSpy(new[] { path });
                }
                else
                {
                    owner.ShowMessage("Could not find reference '{0}', please ensure the project and all references were built correctly!", reference.Name);
                }
            }
            else
            {
                dynamic referenceObject = item.Object;
                if (TryGetProjectFileName(referenceObject, out string fileName))
                {
                    var roslynProject = owner.Workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == fileName);
                    var references    = GetReferences(roslynProject);
                    if (references.TryGetValue(referenceObject.Name, out string path))
                    {
                        OpenAssembliesInILSpy(new[] { path });
                        return;
                    }
                }
                else
                {
                    var values = GetProperties(referenceObject.Properties, "Type", "FusionName", "ResolvedPath");
                    if (values[0] == "Package")
                    {
                        values = GetProperties(referenceObject.Properties, "Name", "Version", "Path");
                        if (values[0] != null && values[1] != null && values[2] != null)
                        {
                            OpenAssembliesInILSpy(new[] { $"{values[2]}\\{values[0]}.{values[1]}.nupkg" });
                            return;
                        }
                    }
                    else if (values[2] != null)
                    {
                        OpenAssembliesInILSpy(new[] { $"{values[2]}" });
                        return;
                    }
                    else if (!string.IsNullOrWhiteSpace(values[1]))
                    {
                        OpenAssembliesInILSpy(new string[] { GacInterop.FindAssemblyInNetGac(AssemblyNameReference.Parse(values[1])) });
                        return;
                    }
                }
                owner.ShowMessage("Could not find reference '{0}', please ensure the project and all references were built correctly!", referenceObject.Name);
            }
        }
        public DnSpyFile Resolve(IAssembly assembly, ModuleDef sourceModule = null, bool delayLoad = false)
        {
            FrameworkRedirect.ApplyFrameworkRedirect(ref assembly, sourceModule);

            if (assembly.IsContentTypeWindowsRuntime)
            {
                return(ResolveWinMD(assembly, sourceModule, delayLoad));
            }

            // WinMD files have a reference to mscorlib but its version is always 255.255.255.255
            // since mscorlib isn't really loaded. The resolver only loads exact versions, so
            // we must change the version or the resolve will fail.
            if (assembly.Name == "mscorlib" && assembly.Version == invalidMscorlibVersion)
            {
                assembly = new AssemblyNameInfo(assembly)
                {
                    Version = newMscorlibVersion
                }
            }
            ;

            return(ResolveNormal(assembly, sourceModule, delayLoad));
        }

        DnSpyFile ResolveNormal(IAssembly assembly, ModuleDef sourceModule, bool delayLoad)
        {
            var existingFile = fileList.FindAssembly(assembly);

            if (existingFile != null)
            {
                return(existingFile);
            }

            var file = LookupFromSearchPaths(assembly, sourceModule, true);

            if (file != null)
            {
                return(fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad));
            }

            if (fileList.UseGAC)
            {
                var gacFile = GacInterop.FindAssemblyInNetGac(assembly);
                if (gacFile != null)
                {
                    return(fileList.GetOrCreate(gacFile, fileList.AssemblyLoadEnabled, true, delayLoad));
                }
                foreach (var path in GacInfo.OtherGacPaths)
                {
                    file = TryLoadFromDir(assembly, true, path);
                    if (file != null)
                    {
                        return(fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad));
                    }
                }
            }

            file = LookupFromSearchPaths(assembly, sourceModule, false);
            if (file != null)
            {
                return(fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad));
            }

            return(null);
        }

        DnSpyFile LookupFromSearchPaths(IAssembly asmName, ModuleDef sourceModule, bool exactCheck)
        {
            DnSpyFile file;
            string    sourceModuleDir = null;

            if (sourceModule != null && File.Exists(sourceModule.Location))
            {
                sourceModuleDir = Path.GetDirectoryName(sourceModule.Location);
                file            = TryLoadFromDir(asmName, exactCheck, sourceModuleDir);
                if (file != null)
                {
                    return(file);
                }
            }
            var ary = asmSearchPathsArray;

            foreach (var path in ary)
            {
                file = TryLoadFromDir(asmName, exactCheck, path);
                if (file != null)
                {
                    return(file);
                }
            }

            return(null);
        }

        DnSpyFile TryLoadFromDir(IAssembly asmName, bool exactCheck, string dirPath)
        {
            string baseName;

            try {
                baseName = Path.Combine(dirPath, asmName.Name);
            }
            catch (ArgumentException) {             // eg. invalid chars in asmName.Name
                return(null);
            }
            return(TryLoadFromDir2(asmName, exactCheck, baseName + ".dll") ??
                   TryLoadFromDir2(asmName, exactCheck, baseName + ".exe"));
        }

        DnSpyFile TryLoadFromDir2(IAssembly asmName, bool exactCheck, string filename)
        {
            if (!File.Exists(filename))
            {
                return(null);
            }

            DnSpyFile file  = null;
            bool      error = true;

            try {
                file = fileList.CreateDnSpyFile(filename);
                file.IsAutoLoaded = true;
                var asm = file.AssemblyDef;
                if (asm == null)
                {
                    return(null);
                }
                bool b = exactCheck ?
                         AssemblyNameComparer.CompareAll.Equals(asmName, asm) :
                         AssemblyNameComparer.NameAndPublicKeyTokenOnly.Equals(asmName, asm);
                if (!b)
                {
                    return(null);
                }

                error = false;
                return(file);
            }
            finally {
                if (error)
                {
                    if (file != null)
                    {
                        file.Dispose();
                    }
                }
            }
        }

        DnSpyFile ResolveWinMD(IAssembly assembly, ModuleDef sourceModule, bool delayLoad)
        {
            var existingFile = fileList.FindAssembly(assembly);

            if (existingFile != null)
            {
                return(existingFile);
            }

            foreach (var winmdPath in GacInfo.WinmdPaths)
            {
                string file;
                try {
                    file = Path.Combine(winmdPath, assembly.Name + ".winmd");
                }
                catch (ArgumentException) {
                    continue;
                }
                if (File.Exists(file))
                {
                    return(fileList.GetOrCreate(file, fileList.AssemblyLoadEnabled, true, delayLoad));
                }
            }
            return(null);
        }
    }
 static string FindAssemblyFromGAC(AssemblyDefinition assemblyDefinition)
 {
     return(GacInterop.FindAssemblyInNetGac(assemblyDefinition.Name));
 }
        void ScanProjectAssemblies()
        {
            // custom user controls don't need custom images
            loadImages = false;
            foreach (IProjectContent pc in AllProjectContentsWithReferences)
            {
                if (pc.Project == null)
                {
                    ReflectionProjectContent rpc = pc as ReflectionProjectContent;
                    if (rpc == null)
                    {
                        continue;
                    }
                    if (rpc.AssemblyFullName == typeof(object).Assembly.FullName)
                    {
                        continue;
                    }
                    if (GacInterop.IsWithinGac(rpc.AssemblyLocation))
                    {
                        continue;
                    }
                }
                foreach (IClass c in pc.Classes)
                {
                    var ctors = c.Methods.Where(method => method.IsConstructor);
                    if (ctors.Any() && !ctors.Any(
                            (IMethod method) => method.IsPublic && method.Parameters.Count == 0
                            ))
                    {
                        // do not include classes that don't have a public parameterless constructor
                        continue;
                    }
                    foreach (IClass subClass in c.ClassInheritanceTree)
                    {
                        if (subClass.FullyQualifiedName == "System.Windows.Forms.Form")
                        {
                            break;                             // is not a design component
                        }
                        if (subClass.FullyQualifiedName == "System.ComponentModel.IComponent")
                        {
                            goto isDesignComponent;
                        }
                        foreach (IAttribute attr in subClass.Attributes)
                        {
                            if (attr.AttributeType.FullyQualifiedName == "System.ComponentModel.DesignTimeVisibleAttribute")
                            {
                                if (attr.PositionalArguments.Count == 1 && attr.PositionalArguments[0] is bool)
                                {
                                    if ((bool)attr.PositionalArguments[0])
                                    {
                                        goto isDesignComponent;
                                    }
                                }
                                else
                                {
                                    goto isDesignComponent;
                                }
                            }
                        }
                    }
                    // is not a design component
                    continue;
isDesignComponent:
                    this.Items.Add(new SideTabItemDesigner(c.Name, new CustomComponentToolBoxItem(c)));
                }
            }
        }
 static string FindAssemblyFromGAC(AssemblyDefinition assemblyDefinition)
 {
     return(GacInterop.FindAssemblyInNetGac(Decompiler.Metadata.AssemblyNameReference.Parse(assemblyDefinition.Name.FullName)));
 }