コード例 #1
0
ファイル: App.xaml.cs プロジェクト: ruo2012/AvaloniaILSpy
        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    var output = new StringBuilder();
        //    if (ILSpy.MainWindow.FormatExceptions(StartupExceptions.ToArray(), output))
        //    {
        //        MessageBox.Show(output.ToString(), "Sorry we crashed!");
        //        Environment.Exit(1);
        //    }
        //    base.OnStartup(e);
        //}

        #endregion


        void Window_RequestNavigate(OpenUriRoutedEventArgs e)
        {
            if (e.Uri.Scheme == "resource")
            {
                AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath))
                {
                    using (StreamReader r = new StreamReader(s))
                    {
                        string line;
                        while ((line = r.ReadLine()) != null)
                        {
                            output.Write(line);
                            output.WriteLine();
                        }
                    }
                }
                ILSpy.MainWindow.Instance.TextView.ShowText(output);
            }
            else
            {
                ILSpy.MainWindow.OpenLink(e.Uri.ToString());
            }
            e.Handled = true;
        }
コード例 #2
0
        void OpenAssemblies(ILSpySettings spySettings)
        {
            HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
            if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1)
            {
                SharpTreeNode node = null;
                if (sessionSettings.ActiveTreeViewPath != null)
                {
                    node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
                    if (node == this.assemblyListTreeNode && sessionSettings.ActiveAutoLoadedAssembly != null)
                    {
                        node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
                    }
                }
                if (node != null)
                {
                    SelectNode(node);

                    // only if not showing the about page, perform the update check:
                    ShowMessageIfUpdatesAvailableAsync(spySettings);
                }
                else
                {
                    AboutPage.Display(decompilerTextView);
                }
            }

            AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();

            if (FormatExceptions(App.StartupExceptions.ToArray(), output))
            {
                decompilerTextView.ShowText(output);
            }
        }
コード例 #3
0
 public override void Execute(object parameter)
 {
     MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvaloniaEditTextOutput> .Factory.StartNew(() => {
         AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
         Parallel.ForEach(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), new ParallelOptions {
             MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct
         }, delegate(LoadedAssembly asm) {
             if (!asm.HasLoadError)
             {
                 Stopwatch w         = Stopwatch.StartNew();
                 Exception exception = null;
                 using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) {
                     try {
                         //new CSharpLanguage().DecompileAssembly(asm, new Decompiler.PlainTextOutput(writer), new DecompilationOptions() { FullDecompilation = true, CancellationToken = ct });
                     }
                     catch (Exception ex) {
                         writer.WriteLine(ex.ToString());
                         exception = ex;
                     }
                 }
                 lock (output) {
                     output.Write(asm.ShortName + " - " + w.Elapsed);
                     if (exception != null)
                     {
                         output.Write(" - ");
                         output.Write(exception.GetType().Name);
                     }
                     output.WriteLine();
                 }
             }
         });
         return(output);
     }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
 }
コード例 #4
0
        public override bool View(DecompilerTextView textView)
        {
            EmbeddedResource er = r as EmbeddedResource;

            if (er != null)
            {
                Stream s = er.GetResourceStream();
                if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit)
                {
                    s.Position = 0;
                    FileType type = GuessFileType.DetectFileType(s);
                    if (type != FileType.Binary)
                    {
                        s.Position = 0;
                        AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                        output.Write(new StreamReader(s, Encoding.UTF8).ReadToEnd());
                        string ext;
                        if (type == FileType.Xml)
                        {
                            ext = ".xml";
                        }
                        else
                        {
                            ext = Path.GetExtension(DecompilerTextView.CleanUpName(er.Name));
                        }
                        textView.ShowNode(output, this, HighlightingManager.Instance.GetDefinitionByExtension(ext));
                        return(true);
                    }
                }
            }
            return(false);
        }
コード例 #5
0
        public override bool View(DecompilerTextView textView)
        {
            AvaloniaEditTextOutput  output       = new AvaloniaEditTextOutput();
            IHighlightingDefinition highlighting = null;

            textView.RunWithCancellation(
                token => Task.Factory.StartNew(
                    () => {
                try {
                    // cache read XAML because stream will be closed after first read
                    if (xml == null)
                    {
                        using (var reader = new StreamReader(Data)) {
                            xml = reader.ReadToEnd();
                        }
                    }
                    output.Write(xml);
                    highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
                }
                catch (Exception ex) {
                    output.Write(ex.ToString());
                }
                return(output);
            }, token)
                ).Then(t => textView.ShowNode(t, this, highlighting)).HandleExceptions();
            return(true);
        }
コード例 #6
0
ファイル: TaskHelper.cs プロジェクト: zhxymh/AvaloniaILSpy
 /// <summary>
 /// Handle exceptions by displaying the error message in the text view.
 /// </summary>
 public static void HandleExceptions(this Task task)
 {
     task.Catch <Exception>(exception => Dispatcher.UIThread.InvokeAsync(new Action(delegate {
         AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
         output.Write(exception.ToString());
         MainWindow.Instance.TextView.ShowText(output);
     }))).IgnoreExceptions();
 }
コード例 #7
0
        public static void Display(DecompilerTextView textView)
        {
            AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();

            output.WriteLine("ILSpy version " + RevisionClass.FullVersion);
            output.AddUIElement(
                delegate {
                StackPanel stackPanel          = new StackPanel();
                stackPanel.HorizontalAlignment = HorizontalAlignment.Center;
                stackPanel.Orientation         = Orientation.Horizontal;
                if (latestAvailableVersion == null)
                {
                    AddUpdateCheckButton(stackPanel, textView);
                }
                else
                {
                    // we already retrieved the latest version sometime earlier
                    ShowAvailableVersion(latestAvailableVersion, stackPanel);
                }
                CheckBox checkBox       = new CheckBox();
                checkBox.Margin         = new Thickness(4);
                checkBox.Content        = "Automatically check for updates every week";
                UpdateSettings settings = new UpdateSettings(ILSpySettings.Load());
                checkBox.Bind(CheckBox.IsCheckedProperty, new Binding("AutomaticUpdateCheckEnabled")
                {
                    Source = settings
                });
                return(new StackPanel {
                    Margin = new Thickness(0, 4, 0, 0),
                    Cursor = Cursor.Default,
                    Children = { stackPanel, checkBox }
                });
            });
            output.WriteLine();
            foreach (var plugin in App.ExportProvider.GetExportedValues <IAboutPageAddition>())
            {
                plugin.Write(output);
            }
            output.WriteLine();
            var asm = typeof(AboutPage).Assembly;

            using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), "README.txt")) {
                using (StreamReader r = new StreamReader(s)) {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        output.WriteLine(line);
                    }
                }
            }
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("SharpDevelop", "http://www.icsharpcode.net/opensource/sd/"));
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MIT License", "resource:license.txt"));
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("LGPL", "resource:LGPL.txt"));
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MS-PL", "resource:MS-PL.txt"));
            textView.ShowText(output);
        }
コード例 #8
0
        internal static async void GeneratePdbForAssembly(LoadedAssembly assembly)
        {
            var file = assembly.GetPEFileOrNull();

            if (!PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
            {
                await MessageBox.Show($"Cannot create PDB file for {Path.GetFileName(assembly.FileName)}, because it does not contain a PE Debug Directory Entry of type 'CodeView'.");

                return;
            }
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title           = "Save file";
            dlg.InitialFileName = DecompilerTextView.CleanUpName(assembly.ShortName) + ".pdb";
            dlg.Filters         = new List <FileDialogFilter> {
                new FileDialogFilter {
                    Name = "Portable PDB", Extensions = { "pdb" }
                }, new FileDialogFilter {
                    Name = "All files", Extensions = { "*" }
                }
            };
            dlg.Directory = Path.GetDirectoryName(assembly.FileName);
            string fileName = await dlg.ShowAsync(App.Current.GetMainWindow());

            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }
            DecompilationOptions options = new DecompilationOptions();

            MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvaloniaEditTextOutput> .Factory.StartNew(() => {
                AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                Stopwatch stopwatch           = Stopwatch.StartNew();
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)) {
                    try {
                        var decompiler = new CSharpDecompiler(file, assembly.GetAssemblyResolver(), options.DecompilerSettings);
                        PortablePdbWriter.WritePdb(file, decompiler, options.DecompilerSettings, stream);
                    } catch (OperationCanceledException) {
                        output.WriteLine();
                        output.WriteLine("Generation was cancelled.");
                        throw;
                    }
                }
                stopwatch.Stop();
                output.WriteLine("Generation complete in " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
                output.WriteLine();
                output.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + fileName + "\""); });
                output.WriteLine();
                return(output);
            }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
        }
コード例 #9
0
 public override bool View(DecompilerTextView textView)
 {
     try {
         AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
         Data.Position = 0;
         IBitmap image = new Bitmap(Data);
         output.AddUIElement(() => new Image {
             Source = image
         });
         output.WriteLine();
         output.AddButton(Images.Save, Resources.Save, async delegate {
             await Save(null);
         });
         textView.ShowNode(output, this);
         return(true);
     }
     catch (Exception) {
         return(false);
     }
 }
コード例 #10
0
        internal static void Execute(IEnumerable <AssemblyTreeNode> nodes)
        {
            var highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
            var options      = PdbToXmlOptions.IncludeEmbeddedSources | PdbToXmlOptions.IncludeMethodSpans | PdbToXmlOptions.IncludeTokens;

            MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvaloniaEditTextOutput> .Factory.StartNew(() => {
                AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                var writer = new TextOutputWriter(output);
                foreach (var node in nodes)
                {
                    string pdbFileName = Path.ChangeExtension(node.LoadedAssembly.FileName, ".pdb");
                    if (!File.Exists(pdbFileName))
                    {
                        continue;
                    }
                    using (var pdbStream = File.OpenRead(pdbFileName))
                        using (var peStream = File.OpenRead(node.LoadedAssembly.FileName))
                            PdbToXmlConverter.ToXml(writer, pdbStream, peStream, options);
                }
                return(output);
            }, ct)).Then(output => MainWindow.Instance.TextView.ShowNodes(output, null, highlighting)).HandleExceptions();
        }
コード例 #11
0
        static void AddUpdateCheckButton(StackPanel stackPanel, DecompilerTextView textView)
        {
            Button button = new Button();

            button.Content = "Check for updates";
            button.Cursor  = Cursor.Default;
            stackPanel.Children.Add(button);

            button.Click += delegate {
                button.Content   = "Checking...";
                button.IsEnabled = false;
                GetLatestVersionAsync().ContinueWith(
                    delegate(Task <AvailableVersionInfo> task) {
                    try {
                        stackPanel.Children.Clear();
                        ShowAvailableVersion(task.Result, stackPanel);
                    } catch (Exception ex) {
                        AvaloniaEditTextOutput exceptionOutput = new AvaloniaEditTextOutput();
                        exceptionOutput.WriteLine(ex.ToString());
                        textView.ShowText(exceptionOutput);
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
            };
        }
コード例 #12
0
        public override bool View(DecompilerTextView textView)
        {
            try {
                AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                Data.Position = 0;
                Bitmap image;

                //HACK: windows imaging does not understand that .cur files have the same layout as .ico
                // so load to data, and modify the ResourceType in the header to make look like an icon...
                MemoryStream s = Data as MemoryStream;
                if (null == s)
                {
                    // data was stored in another stream type (e.g. PinnedBufferedMemoryStream)
                    s = new MemoryStream();
                    Data.CopyTo(s);
                }
                byte[] curData = s.ToArray();
                curData[2] = 1;
                using (Stream stream = new MemoryStream(curData)) {
                    image = new Bitmap(stream);
                }

                output.AddUIElement(() => new Image {
                    Source = image
                });
                output.WriteLine();
                output.AddButton(Images.Save, Resources.Save, async delegate {
                    await Save(null);
                });
                textView.ShowNode(output, this);
                return(true);
            }
            catch (Exception) {
                return(false);
            }
        }
コード例 #13
0
        public override void Execute(object parameter)
        {
            const int numRuns  = 100;
            var       language = MainWindow.Instance.CurrentLanguage;
            var       nodes    = MainWindow.Instance.SelectedNodes.ToArray();
            var       options  = new DecompilationOptions();

            MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvaloniaEditTextOutput> .Factory.StartNew(() => {
                options.CancellationToken = ct;
                Stopwatch w = Stopwatch.StartNew();
                for (int i = 0; i < numRuns; ++i)
                {
                    foreach (var node in nodes)
                    {
                        node.Decompile(language, new PlainTextOutput(), options);
                    }
                }
                w.Stop();
                AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                double msPerRun = w.Elapsed.TotalMilliseconds / numRuns;
                output.Write($"Average time: {msPerRun.ToString("f1")}ms\n");
                return(output);
            }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
        }
コード例 #14
0
 void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args)
 {
     if (nugetPackagesToLoad.Count > 0)
     {
         LoadAssemblies(nugetPackagesToLoad, commandLineLoadedAssemblies, focusNode: false);
         nugetPackagesToLoad.Clear();
     }
     if (args.NavigateTo != null)
     {
         bool found = false;
         if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal))
         {
             string namespaceName = args.NavigateTo.Substring(2);
             foreach (LoadedAssembly asm in commandLineLoadedAssemblies)
             {
                 AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm);
                 if (asmNode != null)
                 {
                     NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName);
                     if (nsNode != null)
                     {
                         found = true;
                         SelectNode(nsNode);
                         break;
                     }
                 }
             }
         }
         else
         {
             foreach (LoadedAssembly asm in commandLineLoadedAssemblies)
             {
                 ModuleDefinition def = asm.GetModuleDefinitionOrNull();
                 if (def != null)
                 {
                     MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def, args.NavigateTo);
                     if (mr != null)
                     {
                         found = true;
                         // Defer JumpToReference call to allow an assembly that was loaded while
                         // resolving a type-forwarder in FindMemberByKey to appear in the assembly list.
                         Dispatcher.UIThread.InvokeAsync(new Action(() => JumpToReference(mr)), DispatcherPriority.Loaded);
                         break;
                     }
                 }
             }
         }
         if (!found)
         {
             AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
             output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", args.NavigateTo));
             decompilerTextView.ShowText(output);
         }
     }
     else if (commandLineLoadedAssemblies.Count == 1)
     {
         // NavigateTo == null and an assembly was given on the command-line:
         // Select the newly loaded assembly
         JumpToReference(commandLineLoadedAssemblies[0].GetModuleDefinitionOrNull());
     }
     if (args.Search != null)
     {
         SearchPane.Instance.SearchTerm = args.Search;
         SearchPane.Instance.Show();
     }
     commandLineLoadedAssemblies.Clear();             // clear references once we don't need them anymore
 }
コード例 #15
0
        async Task <AvaloniaEditTextOutput> CreateSolution(IEnumerable <LoadedAssembly> assemblies, Language language, CancellationToken ct)
        {
            var result = new AvaloniaEditTextOutput();

            var duplicates = new HashSet <string>();

            if (assemblies.Any(asm => !duplicates.Add(asm.ShortName)))
            {
                result.WriteLine("Duplicate assembly names selected, cannot generate a solution.");
                return(result);
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            try {
                await Task.Run(() => Parallel.ForEach(assemblies, n => WriteProject(n, language, solutionDirectory, ct)))
                .ConfigureAwait(false);

                await Task.Run(() => SolutionCreator.WriteSolutionFile(solutionFilePath, projects))
                .ConfigureAwait(false);
            } catch (AggregateException ae) {
                if (ae.Flatten().InnerExceptions.All(e => e is OperationCanceledException))
                {
                    result.WriteLine();
                    result.WriteLine("Generation was cancelled.");
                    return(result);
                }

                result.WriteLine();
                result.WriteLine("Failed to generate the Visual Studio Solution. Errors:");
                ae.Handle(e => {
                    result.WriteLine(e.Message);
                    return(true);
                });

                return(result);
            }

            foreach (var item in statusOutput)
            {
                result.WriteLine(item);
            }

            if (statusOutput.Count == 0)
            {
                result.WriteLine("Successfully decompiled the following assemblies into Visual Studio projects:");
                foreach (var item in assemblies.Select(n => n.Text.ToString()))
                {
                    result.WriteLine(item);
                }

                result.WriteLine();

                if (assemblies.Count() == projects.Count)
                {
                    result.WriteLine("Created the Visual Studio Solution file.");
                }

                result.WriteLine();
                result.WriteLine("Elapsed time: " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
                result.WriteLine();
                result.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + solutionFilePath + "\""); });
            }

            return(result);
        }