Browse Source

Merge branch 'master' into newNR

newNRvisualizers
Daniel Grunwald 13 years ago
parent
commit
4ff696ebde
  1. 15
      data/resources/StringResources.fr.resx
  2. 6
      data/resources/StringResources.nl.resx
  3. BIN
      data/templates/packages/Modernizr.1.7.nupkg
  4. BIN
      data/templates/packages/Modernizr.2.5.3.nupkg
  5. BIN
      data/templates/packages/jQuery.1.6.1.nupkg
  6. BIN
      data/templates/packages/jQuery.1.7.2.nupkg
  7. 8
      data/templates/project/CSharp/MvcRazorProject.xpt
  8. 8
      data/templates/project/CSharp/MvcWebProject.xpt
  9. 8
      data/templates/project/VB/MvcRazorProject.xpt
  10. 8
      data/templates/project/VB/MvcWebProject.xpt
  11. 69
      samples/MSTest/MSTest.SharpDevelop.Tests/MSTest.SharpDevelop.Tests.csproj
  12. 338
      samples/MSTest/MSTest.SharpDevelop.Tests/MSTestFrameworkTests.cs
  13. 184
      samples/MSTest/MSTest.SharpDevelop.Tests/MSTestResultsTests.cs
  14. 31
      samples/MSTest/MSTest.SharpDevelop.Tests/Properties/AssemblyInfo.cs
  15. 24
      samples/MSTest/MSTest.SharpDevelop.sln
  16. 103
      samples/MSTest/MSTest.SharpDevelop/MSTest.SharpDevelop.csproj
  17. 30
      samples/MSTest/MSTest.SharpDevelop/MSTest.addin
  18. 46
      samples/MSTest/MSTest.SharpDevelop/MSTestApplication.cs
  19. 37
      samples/MSTest/MSTest.SharpDevelop/MSTestApplicationCommandLine.cs
  20. 134
      samples/MSTest/MSTest.SharpDevelop/MSTestDebugger.cs
  21. 109
      samples/MSTest/MSTest.SharpDevelop/MSTestFramework.cs
  22. 26
      samples/MSTest/MSTest.SharpDevelop/MSTestOptions.cs
  23. 32
      samples/MSTest/MSTest.SharpDevelop/MSTestOptionsPanel.xaml
  24. 64
      samples/MSTest/MSTest.SharpDevelop/MSTestOptionsPanel.xaml.cs
  25. 31
      samples/MSTest/MSTest.SharpDevelop/MSTestQualifiedClassName.cs
  26. 93
      samples/MSTest/MSTest.SharpDevelop/MSTestResult.cs
  27. 91
      samples/MSTest/MSTest.SharpDevelop/MSTestResults.cs
  28. 27
      samples/MSTest/MSTest.SharpDevelop/MSTestResultsFileName.cs
  29. 138
      samples/MSTest/MSTest.SharpDevelop/MSTestRunner.cs
  30. 28
      samples/MSTest/MSTest.SharpDevelop/ProjectItemExtensions.cs
  31. 31
      samples/MSTest/MSTest.SharpDevelop/Properties/AssemblyInfo.cs
  32. 1
      src/AddIns/BackendBindings/AspNet.Mvc/Project/AspNet.Mvc.csproj
  33. 77
      src/AddIns/BackendBindings/AspNet.Mvc/Project/Src/ViewInBrowser.cs
  34. 4
      src/AddIns/BackendBindings/Python/PythonBinding/Project/Src/PythonResolverContext.cs
  35. 2
      src/AddIns/BackendBindings/VBNetBinding/Project/Src/OptionPanels/ProjectImports.cs
  36. 1389
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/CompletionDataHelper.cs
  37. 145
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlCompilationUnit.cs
  38. 10
      src/AddIns/Debugger/Debugger.AddIn/Pads/Controls/TreeNodeWrapper.cs
  39. 29
      src/AddIns/Debugger/Debugger.AddIn/Pads/Controls/WatchListAutoCompleteCell.cs
  40. 17
      src/AddIns/Debugger/Debugger.AddIn/Pads/WatchPad.cs
  41. 25
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/Commands/FoldingCommands.cs
  42. 2
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.xaml
  43. 7
      src/AddIns/DisplayBindings/FormsDesigner/Project/Src/DesignerGenerator/AbstractDesignerGenerator.cs
  44. 2
      src/AddIns/DisplayBindings/FormsDesigner/Project/Src/Services/TypeResolutionService.cs
  45. 2
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.AddIn/Src/IdeChooseClassService.cs
  46. 2
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.AddIn/Src/MyTypeFinder.cs
  47. 3
      src/AddIns/DisplayBindings/XmlEditor/Project/Src/XmlTreeViewContainerControl.cs
  48. 5
      src/AddIns/DisplayBindings/XmlEditor/Project/Src/XmlView.cs
  49. 6
      src/AddIns/DisplayBindings/XmlEditor/Project/XmlEditor.addin
  50. BIN
      src/AddIns/Misc/PackageManagement/Packages/AvalonEdit.Sample/AvalonEdit.Sample.4.1.0.8000.nupkg
  51. 4
      src/AddIns/Misc/PackageManagement/Packages/AvalonEdit.Sample/AvalonEdit.Sample.nuspec
  52. BIN
      src/AddIns/Misc/PackageManagement/Packages/AvalonEdit/AvalonEdit.4.1.0.8000.nupkg
  53. BIN
      src/AddIns/Misc/PackageManagement/Packages/AvalonEdit/AvalonEdit.4.1.0.8000.symbols.nupkg
  54. 2
      src/AddIns/Misc/PackageManagement/Packages/AvalonEdit/AvalonEdit.nuspec
  55. 4
      src/AddIns/Misc/PackageManagement/Project/Src/EnvDTE/DTE.cs
  56. 10
      src/AddIns/Misc/PackageManagement/Test/Src/EnvDTE/DTETests.cs
  57. 6
      src/AddIns/Misc/SharpRefactoring/Project/Src/ContextActions/AddUsing.cs
  58. 4
      src/AddIns/Misc/SharpRefactoring/Project/Src/MenuItemFactories/ResolveAttribute.cs
  59. 2
      src/AddIns/Misc/SharpRefactoring/Project/Src/MenuItemFactories/ResolveExtensionMethod.cs
  60. 35
      src/Libraries/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.shfbproj
  61. 10
      src/Libraries/AvalonEdit/Documentation/Welcome.aml
  62. 3
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Caret.cs
  63. 35
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretNavigationCommandHandler.cs
  64. 9
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EmptySelection.cs
  65. 178
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs
  66. 125
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeSupport.cs
  67. 149
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/RectangleSelection.cs
  68. 10
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Selection.cs
  69. 14
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SimpleSelection.cs
  70. 8
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/DocumentHighlighter.cs
  71. 12
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingSpan.cs
  72. 146
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PowerShell.xshd
  73. 3
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Resources.cs
  74. 2
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XML-Mode.xshd
  75. 19
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XmlHighlightingDefinition.cs
  76. 5
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.csproj
  77. 17
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorOptions.cs
  78. 65
      src/Libraries/ICSharpCode.Decompiler/Ast/AstBuilder.cs
  79. 7
      src/Libraries/ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs
  80. 9
      src/Libraries/ICSharpCode.Decompiler/Ast/CommentStatement.cs
  81. 16
      src/Libraries/ICSharpCode.Decompiler/Ast/TextOutputFormatter.cs
  82. 2
      src/Libraries/ICSharpCode.Decompiler/Ast/Transforms/ConvertConstructorCallIntoInitializer.cs
  83. 4
      src/Libraries/ICSharpCode.Decompiler/Ast/Transforms/IntroduceUnsafeModifier.cs
  84. 2
      src/Libraries/ICSharpCode.Decompiler/Ast/Transforms/ReplaceMethodCallsWithOperators.cs
  85. 2
      src/Libraries/ICSharpCode.Decompiler/CecilExtensions.cs
  86. 23
      src/Libraries/ICSharpCode.Decompiler/DecompilerSettings.cs
  87. 11
      src/Libraries/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs
  88. 11
      src/Libraries/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs
  89. 36
      src/Libraries/ICSharpCode.Decompiler/ILAst/LoopsAndConditions.cs
  90. 25
      src/Libraries/ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs
  91. 4
      src/Libraries/ICSharpCode.Decompiler/Properties/AssemblyInfo.cs
  92. 81
      src/Libraries/ICSharpCode.Decompiler/Tests/ControlFlow.cs
  93. 55
      src/Libraries/ICSharpCode.Decompiler/Tests/Generics.cs
  94. 2
      src/Libraries/ICSharpCode.Decompiler/Tests/Helpers/RemoveCompilerAttribute.cs
  95. 12
      src/Libraries/ICSharpCode.Decompiler/Tests/ICSharpCode.Decompiler.Tests.csproj
  96. 51
      src/Libraries/ICSharpCode.Decompiler/Tests/IL/ILTests.cs
  97. 53
      src/Libraries/ICSharpCode.Decompiler/Tests/IL/SequenceOfNestedIfs.Output.cs
  98. BIN
      src/Libraries/ICSharpCode.Decompiler/Tests/IL/SequenceOfNestedIfs.dll
  99. 140
      src/Libraries/ICSharpCode.Decompiler/Tests/IL/SequenceOfNestedIfs.il
  100. 0
      src/Libraries/ICSharpCode.Decompiler/Tests/IL/StackTests.exe
  101. Some files were not shown because too many files have changed in this diff Show More

15
data/resources/StringResources.fr.resx

@ -4973,6 +4973,9 @@ Soit ils n'existent pas, soit le document Wix n'est pas pour WiX 3.0 et l'espace
<data name="MainWindow.Windows.Debug.LocalVariables.CopyToClipboard" xml:space="preserve"> <data name="MainWindow.Windows.Debug.LocalVariables.CopyToClipboard" xml:space="preserve">
<value>Copier la valeur dans le presse-papier</value> <value>Copier la valeur dans le presse-papier</value>
</data> </data>
<data name="MainWindow.Windows.Debug.LocalVariables.NameColumn" xml:space="preserve">
<value>Nom</value>
</data>
<data name="MainWindow.Windows.Debug.LocalVariables.NonPublicMembers" xml:space="preserve"> <data name="MainWindow.Windows.Debug.LocalVariables.NonPublicMembers" xml:space="preserve">
<value>Membres non publics</value> <value>Membres non publics</value>
</data> </data>
@ -4994,6 +4997,12 @@ Soit ils n'existent pas, soit le document Wix n'est pas pour WiX 3.0 et l'espace
<data name="MainWindow.Windows.Debug.LocalVariables.StaticMembers" xml:space="preserve"> <data name="MainWindow.Windows.Debug.LocalVariables.StaticMembers" xml:space="preserve">
<value>Membres statiques</value> <value>Membres statiques</value>
</data> </data>
<data name="MainWindow.Windows.Debug.LocalVariables.TypeColumn" xml:space="preserve">
<value>Type</value>
</data>
<data name="MainWindow.Windows.Debug.LocalVariables.ValueColumn" xml:space="preserve">
<value>Valeur</value>
</data>
<data name="MainWindow.Windows.Debug.MemoryPad" xml:space="preserve"> <data name="MainWindow.Windows.Debug.MemoryPad" xml:space="preserve">
<value>Mémoire</value> <value>Mémoire</value>
</data> </data>
@ -5369,6 +5378,9 @@ Soit ils n'existent pas, soit le document Wix n'est pas pour WiX 3.0 et l'espace
<data name="OpenFileTabEventHandler.FileContainingFolderInExplorer" xml:space="preserve"> <data name="OpenFileTabEventHandler.FileContainingFolderInExplorer" xml:space="preserve">
<value>Ouvrir le répertoire dans l'explorateur</value> <value>Ouvrir le répertoire dans l'explorateur</value>
</data> </data>
<data name="OpenFileTabEventHandler.OpenCommandPromptHere" xml:space="preserve">
<value>Ouvrir une invite de commande ici</value>
</data>
<data name="ProjectBrowser.Toolbar.CollapseAll" xml:space="preserve"> <data name="ProjectBrowser.Toolbar.CollapseAll" xml:space="preserve">
<value>Réduire tous les noeuds</value> <value>Réduire tous les noeuds</value>
</data> </data>
@ -5504,6 +5516,9 @@ Soit ils n'existent pas, soit le document Wix n'est pas pour WiX 3.0 et l'espace
<data name="ProjectComponent.ContextMenu.RunProject" xml:space="preserve"> <data name="ProjectComponent.ContextMenu.RunProject" xml:space="preserve">
<value>Lance&amp;r projet</value> <value>Lance&amp;r projet</value>
</data> </data>
<data name="ProjectComponent.ContextMenu.RunProjectWithoutDebugger" xml:space="preserve">
<value>Exécuter ce projet sans débogueur</value>
</data>
<data name="ProjectComponent.ContextMenu.SetAsStartupProject" xml:space="preserve"> <data name="ProjectComponent.ContextMenu.SetAsStartupProject" xml:space="preserve">
<value>Définir comme projet de dém&amp;arrage</value> <value>Définir comme projet de dém&amp;arrage</value>
</data> </data>

6
data/resources/StringResources.nl.resx

@ -5380,6 +5380,9 @@ Microsoft.Tools.WindowsInstallerXml.Extenties.NetFxCompiler, WixNetFxExtentie</v
<data name="OpenFileTabEventHandler.FileContainingFolderInExplorer" xml:space="preserve"> <data name="OpenFileTabEventHandler.FileContainingFolderInExplorer" xml:space="preserve">
<value>Open de document bevattende map in de Explorer</value> <value>Open de document bevattende map in de Explorer</value>
</data> </data>
<data name="OpenFileTabEventHandler.OpenCommandPromptHere" xml:space="preserve">
<value>Open hier de commando prompt</value>
</data>
<data name="ProjectBrowser.Toolbar.CollapseAll" xml:space="preserve"> <data name="ProjectBrowser.Toolbar.CollapseAll" xml:space="preserve">
<value>Alle knooppunten invouwen</value> <value>Alle knooppunten invouwen</value>
</data> </data>
@ -5515,6 +5518,9 @@ Microsoft.Tools.WindowsInstallerXml.Extenties.NetFxCompiler, WixNetFxExtentie</v
<data name="ProjectComponent.ContextMenu.RunProject" xml:space="preserve"> <data name="ProjectComponent.ContextMenu.RunProject" xml:space="preserve">
<value>P&amp;roject starten</value> <value>P&amp;roject starten</value>
</data> </data>
<data name="ProjectComponent.ContextMenu.RunProjectWithoutDebugger" xml:space="preserve">
<value>Project uitvoeren zonder foutopsporing</value>
</data>
<data name="ProjectComponent.ContextMenu.SetAsStartupProject" xml:space="preserve"> <data name="ProjectComponent.ContextMenu.SetAsStartupProject" xml:space="preserve">
<value>Als startproject instellen.</value> <value>Als startproject instellen.</value>
</data> </data>

BIN
data/templates/packages/Modernizr.1.7.nupkg

Binary file not shown.

BIN
data/templates/packages/Modernizr.2.5.3.nupkg

Binary file not shown.

BIN
data/templates/packages/jQuery.1.6.1.nupkg

Binary file not shown.

BIN
data/templates/packages/jQuery.1.7.2.nupkg

Binary file not shown.

8
data/templates/project/CSharp/MvcRazorProject.xpt

@ -273,8 +273,8 @@ Aliquam suscipit tellus vel nunc elementum fringilla.</p>
<head> <head>
<title>@ViewBag.Title</title> <title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css">
<script src="@Url.Content("~/Scripts/modernizer-1.7.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/modernizr-2.5.3.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
</head> </head>
<body> <body>
<div id="page"> <div id="page">
@ -300,8 +300,8 @@ Aliquam suscipit tellus vel nunc elementum fringilla.</p>
<File name="packages.config"> <File name="packages.config">
<![CDATA[<?xml version="1.0" encoding="utf-8"?> <![CDATA[<?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="jQuery" version="1.6.1" /> <package id="jQuery" version="1.7.2" />
<package id="Modernizr" version="1.7" /> <package id="Modernizr" version="2.5.3" />
</packages> </packages>
]]> ]]>
</File> </File>

8
data/templates/project/CSharp/MvcWebProject.xpt

@ -280,8 +280,8 @@ namespace ${StandardNamespace}
<head runat="server"> <head runat="server">
<title><asp:ContentPlaceHolder id="Title" runat="server"/></title> <title><asp:ContentPlaceHolder id="Title" runat="server"/></title>
<link href="<%: Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css"> <link href="<%: Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css">
<script src="<%: Url.Content("~/Scripts/modernizer-1.7.min.js") %>" type="text/javascript"></script> <script src="<%: Url.Content("~/Scripts/modernizr-2.5.3.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery-1.6.1.min.js") %>" type="text/javascript"></script> <script src="<%: Url.Content("~/Scripts/jquery-1.7.2.min.js") %>" type="text/javascript"></script>
</head> </head>
<body> <body>
<div id="page"> <div id="page">
@ -307,8 +307,8 @@ namespace ${StandardNamespace}
<File name="packages.config"> <File name="packages.config">
<![CDATA[<?xml version="1.0" encoding="utf-8"?> <![CDATA[<?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="jQuery" version="1.6.1" /> <package id="jQuery" version="1.7.2" />
<package id="Modernizr" version="1.7" /> <package id="Modernizr" version="2.5.3" />
</packages> </packages>
]]> ]]>
</File> </File>

8
data/templates/project/VB/MvcRazorProject.xpt

@ -265,8 +265,8 @@ Aliquam suscipit tellus vel nunc elementum fringilla.</p>
<head> <head>
<title>@ViewData("Title")</title> <title>@ViewData("Title")</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css">
<script src="@Url.Content("~/Scripts/modernizer-1.7.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/modernizr-2.5.3.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
</head> </head>
<body> <body>
<div id="page"> <div id="page">
@ -292,8 +292,8 @@ Aliquam suscipit tellus vel nunc elementum fringilla.</p>
<File name="packages.config"> <File name="packages.config">
<![CDATA[<?xml version="1.0" encoding="utf-8"?> <![CDATA[<?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="jQuery" version="1.6.1" /> <package id="jQuery" version="1.7.2" />
<package id="Modernizr" version="1.7" /> <package id="Modernizr" version="2.5.3" />
</packages> </packages>
]]> ]]>
</File> </File>

8
data/templates/project/VB/MvcWebProject.xpt

@ -272,8 +272,8 @@ End Class
<head runat="server"> <head runat="server">
<title><asp:ContentPlaceHolder id="Title" runat="server"/></title> <title><asp:ContentPlaceHolder id="Title" runat="server"/></title>
<link href="<%: Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css"> <link href="<%: Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css">
<script src="<%: Url.Content("~/Scripts/modernizer-1.7.min.js") %>" type="text/javascript"></script> <script src="<%: Url.Content("~/Scripts/modernizr-2.5.3.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery-1.6.1.min.js") %>" type="text/javascript"></script> <script src="<%: Url.Content("~/Scripts/jquery-1.7.2.min.js") %>" type="text/javascript"></script>
</head> </head>
<body> <body>
<div id="page"> <div id="page">
@ -299,8 +299,8 @@ End Class
<File name="packages.config"> <File name="packages.config">
<![CDATA[<?xml version="1.0" encoding="utf-8"?> <![CDATA[<?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="jQuery" version="1.6.1" /> <package id="jQuery" version="1.7.2" />
<package id="Modernizr" version="1.7" /> <package id="Modernizr" version="2.5.3" />
</packages> </packages>
]]> ]]>
</File> </File>

69
samples/MSTest/MSTest.SharpDevelop.Tests/MSTest.SharpDevelop.Tests.csproj

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{51D56190-67B7-4A49-BA0A-24010460CCC6}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<OutputType>Library</OutputType>
<RootNamespace>MSTest.SharpDevelop.Tests</RootNamespace>
<AssemblyName>MSTest.SharpDevelop.Tests</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="ICSharpCode.Core">
<HintPath>..\..\..\bin\ICSharpCode.Core.dll</HintPath>
</Reference>
<Reference Include="ICSharpCode.SharpDevelop">
<HintPath>..\..\..\bin\ICSharpCode.SharpDevelop.dll</HintPath>
</Reference>
<Reference Include="ICSharpCode.SharpDevelop.Dom">
<HintPath>..\..\..\bin\ICSharpCode.SharpDevelop.Dom.dll</HintPath>
</Reference>
<Reference Include="nunit.framework">
<HintPath>..\..\..\src\Tools\NUnit\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks">
<HintPath>..\..\..\src\Libraries\RhinoMocks\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="UnitTesting">
<HintPath>..\..\..\AddIns\Analysis\UnitTesting\UnitTesting.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="MSTestFrameworkTests.cs" />
<Compile Include="MSTestResultsTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MSTest.SharpDevelop\MSTest.SharpDevelop.csproj">
<Project>{8DF3A610-47F9-4448-B455-952BD57CB5CC}</Project>
<Name>MSTest.SharpDevelop</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
</Project>

338
samples/MSTest/MSTest.SharpDevelop.Tests/MSTestFrameworkTests.cs

@ -0,0 +1,338 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using ICSharpCode.MSTest;
using ICSharpCode.SharpDevelop.Dom;
using ICSharpCode.SharpDevelop.Project;
using ICSharpCode.UnitTesting;
using NUnit.Framework;
using Rhino.Mocks;
namespace MSTest.SharpDevelop.Tests
{
[TestFixture]
public class MSTestFrameworkTests
{
MSTestFramework testFramework;
IProject fakeProject;
[SetUp]
public void Init()
{
testFramework = new MSTestFramework();
fakeProject = MockRepository.GenerateStub<IProject>();
fakeProject.Stub(p => p.SyncRoot).Return(fakeProject);
}
void AddReferencesToProject(params string[] referenceNames)
{
List<ProjectItem> projectItems = referenceNames
.Select(name => new ReferenceProjectItem(fakeProject, name) as ProjectItem)
.ToList();
AddItemsToProject(projectItems);
}
void AddItemsToProject(List<ProjectItem> projectItems)
{
fakeProject
.Stub(project => project.Items)
.Return(new ReadOnlyCollection<ProjectItem>(projectItems));
}
void AddFileAndReferenceToProject(string fileName, string reference)
{
var projectItems = new List<ProjectItem>();
projectItems.Add(new FileProjectItem(fakeProject, ItemType.Compile, fileName));
projectItems.Add(new ReferenceProjectItem(fakeProject, reference));
AddItemsToProject(projectItems);
}
void NoItemsInProject()
{
AddReferencesToProject();
}
IClass CreateClassWithoutAnyAttributes()
{
IClass fakeClass = MockRepository.GenerateStub<IClass>();
AddAttributesToClass(fakeClass, new List<IAttribute>());
return fakeClass;
}
void AddAttributesToClass(IClass fakeClass, List<IAttribute> attributes)
{
fakeClass.Stub(c => c.Attributes).Return(attributes);
}
IClass CreateClassWithAttributes(params string[] attributeNames)
{
IClass fakeClass = MockRepository.GenerateStub<IClass>();
List<IAttribute> attributes = CreateAttributes(attributeNames);
AddAttributesToClass(fakeClass, attributes);
return fakeClass;
}
List<IAttribute> CreateAttributes(params string[] attributeNames)
{
return attributeNames.Select(name => CreateAttribute(name)).ToList();
}
IAttribute CreateAttribute(string name)
{
IReturnType returnType = MockRepository.GenerateStub<IReturnType>();
returnType.Stub(t => t.FullyQualifiedName).Return(name);
IAttribute attribute = MockRepository.GenerateStub<IAttribute>();
attribute.Stub(a => a.AttributeType).Return(returnType);
return attribute;
}
void MakeClassAbstract(IClass fakeClass)
{
fakeClass.Stub(c => c.IsAbstract).Return(true);
}
IMethod CreateMethodWithoutAnyAttributes()
{
IMethod fakeMethod = MockRepository.GenerateStub<IMethod>();
AddAttributesToMethod(fakeMethod, new List<IAttribute>());
return fakeMethod;
}
IMethod CreateMethodWithAttributes(params string[] attributeNames)
{
IMethod fakeMethod = MockRepository.GenerateStub<IMethod>();
List<IAttribute> attributes = CreateAttributes(attributeNames);
AddAttributesToMethod(fakeMethod, attributes);
return fakeMethod;
}
void AddAttributesToMethod(IMethod method, List<IAttribute> attributes)
{
method.Stub(m => m.Attributes).Return(attributes);
}
List<TestMember> GetTestMembersFor(IClass fakeClass)
{
return testFramework.GetTestMembersFor(fakeClass).ToList();
}
void AddMethodsToClass(IClass fakeClass, List<IMethod> methods)
{
fakeClass.Stub(c => c.Methods).Return(methods);
}
[Test]
public void IsTestProject_NullProject_ReturnsFalse()
{
bool result = testFramework.IsTestProject(null);
Assert.IsFalse(result);
}
[Test]
public void IsTestProject_ProjectWithMSTestAssemblyReference_ReturnsTrue()
{
AddReferencesToProject("System", "Microsoft.VisualStudio.QualityTools.UnitTestFramework");
bool result = testFramework.IsTestProject(fakeProject);
Assert.IsTrue(result);
}
[Test]
public void IsTestProject_ProjectWithoutMSTestAssemblyReference_ReturnsFalse()
{
NoItemsInProject();
bool result = testFramework.IsTestProject(fakeProject);
Assert.IsFalse(result);
}
[Test]
public void IsTestProject_ProjectWithMSTestAssemblyReferenceInUpperCase_ReturnsTrue()
{
AddReferencesToProject("MICROSOFT.VISUALSTUDIO.QUALITYTOOLS.UNITTESTFRAMEWORK");
bool result = testFramework.IsTestProject(fakeProject);
Assert.IsTrue(result);
}
[Test]
public void IsTestProject_ProjectWithMSTestAssemblyReferenceAndFileProjectItem_ReturnsTrue()
{
AddFileAndReferenceToProject("test.cs", "Microsoft.VisualStudio.QualityTools.UnitTestFramework");
bool result = testFramework.IsTestProject(fakeProject);
Assert.IsTrue(result);
}
[Test]
public void IsTestProject_ProjectWithMSTestAssemblyReferenceUsingFullName_ReturnsTrue()
{
AddReferencesToProject("Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=2.5.3.9345, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77");
bool result = testFramework.IsTestProject(fakeProject);
Assert.IsTrue(result);
}
[Test]
public void IsTestClass_ClassHasNoAttributes_ReturnsFalse()
{
IClass fakeClass = CreateClassWithoutAnyAttributes();
bool result = testFramework.IsTestClass(fakeClass);
Assert.IsFalse(result);
}
[Test]
public void IsTestClass_ClassHasTestFixtureAttributeMissingAttributePart_ReturnsTrue()
{
IClass fakeClass = CreateClassWithAttributes("TestClass");
bool result = testFramework.IsTestClass(fakeClass);
Assert.IsTrue(result);
}
[Test]
public void IsTestClass_ClassHasTestClassAttributeAndIsAbstract_ReturnsFalse()
{
IClass fakeClass = CreateClassWithAttributes("TestClass");
MakeClassAbstract(fakeClass);
bool result = testFramework.IsTestClass(fakeClass);
Assert.IsFalse(result);
}
[Test]
public void IsTestClass_ClassHasTestClassAttributeIncludingAttributePart_ReturnsTrue()
{
IClass fakeClass = CreateClassWithAttributes("TestClassAttribute");
bool result = testFramework.IsTestClass(fakeClass);
Assert.IsTrue(result);
}
[Test]
public void IsTestClass_ClassHasFullyQualifiedMSTestClassAttribute_ReturnsTrue()
{
IClass fakeClass = CreateClassWithAttributes("Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute");
bool result = testFramework.IsTestClass(fakeClass);
Assert.IsTrue(result);
}
[Test]
public void IsTestClass_ClassIsNull_ReturnsFalse()
{
bool result = testFramework.IsTestClass(null);
Assert.IsFalse(result);
}
[Test]
public void IsTestMember_MethodHasNoAttributes_ReturnsFalse()
{
IMethod method = CreateMethodWithoutAnyAttributes();
bool result = testFramework.IsTestMember(method);
Assert.IsFalse(result);
}
[Test]
public void IsTestMember_MethodHasTestMethodAttributeWithoutAttributePart_ReturnsTrue()
{
IMethod method = CreateMethodWithAttributes("TestMethod");
bool result = testFramework.IsTestMember(method);
Assert.IsTrue(result);
}
[Test]
public void IsTestMember_MethodHasTestMethodAttributeAttribute_ReturnsTrue()
{
IMethod method = CreateMethodWithAttributes("TestMethodAttribute");
bool result = testFramework.IsTestMember(method);
Assert.IsTrue(result);
}
[Test]
public void IsTestMember_MethodHasFullyQualifiedMSTestTestMethodAttribute_ReturnsTrue()
{
IMethod method = CreateMethodWithAttributes("Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute");
bool result = testFramework.IsTestMember(method);
Assert.IsTrue(result);
}
[Test]
public void IsTestMember_MethodIsNull_ReturnsFalse()
{
bool result = testFramework.IsTestMember(null);
Assert.IsFalse(result);
}
[Test]
public void IsTestMember_MemberNotMethod_ReturnsFalse()
{
IMember member = MockRepository.GenerateStub<IMember>();
bool result = testFramework.IsTestMember(member);
Assert.IsFalse(result);
}
[Test]
public void GetTestMembersFor_ClassHasNoMethods_ReturnsFalse()
{
IClass fakeClass = CreateClassWithAttributes("TestClass");
AddMethodsToClass(fakeClass, new List<IMethod>());
List<TestMember> testMembers = GetTestMembersFor(fakeClass);
Assert.AreEqual(0, testMembers.Count);
}
[Test]
public void GetTestMembersFor_ClassHasTwoMethodsAndSecondOneIsTestMethod_ReturnsSecondTestMethodOnly()
{
IClass fakeClass = CreateClassWithAttributes("TestClass");
var methods = new List<IMethod>();
methods.Add(CreateMethodWithoutAnyAttributes());
IMethod testMethod = CreateMethodWithAttributes("TestMethod");
methods.Add(testMethod);
AddMethodsToClass(fakeClass, methods);
List<TestMember> testMembers = GetTestMembersFor(fakeClass);
Assert.AreEqual(1, testMembers.Count);
Assert.AreEqual(testMethod, testMembers[0].Member);
}
}
}

184
samples/MSTest/MSTest.SharpDevelop.Tests/MSTestResultsTests.cs

@ -0,0 +1,184 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using ICSharpCode.MSTest;
using ICSharpCode.SharpDevelop.Dom;
using ICSharpCode.UnitTesting;
using NUnit.Framework;
namespace MSTest.SharpDevelop.Tests
{
[TestFixture]
public class MSTestResultsTests
{
MSTestResults testResults;
void CreateMSTestResults(string xml)
{
using (var reader = new XmlTextReader(new StringReader(xml))) {
testResults = new MSTestResults(reader);
}
}
void AssertTestResultsAreEqual(TestResult[] expectedResults)
{
List<string> expectedResultsAsString = ConvertToStrings(expectedResults);
List<string> actualResultsAsString = ConvertToStrings(testResults);
CollectionAssert.AreEqual(expectedResultsAsString, actualResultsAsString);
}
List<string> ConvertToStrings(IEnumerable<TestResult> results)
{
return results.Select(
result => String.Format(
"Name: {0}, Result: {1}, Message: '{2}', StackTrace: '{3}', StackPosition: {4}",
result.Name,
result.ResultType,
result.Message,
result.StackTrace,
result.StackTraceFilePosition))
.ToList();
}
[Test]
public void Results_OneClassWithTwoPassingTestMethods_ReturnsTwoResults()
{
CreateMSTestResults(oneClassWithTwoPassingTestMethods);
var expectedResults = new TestResult[] {
new TestResult("FooTest.UnitTest1.TestMethod1") {
ResultType = TestResultType.Success
},
new TestResult("FooTest.UnitTest1.TestMethod2") {
ResultType = TestResultType.Success
},
};
AssertTestResultsAreEqual(expectedResults);
}
string oneClassWithTwoPassingTestMethods =
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<TestRun id=""13473da1-70ea-422c-86a5-3b5d04610561"" name=""FEYNMAN 2012-05-06 11:02:13"" runUser=""Feynman\Matt"" xmlns=""http://microsoft.com/schemas/VisualStudio/TeamTest/2010"">
<TestSettings name=""Local"" id=""1af0c4fe-35c7-49e5-b22a-40677255db56"">
<Description>These are default test settings for a local test run.</Description>
<Deployment runDeploymentRoot=""FEYNMAN 2012-05-06 11_02_13"">
<DeploymentItem filename=""T4Scaffolding.Test\ExampleScripts\"" />
</Deployment>
<Execution>
<TestTypeSpecific>
<UnitTestRunConfig testTypeId=""13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"">
<AssemblyResolution>
<TestDirectory useLoadContext=""true"" />
</AssemblyResolution>
</UnitTestRunConfig>
<WebTestRunConfiguration testTypeId=""4e7599fa-5ecb-43e9-a887-cd63cf72d207"">
<Browser name=""Internet Explorer 7.0"">
<Headers>
<Header name=""User-Agent"" value=""Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"" />
<Header name=""Accept"" value=""*/*"" />
<Header name=""Accept-Language"" value=""{{$IEAcceptLanguage}}"" />
<Header name=""Accept-Encoding"" value=""GZIP"" />
</Headers>
</Browser>
</WebTestRunConfiguration>
</TestTypeSpecific>
<AgentRule name=""LocalMachineDefaultRole"">
</AgentRule>
</Execution>
</TestSettings>
<Times creation=""2012-05-06T11:02:13.0655060+01:00"" queuing=""2012-05-06T11:02:16.0845060+01:00"" start=""2012-05-06T11:02:16.4355060+01:00"" finish=""2012-05-06T11:02:17.8915060+01:00"" />
<ResultSummary outcome=""Completed"">
<Counters total=""2"" executed=""2"" passed=""2"" error=""0"" failed=""0"" timeout=""0"" aborted=""0"" inconclusive=""0"" passedButRunAborted=""0"" notRunnable=""0"" notExecuted=""0"" disconnected=""0"" warning=""0"" completed=""0"" inProgress=""0"" pending=""0"" />
</ResultSummary>
<TestDefinitions>
<UnitTest name=""TestMethod2"" storage=""d:\temp\test\mvcscaffolding_31fa7ea49b52\footest\bin\debug\footest.dll"" id=""760d70dc-fcd4-bd05-26dd-50b565053466"">
<Execution id=""4d09aff0-ba01-4c01-9c3c-dd6475e89ef2"" />
<TestMethod codeBase=""D:/projects/FooTest/bin/Debug/FooTest.DLL"" adapterTypeName=""Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" className=""FooTest.UnitTest1, FooTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"" name=""TestMethod2"" />
</UnitTest>
<UnitTest name=""TestMethod1"" storage=""d:\temp\test\mvcscaffolding_31fa7ea49b52\footest\bin\debug\footest.dll"" id=""752967dd-f45f-65ac-ca4a-dcd30f56a25a"">
<Execution id=""ba931d00-d381-43c3-b0f9-f4cf37015438"" />
<TestMethod codeBase=""D:/projects/FooTest/bin/Debug/FooTest.DLL"" adapterTypeName=""Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" className=""FooTest.UnitTest1, FooTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"" name=""TestMethod1"" />
</UnitTest>
</TestDefinitions>
<TestLists>
<TestList name=""Results Not in a List"" id=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" />
<TestList name=""All Loaded Results"" id=""19431567-8539-422a-85d7-44ee4e166bda"" />
</TestLists>
<TestEntries>
<TestEntry testId=""752967dd-f45f-65ac-ca4a-dcd30f56a25a"" executionId=""ba931d00-d381-43c3-b0f9-f4cf37015438"" testListId=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" />
<TestEntry testId=""760d70dc-fcd4-bd05-26dd-50b565053466"" executionId=""4d09aff0-ba01-4c01-9c3c-dd6475e89ef2"" testListId=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" />
</TestEntries>
<Results>
<UnitTestResult executionId=""ba931d00-d381-43c3-b0f9-f4cf37015438"" testId=""752967dd-f45f-65ac-ca4a-dcd30f56a25a"" testName=""TestMethod1"" computerName=""FEYNMAN"" duration=""00:00:00.0501283"" startTime=""2012-05-06T11:02:16.5755060+01:00"" endTime=""2012-05-06T11:02:17.7465060+01:00"" testType=""13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"" outcome=""Passed"" testListId=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" relativeResultsDirectory=""ba931d00-d381-43c3-b0f9-f4cf37015438"">
</UnitTestResult>
<UnitTestResult executionId=""4d09aff0-ba01-4c01-9c3c-dd6475e89ef2"" testId=""760d70dc-fcd4-bd05-26dd-50b565053466"" testName=""TestMethod2"" computerName=""FEYNMAN"" duration=""00:00:00.0018331"" startTime=""2012-05-06T11:02:17.7655060+01:00"" endTime=""2012-05-06T11:02:17.7785060+01:00"" testType=""13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"" outcome=""Passed"" testListId=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" relativeResultsDirectory=""4d09aff0-ba01-4c01-9c3c-dd6475e89ef2"">
</UnitTestResult>
</Results>
</TestRun>";
[Test]
public void Results_OneTestMethodThrowsException_ReturnsOneErrorResultWithStackTrace()
{
CreateMSTestResults(oneTestMethodThrowsException);
var expectedResults = new TestResult[] {
new TestResult("FooTest.UnitTest1.TestMethod1") {
ResultType = TestResultType.Failure,
Message = "System.ApplicationException: asdfafds",
StackTrace = " at FooTest.UnitTest1.TestMethod1() in d:\\projects\\FooTest\\UnitTest1.cs:line 21\r\n",
StackTraceFilePosition = new FilePosition(@"d:\projects\FooTest\UnitTest1.cs", 21, 1)
}
};
AssertTestResultsAreEqual(expectedResults);
}
string oneTestMethodThrowsException =
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<TestRun id=""7c0b0a20-13c6-4c28-b74c-e29c271f2ec4"" name=""FEYNMAN 2012-05-06 13:07:05"" runUser=""Feynman\Matt"" xmlns=""http://microsoft.com/schemas/VisualStudio/TeamTest/2010"">
<TestSettings name=""Default Test Settings"" id=""03cf0958-a7e3-4b25-b98b-435f01359ee1"">
<Execution>
<TestTypeSpecific />
<AgentRule name=""Execution Agents"">
</AgentRule>
</Execution>
<Deployment runDeploymentRoot=""FEYNMAN 2012-05-06 13_07_05"" />
</TestSettings>
<Times creation=""2012-05-06T13:07:05.9187060+01:00"" queuing=""2012-05-06T13:07:06.6519060+01:00"" start=""2012-05-06T13:07:06.8235060+01:00"" finish=""2012-05-06T13:07:08.0403060+01:00"" />
<ResultSummary outcome=""Failed"">
<Counters total=""1"" executed=""1"" passed=""0"" error=""0"" failed=""1"" timeout=""0"" aborted=""0"" inconclusive=""0"" passedButRunAborted=""0"" notRunnable=""0"" notExecuted=""0"" disconnected=""0"" warning=""0"" completed=""0"" inProgress=""0"" pending=""0"" />
</ResultSummary>
<TestDefinitions>
<UnitTest name=""TestMethod1"" storage=""d:\projects\footest\bin\debug\footest.dll"" id=""752967dd-f45f-65ac-ca4a-dcd30f56a25a"">
<Execution id=""c147e8ae-7ee7-4f28-9db3-a708e350c68d"" />
<TestMethod codeBase=""D:/projects/FooTest/bin/Debug/FooTest.DLL"" adapterTypeName=""Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" className=""FooTest.UnitTest1, FooTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"" name=""TestMethod1"" />
</UnitTest>
</TestDefinitions>
<TestLists>
<TestList name=""Results Not in a List"" id=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" />
<TestList name=""All Loaded Results"" id=""19431567-8539-422a-85d7-44ee4e166bda"" />
</TestLists>
<TestEntries>
<TestEntry testId=""752967dd-f45f-65ac-ca4a-dcd30f56a25a"" executionId=""c147e8ae-7ee7-4f28-9db3-a708e350c68d"" testListId=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" />
</TestEntries>
<Results>
<UnitTestResult executionId=""c147e8ae-7ee7-4f28-9db3-a708e350c68d"" testId=""752967dd-f45f-65ac-ca4a-dcd30f56a25a"" testName=""TestMethod1"" computerName=""FEYNMAN"" duration=""00:00:00.0404760"" startTime=""2012-05-06T13:07:06.9015060+01:00"" endTime=""2012-05-06T13:07:07.8375060+01:00"" testType=""13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"" outcome=""Failed"" testListId=""8c84fa94-04c1-424b-9868-57a2d4851a1d"" relativeResultsDirectory=""c147e8ae-7ee7-4f28-9db3-a708e350c68d"">
<Output>
<ErrorInfo>
<Message>Test method FooTest.UnitTest1.TestMethod1 threw exception:
System.ApplicationException: asdfafds</Message>
<StackTrace> at FooTest.UnitTest1.TestMethod1() in d:\projects\FooTest\UnitTest1.cs:line 21
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
</Results>
</TestRun>";
}
}

31
samples/MSTest/MSTest.SharpDevelop.Tests/Properties/AssemblyInfo.cs

@ -0,0 +1,31 @@
#region Using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSTest.SharpDevelop.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MSTest.SharpDevelop.Tests")]
[assembly: AssemblyCopyright("Copyright 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(false)]
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0")]

24
samples/MSTest/MSTest.SharpDevelop.sln

@ -0,0 +1,24 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
# SharpDevelop 4.2.0.8749-Beta 2
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SharpDevelop", "MSTest.SharpDevelop\MSTest.SharpDevelop.csproj", "{8DF3A610-47F9-4448-B455-952BD57CB5CC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSTest.SharpDevelop.Tests", "MSTest.SharpDevelop.Tests\MSTest.SharpDevelop.Tests.csproj", "{51D56190-67B7-4A49-BA0A-24010460CCC6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8DF3A610-47F9-4448-B455-952BD57CB5CC}.Debug|x86.Build.0 = Debug|x86
{8DF3A610-47F9-4448-B455-952BD57CB5CC}.Debug|x86.ActiveCfg = Debug|x86
{8DF3A610-47F9-4448-B455-952BD57CB5CC}.Release|x86.Build.0 = Release|x86
{8DF3A610-47F9-4448-B455-952BD57CB5CC}.Release|x86.ActiveCfg = Release|x86
{51D56190-67B7-4A49-BA0A-24010460CCC6}.Debug|x86.Build.0 = Debug|x86
{51D56190-67B7-4A49-BA0A-24010460CCC6}.Debug|x86.ActiveCfg = Debug|x86
{51D56190-67B7-4A49-BA0A-24010460CCC6}.Release|x86.Build.0 = Release|x86
{51D56190-67B7-4A49-BA0A-24010460CCC6}.Release|x86.ActiveCfg = Release|x86
EndGlobalSection
EndGlobal

103
samples/MSTest/MSTest.SharpDevelop/MSTest.SharpDevelop.csproj

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{8DF3A610-47F9-4448-B455-952BD57CB5CC}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<OutputType>Library</OutputType>
<RootNamespace>ICSharpCode.MSTest</RootNamespace>
<AssemblyName>MSTest.SharpDevelop</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder>
<OutputPath>..\..\..\AddIns\Samples\MSTest</OutputPath>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="ICSharpCode.Core">
<HintPath>..\..\..\bin\ICSharpCode.Core.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.Core.Presentation">
<HintPath>..\..\..\bin\ICSharpCode.Core.Presentation.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.SharpDevelop">
<HintPath>..\..\..\bin\ICSharpCode.SharpDevelop.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.SharpDevelop.Dom">
<HintPath>..\..\..\bin\ICSharpCode.SharpDevelop.Dom.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.SharpDevelop.Widgets">
<HintPath>..\..\..\bin\ICSharpCode.SharpDevelop.Widgets.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="UnitTesting">
<HintPath>..\..\..\AddIns\Analysis\UnitTesting\UnitTesting.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="MSTestApplication.cs" />
<Compile Include="MSTestApplicationCommandLine.cs" />
<Compile Include="MSTestDebugger.cs" />
<Compile Include="MSTestFramework.cs" />
<Compile Include="MSTestOptions.cs" />
<Compile Include="MSTestOptionsPanel.xaml.cs">
<DependentUpon>MSTestOptionsPanel.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MSTestQualifiedClassName.cs" />
<Compile Include="MSTestResult.cs" />
<Compile Include="MSTestResults.cs" />
<Compile Include="MSTestResultsFileName.cs" />
<Compile Include="MSTestRunner.cs" />
<Compile Include="ProjectItemExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="MSTest.addin">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Page Include="MSTestOptionsPanel.xaml" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
</Project>

30
samples/MSTest/MSTest.SharpDevelop/MSTest.addin

@ -0,0 +1,30 @@
<AddIn
name="MSTest"
author="Matt Ward"
copyright="prj:///doc/copyright.txt"
description="MSTest support">
<Manifest>
<Identity name="ICSharpCode.MSTest"/>
</Manifest>
<Runtime>
<Import assembly=":ICSharpCode.SharpDevelop"/>
<Import assembly="$ICSharpCode.UnitTesting/UnitTesting.dll"/>
<Import assembly="MSTest.SharpDevelop.dll"/>
</Runtime>
<Path name="/SharpDevelop/UnitTesting/TestFrameworks">
<TestFramework
id="mstest"
class="ICSharpCode.MSTest.MSTestFramework"
supportedProjects=".csproj"/>
</Path>
<Path name="/SharpDevelop/Dialogs/OptionsDialog/ToolsOptions">
<OptionPanel
id="MSTestOptionsPanel"
label="MS Test"
class="ICSharpCode.MSTest.MSTestOptionsPanel"/>
</Path>
</AddIn>

46
samples/MSTest/MSTest.SharpDevelop/MSTestApplication.cs

@ -0,0 +1,46 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Diagnostics;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestApplication
{
SelectedTests selectedTests;
string resultsFileName;
public MSTestApplication(SelectedTests selectedTests, string resultsFileName)
{
this.selectedTests = selectedTests;
this.resultsFileName = resultsFileName;
GetProcessStartInfo();
}
void GetProcessStartInfo()
{
ProcessStartInfo = new ProcessStartInfo(MSTestOptions.MSTestPath, GetCommandLine());
}
string GetCommandLine()
{
var commandLine = new MSTestApplicationCommandLine();
commandLine.AppendQuoted("testcontainer", selectedTests.Project.OutputAssemblyFullPath);
commandLine.AppendQuoted("resultsfile", resultsFileName);
commandLine.Append("detail", "errorstacktrace");
if (selectedTests.NamespaceFilter != null) {
commandLine.Append("test", selectedTests.NamespaceFilter);
} else if (selectedTests.Member != null) {
commandLine.Append("test", selectedTests.Member.FullyQualifiedName);
} else if (selectedTests.Class != null) {
commandLine.Append("test", selectedTests.Class.FullyQualifiedName);
}
return commandLine.ToString();
}
public ProcessStartInfo ProcessStartInfo { get; private set; }
}
}

37
samples/MSTest/MSTest.SharpDevelop/MSTestApplicationCommandLine.cs

@ -0,0 +1,37 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Text;
namespace ICSharpCode.MSTest
{
public class MSTestApplicationCommandLine
{
StringBuilder commandLine = new StringBuilder();
public MSTestApplicationCommandLine()
{
}
public void Append(string argument, string value)
{
AppendFormat("/{0}:{1} ", argument, value);
}
public void AppendQuoted(string argument, string value)
{
AppendFormat("/{0}:\"{1}\" ", argument, value);
}
void AppendFormat(string format, string argument, string value)
{
commandLine.AppendFormat(format, argument, value);
}
public override string ToString()
{
return commandLine.ToString();
}
}
}

134
samples/MSTest/MSTest.SharpDevelop/MSTestDebugger.cs

@ -0,0 +1,134 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Diagnostics;
using System.IO;
using ICSharpCode.SharpDevelop.Debugging;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestDebugger : TestRunnerBase
{
IUnitTestDebuggerService debuggerService;
IUnitTestMessageService messageService;
IDebugger debugger;
string resultsFileName;
public MSTestDebugger()
: this(
new UnitTestDebuggerService(),
new UnitTestMessageService())
{
}
public MSTestDebugger(
IUnitTestDebuggerService debuggerService,
IUnitTestMessageService messageService)
{
this.debuggerService = debuggerService;
this.messageService = messageService;
this.debugger = debuggerService.CurrentDebugger;
}
public override void Start(SelectedTests selectedTests)
{
ProcessStartInfo startInfo = GetProcessStartInfo(selectedTests);
if (IsDebuggerRunning) {
if (CanStopDebugging()) {
debugger.Stop();
Start(startInfo);
}
} else {
Start(startInfo);
}
}
protected override ProcessStartInfo GetProcessStartInfo(SelectedTests selectedTests)
{
resultsFileName = new MSTestResultsFileName(selectedTests).FileName;
CreateDirectoryForResultsFile();
var mstestApplication = new MSTestApplication(selectedTests, resultsFileName);
return mstestApplication.ProcessStartInfo;
}
public bool IsDebuggerRunning {
get { return debuggerService.IsDebuggerLoaded && debugger.IsDebugging; }
}
bool CanStopDebugging()
{
string question = "${res:XML.MainMenu.RunMenu.Compile.StopDebuggingQuestion}";
string caption = "${res:XML.MainMenu.RunMenu.Compile.StopDebuggingTitle}";
return messageService.AskQuestion(question, caption);
}
void CreateDirectoryForResultsFile()
{
string path = Path.GetDirectoryName(resultsFileName);
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
}
void Start(ProcessStartInfo startInfo)
{
StartDebugger(startInfo);
}
void StartDebugger(ProcessStartInfo startInfo)
{
LogCommandLine(startInfo);
bool running = false;
debugger.DebugStopped += DebugStopped;
try {
debugger.Start(startInfo);
running = true;
} finally {
if (!running) {
debugger.DebugStopped -= DebugStopped;
}
}
}
void DebugStopped(object source, EventArgs e)
{
debugger.DebugStopped -= DebugStopped;
if (File.Exists(resultsFileName)) {
var testResults = new MSTestResults(resultsFileName);
var workbench = new UnitTestWorkbench();
workbench.SafeThreadAsyncCall(() => UpdateTestResults(testResults));
} else {
messageService.ShowFormattedErrorMessage("Unable to find test results file: '{0}'.", resultsFileName);
OnAllTestsFinished(source, e);
}
}
void UpdateTestResults(MSTestResults testResults)
{
foreach (TestResult result in testResults) {
OnTestFinished(this, new TestFinishedEventArgs(result));
}
OnAllTestsFinished(this, new EventArgs());
}
public override void Stop()
{
if (debugger.IsDebugging) {
debugger.Stop();
}
}
public override void Dispose()
{
Stop();
try {
File.Delete(resultsFileName);
} catch { }
}
}
}

109
samples/MSTest/MSTest.SharpDevelop/MSTestFramework.cs

@ -0,0 +1,109 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.SharpDevelop.Dom;
using ICSharpCode.SharpDevelop.Project;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestFramework : ITestFramework
{
public bool IsBuildNeededBeforeTestRun {
get { return true; }
}
public bool IsTestMember(IMember member)
{
var method = member as IMethod;
if (method == null)
return false;
return IsTestMethod(method);
}
bool IsTestMethod(IMethod method)
{
foreach (IAttribute attribute in method.Attributes) {
if (IsMSTestMethodAttribute(attribute)) {
return true;
}
}
return false;
}
bool IsMSTestMethodAttribute(IAttribute attribute)
{
return IsMSTestMethodAttribute(attribute.AttributeType.FullyQualifiedName);
}
bool IsMSTestMethodAttribute(string name)
{
return
name == "TestMethod" ||
name == "TestMethodAttribute" ||
name == "Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute";
}
public bool IsTestClass(IClass c)
{
if ((c == null) || (c.IsAbstract))
return false;
foreach (IAttribute attribute in c.Attributes) {
if (IsMSTestClassAttribute(attribute)) {
return true;
}
}
return false;
}
bool IsMSTestClassAttribute(IAttribute attribute)
{
return IsMSTestClassAttribute(attribute.AttributeType.FullyQualifiedName);
}
bool IsMSTestClassAttribute(string name)
{
return
name == "TestClass" ||
name == "TestClassAttribute" ||
name == "Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute";
}
public bool IsTestProject(IProject project)
{
if (project == null)
return false;
foreach (ProjectItem item in project.Items) {
if (item.IsMSTestAssemblyReference()) {
return true;
}
}
return false;
}
public IEnumerable<TestMember> GetTestMembersFor(IClass c)
{
return c.Methods
.Where(IsTestMethod)
.Select(method => new TestMember(method));
}
public ITestRunner CreateTestRunner()
{
return new MSTestRunner();
}
public ITestRunner CreateTestDebugger()
{
return new MSTestDebugger();
}
}
}

26
samples/MSTest/MSTest.SharpDevelop/MSTestOptions.cs

@ -0,0 +1,26 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.IO;
using ICSharpCode.Core;
namespace ICSharpCode.MSTest
{
public static class MSTestOptions
{
static Properties properties = PropertyService.Get("MSTestOptions", new Properties());
public static string MSTestPath {
get { return properties.Get<string>("MSTestPath", GetDefaultMSTestPath()); }
set { properties.Set("MSTestPath", value); }
}
static string GetDefaultMSTestPath()
{
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
@"Microsoft Visual Studio 10.0\Common7\IDE\mstest.exe");
}
}
}

32
samples/MSTest/MSTest.SharpDevelop/MSTestOptionsPanel.xaml

@ -0,0 +1,32 @@
<gui:OptionPanel
x:Class="ICSharpCode.MSTest.MSTestOptionsPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:core="http://icsharpcode.net/sharpdevelop/core"
xmlns:sd="clr-namespace:ICSharpCode.SharpDevelop"
xmlns:gui="clr-namespace:ICSharpCode.SharpDevelop.Gui;assembly=ICSharpCode.SharpDevelop"
xmlns:widgets="http://icsharpcode.net/sharpdevelop/widgets"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ICSharpCode.SharpDevelop.Gui.OptionPanels">
<StackPanel>
<GroupBox Header="MS Test">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Content="Path:"/>
<TextBox
Grid.Column="1"
Text="{Binding MSTestPath}"/>
<Button
Grid.Column="2"
Content="..."
Command="{Binding BrowseCommand}"
Padding="4, 0"
Margin="4,0"/>
</Grid>
</GroupBox>
</StackPanel>
</gui:OptionPanel>

64
samples/MSTest/MSTest.SharpDevelop/MSTestOptionsPanel.xaml.cs

@ -0,0 +1,64 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Input;
using ICSharpCode.SharpDevelop.Gui;
using ICSharpCode.SharpDevelop.Widgets;
using Microsoft.Win32;
namespace ICSharpCode.MSTest
{
public partial class MSTestOptionsPanel : OptionPanel, INotifyPropertyChanged
{
string msTestPath;
bool changed;
public MSTestOptionsPanel()
{
InitializeComponent();
BrowseCommand = new RelayCommand(Browse);
msTestPath = MSTestOptions.MSTestPath;
DataContext = this;
}
public ICommand BrowseCommand { get; private set; }
void Browse()
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() ?? false) {
MSTestPath = dialog.FileName;
}
}
public string MSTestPath {
get { return msTestPath; }
set {
msTestPath = value;
changed = true;
OnPropertyChanged("MSTestPath");
}
}
public override bool SaveOptions()
{
if (changed) {
MSTestOptions.MSTestPath = msTestPath;
}
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}

31
samples/MSTest/MSTest.SharpDevelop/MSTestQualifiedClassName.cs

@ -0,0 +1,31 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
namespace ICSharpCode.MSTest
{
public class MSTestQualifiedClassName
{
public MSTestQualifiedClassName(string qualifiedClassName)
{
ClassName = GetClassName(qualifiedClassName);
}
string GetClassName(string qualifiedClassName)
{
int index = qualifiedClassName.IndexOf(',');
if (index > 0) {
return qualifiedClassName.Substring(0, index);
}
return qualifiedClassName;
}
public string ClassName { get; private set; }
public string GetQualifiedMethodName(string methodName)
{
return String.Format("{0}.{1}", ClassName, methodName);
}
}
}

93
samples/MSTest/MSTest.SharpDevelop/MSTestResult.cs

@ -0,0 +1,93 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.IO;
using ICSharpCode.SharpDevelop.Dom;
using ICSharpCode.SharpDevelop.Gui;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestResult
{
public MSTestResult(string id)
{
this.Id = id;
}
public string Id { get; private set; }
public string Name { get; private set; }
public TestResultType ResultType { get; private set; }
public string StackTrace { get; set; }
public string Message { get; set; }
public void UpdateTestName(string qualifiedClassName, string methodName)
{
UpdateTestName(new MSTestQualifiedClassName(qualifiedClassName), methodName);
}
public void UpdateTestName(MSTestQualifiedClassName qualifiedClassName, string methodName)
{
this.Name = qualifiedClassName.GetQualifiedMethodName(methodName);
}
public void UpdateResult(string result)
{
if (result == "Passed") {
this.ResultType = TestResultType.Success;
} else if (result == "Failed") {
this.ResultType = TestResultType.Failure;
}
}
public bool IsError {
get { return ResultType == TestResultType.Failure; }
}
public TestResult ToTestResult()
{
return new TestResult(Name) {
ResultType = ResultType,
Message = GetMessage(),
StackTrace = StackTrace,
StackTraceFilePosition = GetStackTraceFilePosition()
};
}
string GetMessage()
{
if (String.IsNullOrEmpty(Message))
return String.Empty;
int index = Message.IndexOf('\n');
if (index > 0) {
return Message.Substring(index + 1);
}
return Message;
}
FilePosition GetStackTraceFilePosition()
{
if (!String.IsNullOrEmpty(StackTrace)) {
return ParseFilePositionFromStackTrace();
}
return FilePosition.Empty;
}
FilePosition ParseFilePositionFromStackTrace()
{
FileLineReference fileLineRef = OutputTextLineParser.GetNUnitOutputFileLineReference(StackTrace, true);
if (fileLineRef != null) {
return CreateFilePosition(fileLineRef);
}
return FilePosition.Empty;
}
FilePosition CreateFilePosition(FileLineReference fileLineRef)
{
string fileName = Path.GetFullPath(fileLineRef.FileName);
return new FilePosition(fileName, fileLineRef.Line, fileLineRef.Column + 1);
}
}
}

91
samples/MSTest/MSTest.SharpDevelop/MSTestResults.cs

@ -0,0 +1,91 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Xml;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestResults : List<TestResult>
{
Dictionary<string, MSTestResult> testDefinitions = new Dictionary<string, MSTestResult>();
public MSTestResults(string fileName)
: this(new XmlTextReader(fileName))
{
}
public MSTestResults(XmlTextReader reader)
{
ReadResults(reader);
}
void ReadResults(XmlTextReader reader)
{
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
if (reader.Name == "UnitTest") {
ReadUnitTest(reader);
} else if (reader.Name == "UnitTestResult") {
ReadUnitTestResult(reader);
}
break;
}
}
}
void ReadUnitTest(XmlTextReader reader)
{
var testResult = new MSTestResult(reader.GetAttribute("id"));
testDefinitions.Add(testResult.Id, testResult);
if (reader.ReadToDescendant("TestMethod")) {
testResult.UpdateTestName(reader.GetAttribute("className"), reader.GetAttribute("name"));
}
}
void ReadUnitTestResult(XmlTextReader reader)
{
string testId = reader.GetAttribute("testId");
MSTestResult testResult = FindTestResult(testId);
if (testResult != null) {
testResult.UpdateResult(reader.GetAttribute("outcome"));
if (testResult.IsError) {
ReadErrorInformation(testResult, reader);
}
Add(testResult.ToTestResult());
}
}
void ReadErrorInformation(MSTestResult testResult, XmlTextReader reader)
{
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.EndElement:
if (reader.Name == "UnitTestResult") {
return;
}
break;
case XmlNodeType.Element:
if (reader.Name == "Message") {
testResult.Message = reader.ReadElementContentAsString();
} else if (reader.Name == "StackTrace") {
testResult.StackTrace = reader.ReadElementContentAsString();
}
break;
}
}
}
MSTestResult FindTestResult(string testId)
{
MSTestResult testResult = null;
testDefinitions.TryGetValue(testId, out testResult);
return testResult;
}
}
}

27
samples/MSTest/MSTest.SharpDevelop/MSTestResultsFileName.cs

@ -0,0 +1,27 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.IO;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestResultsFileName
{
public MSTestResultsFileName(SelectedTests selectedTests)
{
FileName = GetFileName(selectedTests);
}
public string FileName { get; private set; }
string GetFileName(SelectedTests selectedTests)
{
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Temp",
selectedTests.Project.Name + "-Results.trx");
}
}
}

138
samples/MSTest/MSTest.SharpDevelop/MSTestRunner.cs

@ -0,0 +1,138 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Diagnostics;
using System.IO;
using ICSharpCode.SharpDevelop.Util;
using ICSharpCode.UnitTesting;
namespace ICSharpCode.MSTest
{
public class MSTestRunner : TestRunnerBase
{
IUnitTestProcessRunner processRunner;
IFileSystem fileSystem;
IUnitTestMessageService messageService;
string resultsFileName;
public MSTestRunner()
: this(new UnitTestProcessRunner(),
new UnitTestFileService(),
new UnitTestMessageService())
{
}
public MSTestRunner(
IUnitTestProcessRunner processRunner,
IFileSystem fileSystem,
IUnitTestMessageService messageService)
{
this.processRunner = processRunner;
this.fileSystem = fileSystem;
this.messageService = messageService;
processRunner.LogStandardOutputAndError = false;
processRunner.OutputLineReceived += OutputLineReceived;
processRunner.ErrorLineReceived += OutputLineReceived;
processRunner.ProcessExited += ProcessRunnerExited;
}
void ProcessRunnerExited(object source, EventArgs e)
{
// Read all tests.
if (FileExists(resultsFileName)) {
var testResults = new MSTestResults(resultsFileName);
var workbench = new UnitTestWorkbench();
workbench.SafeThreadAsyncCall(() => UpdateTestResults(testResults));
} else {
messageService.ShowFormattedErrorMessage("Unable to find test results file: '{0}'.", resultsFileName);
OnAllTestsFinished(source, e);
}
}
void UpdateTestResults(MSTestResults testResults)
{
foreach (TestResult result in testResults) {
OnTestFinished(this, new TestFinishedEventArgs(result));
}
OnAllTestsFinished(this, new EventArgs());
}
void OutputLineReceived(object source, LineReceivedEventArgs e)
{
OnMessageReceived(e.Line);
}
public override void Start(SelectedTests selectedTests)
{
ProcessStartInfo startInfo = GetProcessStartInfo(selectedTests);
TryDeleteResultsFile();
Start(startInfo);
}
protected override ProcessStartInfo GetProcessStartInfo(SelectedTests selectedTests)
{
resultsFileName = new MSTestResultsFileName(selectedTests).FileName;
CreateDirectoryForResultsFile();
var mstestApplication = new MSTestApplication(selectedTests, resultsFileName);
return mstestApplication.ProcessStartInfo;
}
void Start(ProcessStartInfo processStartInfo)
{
LogCommandLine(processStartInfo);
if (FileExists(processStartInfo.FileName)) {
processRunner.WorkingDirectory = processStartInfo.WorkingDirectory;
processRunner.Start(processStartInfo.FileName, processStartInfo.Arguments);
} else {
ShowApplicationDoesNotExistMessage(processStartInfo.FileName);
}
}
void CreateDirectoryForResultsFile()
{
string path = Path.GetDirectoryName(resultsFileName);
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
}
bool FileExists(string fileName)
{
return fileSystem.FileExists(fileName);
}
void ShowApplicationDoesNotExistMessage(string fileName)
{
string resourceString = "${res:ICSharpCode.UnitTesting.TestRunnerNotFoundMessageFormat}";
messageService.ShowFormattedErrorMessage(resourceString, fileName);
}
public override void Stop()
{
processRunner.Kill();
}
public override void Dispose()
{
processRunner.ErrorLineReceived -= OutputLineReceived;
processRunner.OutputLineReceived -= OutputLineReceived;
processRunner.ProcessExited -= ProcessRunnerExited;
TryDeleteResultsFile();
}
void TryDeleteResultsFile()
{
try {
Console.WriteLine("Deleting results file: " + resultsFileName);
File.Delete(resultsFileName);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}

28
samples/MSTest/MSTest.SharpDevelop/ProjectItemExtensions.cs

@ -0,0 +1,28 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using ICSharpCode.SharpDevelop.Project;
namespace ICSharpCode.MSTest
{
public static class ProjectItemExtensions
{
public static bool IsMSTestAssemblyReference(this ProjectItem item)
{
var referenceItem = item as ReferenceProjectItem;
if (referenceItem == null)
return false;
return IsMSTestAssemblyReference(referenceItem);
}
public static bool IsMSTestAssemblyReference(this ReferenceProjectItem item)
{
return String.Equals(
item.ShortName,
"Microsoft.VisualStudio.QualityTools.UnitTestFramework",
StringComparison.OrdinalIgnoreCase);
}
}
}

31
samples/MSTest/MSTest.SharpDevelop/Properties/AssemblyInfo.cs

@ -0,0 +1,31 @@
#region Using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSTest.SharpDevelop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MSTest.SharpDevelop")]
[assembly: AssemblyCopyright("Copyright 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(false)]
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0")]

1
src/AddIns/BackendBindings/AspNet.Mvc/Project/AspNet.Mvc.csproj

@ -231,7 +231,6 @@
<Compile Include="Src\SelectedMvcFolder.cs" /> <Compile Include="Src\SelectedMvcFolder.cs" />
<Compile Include="Src\SelectedMvcViewFolder.cs" /> <Compile Include="Src\SelectedMvcViewFolder.cs" />
<Compile Include="Src\SlideBehaviour.cs" /> <Compile Include="Src\SlideBehaviour.cs" />
<Compile Include="Src\ViewInBrowser.cs" />
<Compile Include="Src\ViewModelBase.cs" /> <Compile Include="Src\ViewModelBase.cs" />
<Compile Include="Src\VisualStudioProjectExtension.cs" /> <Compile Include="Src\VisualStudioProjectExtension.cs" />
<Compile Include="Src\WebBehavior.cs" /> <Compile Include="Src\WebBehavior.cs" />

77
src/AddIns/BackendBindings/AspNet.Mvc/Project/Src/ViewInBrowser.cs

@ -1,77 +0,0 @@
//// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
//// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
//
//using System;
//using System.IO;
//using System.Linq;
//
//using ICSharpCode.Core;
//using ICSharpCode.SharpDevelop.Gui.OptionPanels;
//using ICSharpCode.SharpDevelop.Project;
//using ICSharpCode.SharpDevelop.Project.Commands;
//
//namespace ICSharpCode.AspNet.Mvc
//{
// public class ViewInBrowser : AbstractMenuCommand
// {
// public override void Run()
// {
// var node = ProjectBrowserPad.Instance.SelectedNode as FileNode;
// if (node == null) {
// return;
// }
//
// var project = ProjectService.CurrentProject as CompilableProject;
// if (project == null) {
// return;
// }
//
// if (!project.IsWebProject) {
// MessageService.ShowError("${res:ProjectComponent.ContextMenu.NotAWebProject}");
// return;
// }
//
// if (!WebProjectService.IsIISOrIISExpressInstalled) {
// MessageService.ShowError("${res:ICSharpCode.WebProjectOptionsPanel.IISNotFound}");
// return;
// }
//
// string fileName = node.FileName;
//
//// // set project options
//// project.StartAction = StartAction.StartURL;
//// string directoryName = Path.GetDirectoryName(project.FileName) + "\\";
//// project.StartUrl = fileName.Replace(directoryName, "/").Replace("\\", "/");
//
// // set web server options
// string projectName = project.Name;
// WebProjectOptions existingOptions = WebProjectsOptions.Instance.GetWebProjectOptions(projectName);
//
// var options = new WebProjectOptions {
// Data = new WebProjectDebugData {
// WebServer = WebProjectService.IsIISExpressInstalled ? WebServer.IISExpress : WebServer.IIS,
// Port = (existingOptions != null && existingOptions.Data != null) ? existingOptions.Data.Port : "8080", //TODO: port collision detection
// ProjectUrl = string.Format("{0}/{1}", WebBehavior.LocalHost, project.Name)
// },
// ProjectName = projectName
// };
//
// if (options.Data.WebServer == WebServer.IISExpress) {
// options.Data.ProjectUrl = string.Format(
// @"{0}:{1}/{2}", WebBehavior.LocalHost, options.Data.Port, projectName);
// }
//
// WebProjectsOptions.Instance.SetWebProjectOptions(projectName, options);
//
// // create virtual directory
// string error = WebProjectService.CreateVirtualDirectory(
// options.Data.WebServer,
// projectName,
// Path.GetDirectoryName(ProjectService.CurrentProject.FileName));
// LoggingService.Info(error ?? string.Empty);
//
// // RunProject
// new RunProject().Run();
// }
// }
//}

4
src/AddIns/BackendBindings/Python/PythonBinding/Project/Src/PythonResolverContext.cs

@ -4,6 +4,8 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Dom; using ICSharpCode.SharpDevelop.Dom;
namespace ICSharpCode.PythonBinding namespace ICSharpCode.PythonBinding
@ -118,7 +120,7 @@ namespace ICSharpCode.PythonBinding
public bool PartialNamespaceExistsInProjectReferences(string name) public bool PartialNamespaceExistsInProjectReferences(string name)
{ {
foreach (IProjectContent referencedContent in projectContent.ReferencedContents) { foreach (IProjectContent referencedContent in projectContent.ThreadSafeGetReferencedContents()) {
if (PartialNamespaceExists(referencedContent, name)) { if (PartialNamespaceExists(referencedContent, name)) {
return true; return true;
} }

2
src/AddIns/BackendBindings/VBNetBinding/Project/Src/OptionPanels/ProjectImports.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.VBNetBinding.OptionPanels
} }
IProjectContent projectContent = ParserService.GetProjectContent(project); IProjectContent projectContent = ParserService.GetProjectContent(project);
foreach(IProjectContent refProjectContent in projectContent.ReferencedContents) { foreach(IProjectContent refProjectContent in projectContent.ThreadSafeGetReferencedContents()) {
AddNamespaces(refProjectContent); AddNamespaces(refProjectContent);
} }

1389
src/AddIns/BackendBindings/XamlBinding/XamlBinding/CompletionDataHelper.cs

File diff suppressed because it is too large Load Diff

145
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlCompilationUnit.cs

@ -0,0 +1,145 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Dom;
namespace ICSharpCode.XamlBinding
{
/// <summary>
/// Description of XamlCompilationUnit.
/// </summary>
public class XamlCompilationUnit : DefaultCompilationUnit
{
public XamlCompilationUnit(IProjectContent projectContent)
: base(projectContent)
{
}
public NodeWrapper TreeRootNode { get; set; }
/// <summary>
/// Creates a IReturnType looking for a class referenced in XAML.
/// </summary>
/// <param name="xmlNamespace">The XML namespace</param>
/// <param name="className">The class name</param>
/// <returns>A new IReturnType that will search the referenced type on demand.</returns>
public IReturnType CreateType(string xmlNamespace, string className)
{
if (string.IsNullOrEmpty(className) || className.Contains("."))
return null;
if (xmlNamespace.StartsWith("clr-namespace:", StringComparison.OrdinalIgnoreCase)) {
return CreateClrNamespaceType(this.ProjectContent, xmlNamespace, className);
} else {
return new XamlClassReturnType(this, xmlNamespace, className);
}
}
static IReturnType CreateClrNamespaceType(IProjectContent pc, string xmlNamespace, string className)
{
string namespaceName = GetNamespaceNameFromClrNamespace(xmlNamespace);
return new GetClassReturnType(pc, namespaceName + "." + className, 0);
}
static string GetNamespaceNameFromClrNamespace(string xmlNamespace)
{
string namespaceName = xmlNamespace.Substring("clr-namespace:".Length);
int pos = namespaceName.IndexOf(';');
if (pos >= 0) {
// we expect that the target type is also a reference of the project, so we
// can ignore the assembly part after the ;
namespaceName = namespaceName.Substring(0, pos);
}
return namespaceName;
}
/// <summary>
/// Finds a type referenced in XAML.
/// </summary>
/// <param name="xmlNamespace">The XML namespace</param>
/// <param name="className">The class name</param>
/// <returns>Returns the referenced type, or null if it cannot be found.</returns>
public IReturnType FindType(string xmlNamespace, string className)
{
return FindType(this.ProjectContent, xmlNamespace, className);
}
public static IReturnType FindType(IProjectContent pc, string xmlNamespace, string className)
{
if (pc == null)
throw new ArgumentNullException("pc");
if (xmlNamespace == null || className == null)
return null;
if (xmlNamespace.StartsWith("clr-namespace:", StringComparison.OrdinalIgnoreCase)) {
return CreateClrNamespaceType(pc, xmlNamespace, className);
}
else {
IReturnType type = FindTypeInAssembly(pc, xmlNamespace, className);
if (type != null)
return type;
foreach (IProjectContent p in pc.ThreadSafeGetReferencedContents()) {
type = FindTypeInAssembly(p, xmlNamespace, className);
if (type != null)
return type;
}
return null;
}
}
static IReturnType FindTypeInAssembly(IProjectContent projectContent, string xmlNamespace, string className)
{
foreach (IAttribute att in projectContent.GetAssemblyAttributes()) {
if (att.PositionalArguments.Count == 2
&& att.AttributeType.FullyQualifiedName == "System.Windows.Markup.XmlnsDefinitionAttribute") {
string namespaceName = att.PositionalArguments[1] as string;
if (xmlNamespace.Equals(att.PositionalArguments[0]) && namespaceName != null) {
IClass c = projectContent.GetClass(namespaceName + "." + className, 0);
if (c != null)
return c.DefaultReturnType;
}
}
}
return null;
}
public static IEnumerable<IClass> GetNamespaceMembers(IProjectContent pc, string xmlNamespace)
{
if (pc == null)
throw new ArgumentNullException("pc");
if (!string.IsNullOrEmpty(xmlNamespace)) {
if (xmlNamespace.StartsWith("clr-namespace:", StringComparison.OrdinalIgnoreCase))
return pc.GetNamespaceContents(GetNamespaceNameFromClrNamespace(xmlNamespace)).OfType<IClass>();
else {
var list = new List<ICompletionEntry>();
AddNamespaceMembersInAssembly(pc, xmlNamespace, list);
foreach (IProjectContent p in pc.ThreadSafeGetReferencedContents()) {
AddNamespaceMembersInAssembly(p, xmlNamespace, list);
}
return list.OfType<IClass>();
}
}
return Enumerable.Empty<IClass>();
}
static void AddNamespaceMembersInAssembly(IProjectContent projectContent, string xmlNamespace, List<ICompletionEntry> list)
{
foreach (IAttribute att in projectContent.GetAssemblyAttributes()) {
if (att.PositionalArguments.Count == 2
&& att.AttributeType.FullyQualifiedName == "System.Windows.Markup.XmlnsDefinitionAttribute") {
string namespaceName = att.PositionalArguments[1] as string;
if (xmlNamespace.Equals(att.PositionalArguments[0]) && namespaceName != null) {
projectContent.AddNamespaceContents(list, namespaceName, projectContent.Language, false);
}
}
}
}
}
}

10
src/AddIns/Debugger/Debugger.AddIn/Pads/Controls/TreeNodeWrapper.cs

@ -39,6 +39,16 @@ namespace Debugger.AddIn.Pads.Controls
get { return Node.HasChildNodes; } get { return Node.HasChildNodes; }
} }
public override bool CanDelete()
{
return Parent is WatchRootNode;
}
public override void Delete()
{
Parent.Children.Remove(this);
}
protected override void LoadChildren() protected override void LoadChildren()
{ {
if (Node.HasChildNodes) { if (Node.HasChildNodes) {

29
src/AddIns/Debugger/Debugger.AddIn/Pads/Controls/WatchListAutoCompleteCell.cs

@ -25,7 +25,7 @@ namespace Debugger.AddIn.Pads.Controls
{ {
public partial class WatchListAutoCompleteCell : UserControl public partial class WatchListAutoCompleteCell : UserControl
{ {
private string language; string language;
protected ConsoleControl console; protected ConsoleControl console;
@ -33,7 +33,7 @@ namespace Debugger.AddIn.Pads.Controls
DependencyProperty.Register("CommandText", typeof(string), typeof(WatchListAutoCompleteCell), DependencyProperty.Register("CommandText", typeof(string), typeof(WatchListAutoCompleteCell),
new UIPropertyMetadata(null, new PropertyChangedCallback(OnCommandTextChanged))); new UIPropertyMetadata(null, new PropertyChangedCallback(OnCommandTextChanged)));
private NRefactoryResolver resolver; NRefactoryResolver resolver;
public event EventHandler CommandEntered; public event EventHandler CommandEntered;
@ -72,7 +72,7 @@ namespace Debugger.AddIn.Pads.Controls
this.Process = debugger.DebuggedProcess; this.Process = debugger.DebuggedProcess;
} }
private Process Process { get; set; } Process Process { get; set; }
/// <summary> /// <summary>
/// Gets/sets the command text displayed at the command prompt. /// Gets/sets the command text displayed at the command prompt.
@ -82,13 +82,13 @@ namespace Debugger.AddIn.Pads.Controls
set { console.CommandText = value; } set { console.CommandText = value; }
} }
private ITextEditor TextEditor { ITextEditor TextEditor {
get { get {
return console.TextEditor; return console.TextEditor;
} }
} }
private void console_TextAreaPreviewKeyDown(object sender, KeyEventArgs e) void console_TextAreaPreviewKeyDown(object sender, KeyEventArgs e)
{ {
if (e.Key == Key.Return || e.Key == Key.Escape) { if (e.Key == Key.Return || e.Key == Key.Escape) {
@ -106,7 +106,7 @@ namespace Debugger.AddIn.Pads.Controls
} }
} }
private void console_LostFocus(object sender, RoutedEventArgs e) void console_LostFocus(object sender, RoutedEventArgs e)
{ {
if (string.IsNullOrEmpty(CommandText) || !this.CheckSyntax()) if (string.IsNullOrEmpty(CommandText) || !this.CheckSyntax())
return; return;
@ -115,7 +115,7 @@ namespace Debugger.AddIn.Pads.Controls
CommandEntered(this, EventArgs.Empty); CommandEntered(this, EventArgs.Empty);
} }
private bool CheckSyntax() bool CheckSyntax()
{ {
string command = CommandText; string command = CommandText;
@ -139,7 +139,7 @@ namespace Debugger.AddIn.Pads.Controls
return true; return true;
} }
private void consoleControl_TextAreaTextEntered(object sender, TextCompositionEventArgs e) void consoleControl_TextAreaTextEntered(object sender, TextCompositionEventArgs e)
{ {
foreach (char ch in e.Text) { foreach (char ch in e.Text) {
if (ch == '.') { if (ch == '.') {
@ -148,21 +148,15 @@ namespace Debugger.AddIn.Pads.Controls
} }
} }
private void ShowDotCompletion(string currentText) void ShowDotCompletion(string currentText)
{ {
var seg = Process.SelectedStackFrame.NextStatement; var seg = Process.SelectedStackFrame.NextStatement;
var expressionFinder = ParserService.GetExpressionFinder(seg.Filename); var expressionFinder = ParserService.GetExpressionFinder(seg.Filename);
var info = ParserService.GetParseInformation(seg.Filename); var info = ParserService.GetParseInformation(seg.Filename);
string text = ParserService.GetParseableFileContent(seg.Filename).Text; string text = ParserService.GetParseableFileContent(seg.Filename).Text;
int currentOffset = TextEditor.Caret.Offset - console.CommandOffset - 1; int currentOffset = TextEditor.Caret.Offset - console.CommandOffset - 1;
var expr = expressionFinder.FindExpression(currentText, currentOffset); var expr = expressionFinder.FindExpression(currentText, currentOffset);
expr.Region = new DomRegion(seg.StartLine, seg.StartColumn, seg.EndLine, seg.EndColumn); expr.Region = new DomRegion(seg.StartLine, seg.StartColumn, seg.EndLine, seg.EndColumn);
var rr = resolver.Resolve(expr, info, text); var rr = resolver.Resolve(expr, info, text);
if (rr != null) { if (rr != null) {
@ -170,9 +164,12 @@ namespace Debugger.AddIn.Pads.Controls
} }
} }
private static void OnCommandTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { static void OnCommandTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var cell = d as WatchListAutoCompleteCell; var cell = d as WatchListAutoCompleteCell;
if (cell != null && e.NewValue != null) {
cell.CommandText = e.NewValue.ToString(); cell.CommandText = e.NewValue.ToString();
} }
} }
} }
}

17
src/AddIns/Debugger/Debugger.AddIn/Pads/WatchPad.cs

@ -55,12 +55,11 @@ namespace ICSharpCode.SharpDevelop.Gui.Pads
watchList = new WatchList(WatchListType.Watch); watchList = new WatchList(WatchListType.Watch);
watchList.ContextMenu = MenuService.CreateContextMenu(this, "/SharpDevelop/Pads/WatchPad/ContextMenu"); watchList.ContextMenu = MenuService.CreateContextMenu(this, "/SharpDevelop/Pads/WatchPad/ContextMenu");
watchList.MouseDoubleClick += watchList_DoubleClick; watchList.MouseDoubleClick += WatchListDoubleClick;
watchList.KeyUp += watchList_KeyUp;
watchList.WatchItems.CollectionChanged += OnWatchItemsCollectionChanged; watchList.WatchItems.CollectionChanged += OnWatchItemsCollectionChanged;
panel.Children.Add(watchList); panel.Children.Add(watchList);
panel.KeyUp += new KeyEventHandler(panel_KeyUp); panel.KeyDown += PanelKeyDown;
// wire events that influence the items // wire events that influence the items
LoadSavedNodes(); LoadSavedNodes();
@ -122,7 +121,7 @@ namespace ICSharpCode.SharpDevelop.Gui.Pads
#endregion #endregion
void panel_KeyUp(object sender, KeyEventArgs e) void PanelKeyDown(object sender, KeyEventArgs e)
{ {
if (e.Key == Key.Insert) { if (e.Key == Key.Insert) {
AddNewWatch(); AddNewWatch();
@ -130,15 +129,7 @@ namespace ICSharpCode.SharpDevelop.Gui.Pads
} }
} }
void watchList_KeyUp(object sender, KeyEventArgs e) void WatchListDoubleClick(object sender, MouseEventArgs e)
{
if (e.Key == Key.Delete) {
RemoveWatchCommand cmd = new RemoveWatchCommand { Owner = this };
cmd.Run();
}
}
void watchList_DoubleClick(object sender, MouseEventArgs e)
{ {
if (watchList.SelectedNode == null) if (watchList.SelectedNode == null)
{ {

25
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/Commands/FoldingCommands.cs

@ -5,6 +5,7 @@ using System;
using System.Linq; using System.Linq;
using ICSharpCode.AvalonEdit.Folding; using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.Core; using ICSharpCode.Core;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Editor; using ICSharpCode.SharpDevelop.Editor;
using ICSharpCode.SharpDevelop.Gui; using ICSharpCode.SharpDevelop.Gui;
@ -16,14 +17,14 @@ namespace ICSharpCode.AvalonEdit.AddIn.Commands
{ {
ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider; ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider;
ITextEditor editor = provider.TextEditor; ITextEditor editor = provider.TextEditor;
ParserFoldingStrategy strategy = editor.GetService(typeof(ParserFoldingStrategy)) as ParserFoldingStrategy; FoldingManager foldingManager = editor.GetService(typeof(FoldingManager)) as FoldingManager;
if (strategy != null) { if (foldingManager != null) {
// look for folding on this line: // look for folding on this line:
FoldingSection folding = strategy.FoldingManager.GetNextFolding(editor.Document.GetOffset(editor.Caret.Line, 1)); FoldingSection folding = foldingManager.GetNextFolding(editor.Document.PositionToOffset(editor.Caret.Line, 1));
if (folding == null || editor.Document.GetLineByOffset(folding.StartOffset).LineNumber != editor.Caret.Line) { if (folding == null || editor.Document.GetLineForOffset(folding.StartOffset).LineNumber != editor.Caret.Line) {
// no folding found on current line: find innermost folding containing the caret // no folding found on current line: find innermost folding containing the caret
folding = strategy.FoldingManager.GetFoldingsContaining(editor.Caret.Offset).LastOrDefault(); folding = foldingManager.GetFoldingsContaining(editor.Caret.Offset).LastOrDefault();
} }
if (folding != null) { if (folding != null) {
folding.IsFolded = !folding.IsFolded; folding.IsFolded = !folding.IsFolded;
@ -38,17 +39,17 @@ namespace ICSharpCode.AvalonEdit.AddIn.Commands
{ {
ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider; ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider;
ITextEditor editor = provider.TextEditor; ITextEditor editor = provider.TextEditor;
ParserFoldingStrategy strategy = editor.GetService(typeof(ParserFoldingStrategy)) as ParserFoldingStrategy; FoldingManager foldingManager = editor.GetService(typeof(FoldingManager)) as FoldingManager;
if (strategy != null) { if (foldingManager != null) {
bool doFold = true; bool doFold = true;
foreach (FoldingSection fm in strategy.FoldingManager.AllFoldings) { foreach (FoldingSection fm in foldingManager.AllFoldings) {
if (fm.IsFolded) { if (fm.IsFolded) {
doFold = false; doFold = false;
break; break;
} }
} }
foreach (FoldingSection fm in strategy.FoldingManager.AllFoldings) { foreach (FoldingSection fm in foldingManager.AllFoldings) {
fm.IsFolded = doFold; fm.IsFolded = doFold;
} }
} }
@ -61,10 +62,10 @@ namespace ICSharpCode.AvalonEdit.AddIn.Commands
{ {
ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider; ITextEditorProvider provider = WorkbenchSingleton.Workbench.ActiveViewContent as ITextEditorProvider;
ITextEditor editor = provider.TextEditor; ITextEditor editor = provider.TextEditor;
ParserFoldingStrategy strategy = editor.GetService(typeof(ParserFoldingStrategy)) as ParserFoldingStrategy; FoldingManager foldingManager = editor.GetService(typeof(FoldingManager)) as FoldingManager;
if (strategy != null) { if (foldingManager != null) {
foreach (FoldingSection fm in strategy.FoldingManager.AllFoldings) { foreach (FoldingSection fm in foldingManager.AllFoldings) {
fm.IsFolded = ParserFoldingStrategy.IsDefinition(fm); fm.IsFolded = ParserFoldingStrategy.IsDefinition(fm);
} }
} }

2
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.xaml

@ -6,7 +6,7 @@
<UserControl.Resources> <UserControl.Resources>
<DataTemplate x:Key="comboBoxItemTemplate"> <DataTemplate x:Key="comboBoxItemTemplate">
<StackPanel Orientation="Horizontal"> <StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}" Width="16" Height="16" Margin="0,0,2,0"/> <Image Source="{Binding Image}" Width="16" Height="16" Margin="0,-1,2,-1"/>
<TextBlock Text="{Binding Text}" Name="textBlock"/> <TextBlock Text="{Binding Text}" Name="textBlock"/>
</StackPanel> </StackPanel>
<DataTemplate.Triggers> <DataTemplate.Triggers>

7
src/AddIns/DisplayBindings/FormsDesigner/Project/Src/DesignerGenerator/AbstractDesignerGenerator.cs

@ -344,8 +344,11 @@ namespace ICSharpCode.FormsDesigner
continue; continue;
if (expr.TargetType.BaseType != "System.ComponentModel.ISupportInitialize") if (expr.TargetType.BaseType != "System.ComponentModel.ISupportInitialize")
continue; continue;
CodeMemberField field = formClass.Members.OfType<CodeMemberField>().First(f => this.formClass.ProjectContent.Language.NameComparer.Equals(fieldRef.FieldName, f.Name)); IField field = this.formClass.DefaultReturnType.GetFields()
IClass fieldType = this.formClass.ProjectContent.GetClass(field.Type.BaseType, 0); .First(f => this.formClass.ProjectContent.Language.NameComparer.Equals(fieldRef.FieldName, f.Name));
if (field.ReturnType == null)
continue;
IClass fieldType = field.ReturnType.GetUnderlyingClass();
if (fieldType == null) if (fieldType == null)
continue; continue;
if (!fieldType.IsTypeInInheritanceTree(iSupportInitializeInterface)) if (!fieldType.IsTypeInInheritanceTree(iSupportInitializeInterface))

2
src/AddIns/DisplayBindings/FormsDesigner/Project/Src/Services/TypeResolutionService.cs

@ -128,7 +128,7 @@ namespace ICSharpCode.FormsDesigner.Services
try { try {
// load dependencies of current assembly // load dependencies of current assembly
foreach (IProjectContent rpc in pc.ReferencedContents) { foreach (IProjectContent rpc in pc.ThreadSafeGetReferencedContents()) {
if (rpc is ParseProjectContent) { if (rpc is ParseProjectContent) {
LoadAssembly(rpc); LoadAssembly(rpc);
} else if (rpc is ReflectionProjectContent) { } else if (rpc is ReflectionProjectContent) {

2
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.AddIn/Src/IdeChooseClassService.cs

@ -43,7 +43,7 @@ namespace ICSharpCode.WpfDesign.AddIn
var pc = ParserService.CurrentProjectContent; var pc = ParserService.CurrentProjectContent;
var a = GetAssembly(pc); var a = GetAssembly(pc);
if (a != null) yield return a; if (a != null) yield return a;
foreach (var r in pc.ReferencedContents) { foreach (var r in pc.ThreadSafeGetReferencedContents()) {
a = GetAssembly(r); a = GetAssembly(r);
if (a != null) yield return a; if (a != null) yield return a;
} }

2
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.AddIn/Src/MyTypeFinder.cs

@ -52,7 +52,7 @@ namespace ICSharpCode.WpfDesign.AddIn
Assembly FindAssemblyInProjectReferences(IProjectContent pc, string name) Assembly FindAssemblyInProjectReferences(IProjectContent pc, string name)
{ {
foreach (IProjectContent referencedProjectContent in pc.ReferencedContents) { foreach (IProjectContent referencedProjectContent in pc.ThreadSafeGetReferencedContents()) {
if (name == referencedProjectContent.AssemblyName) { if (name == referencedProjectContent.AssemblyName) {
return this.typeResolutionService.LoadAssembly(referencedProjectContent); return this.typeResolutionService.LoadAssembly(referencedProjectContent);
} }

3
src/AddIns/DisplayBindings/XmlEditor/Project/Src/XmlTreeViewContainerControl.cs

@ -200,7 +200,7 @@ namespace ICSharpCode.XmlEditor
/// comment node currently on display. /// comment node currently on display.
/// </summary> /// </summary>
public string TextContent { public string TextContent {
get { return textBox.Text; } get { return textBox.Text.Replace("\n", "\r\n"); }
set { textBox.Text = value; } set { textBox.Text = value; }
} }
@ -740,6 +740,7 @@ namespace ICSharpCode.XmlEditor
// //
this.textBox.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox.Location = new System.Drawing.Point(0, 0); this.textBox.Location = new System.Drawing.Point(0, 0);
this.textBox.Multiline = true;
this.textBox.Name = "textBox"; this.textBox.Name = "textBox";
this.textBox.Size = new System.Drawing.Size(375, 326); this.textBox.Size = new System.Drawing.Size(375, 326);
this.textBox.TabIndex = 2; this.textBox.TabIndex = 2;

5
src/AddIns/DisplayBindings/XmlEditor/Project/Src/XmlView.cs

@ -142,8 +142,9 @@ namespace ICSharpCode.XmlEditor
{ {
if (editor == null) return false; if (editor == null) return false;
try { try {
XmlDocument Document = new XmlDocument(); XmlDocument document = new XmlDocument();
Document.LoadXml(editor.Document.Text); document.XmlResolver = null;
document.LoadXml(editor.Document.Text);
return true; return true;
} catch (XmlException ex) { } catch (XmlException ex) {
AddTask(editor.FileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskType.Error); AddTask(editor.FileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskType.Error);

6
src/AddIns/DisplayBindings/XmlEditor/Project/XmlEditor.addin

@ -24,7 +24,7 @@
<Path name="/SharpDevelop/ViewContent/TextEditor/CodeCompletion"> <Path name="/SharpDevelop/ViewContent/TextEditor/CodeCompletion">
<CodeCompletionBinding <CodeCompletionBinding
id="Xml" id="Xml"
extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.build;.xfrm;.targets;.xpt;.xft;.map;.wsdl;.disco;.nuspec;.booproj;.fsproj;.pyproj;.rbproj;.vcxproj;.wixproj" extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.build;.xfrm;.targets;.xpt;.xft;.map;.wsdl;.disco;.nuspec;.booproj;.fsproj;.pyproj;.rbproj;.vcxproj;.wixproj;.ps1xml"
class="ICSharpCode.XmlEditor.XmlCodeCompletionBinding"/> class="ICSharpCode.XmlEditor.XmlCodeCompletionBinding"/>
</Path> </Path>
@ -55,7 +55,7 @@
<LanguageBinding <LanguageBinding
id="Xml" id="Xml"
class="ICSharpCode.XmlEditor.XmlLanguageBinding" class="ICSharpCode.XmlEditor.XmlLanguageBinding"
extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.build;.xfrm;.targets;.xpt;.xft;.map;.wsdl;.disco;.nuspec;.booproj;.fsproj;.pyproj;.rbproj;.vcxproj;.wixproj" /> extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.build;.xfrm;.targets;.xpt;.xft;.map;.wsdl;.disco;.nuspec;.booproj;.fsproj;.pyproj;.rbproj;.vcxproj;.wixproj;.ps1xml" />
</Path> </Path>
<Path name="/SharpDevelop/Workbench/DisplayBindings"> <Path name="/SharpDevelop/Workbench/DisplayBindings">
@ -68,7 +68,7 @@
<!-- Extra project browser icons --> <!-- Extra project browser icons -->
<Path name="/Workspace/Icons"> <Path name="/Workspace/Icons">
<Icon id="ExtraXmlFileIcon" <Icon id="ExtraXmlFileIcon"
extensions=".manifest;.config;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.xfrm;.targets;.xpt;.xft;.map;.wsdl;.disco;.xaml;.nuspec;.booproj;.fsproj;.pyproj;.rbproj;.vcxproj;.wixproj" extensions=".manifest;.config;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.xfrm;.targets;.xpt;.xft;.map;.wsdl;.disco;.xaml;.nuspec;.booproj;.fsproj;.pyproj;.rbproj;.vcxproj;.wixproj;.ps1xml"
resource="FileIcons.XmlIcon" /> resource="FileIcons.XmlIcon" />
</Path> </Path>

BIN
src/AddIns/Misc/PackageManagement/Packages/AvalonEdit.Sample/AvalonEdit.Sample.4.1.0.8000.nupkg

Binary file not shown.

4
src/AddIns/Misc/PackageManagement/Packages/AvalonEdit.Sample/AvalonEdit.Sample.nuspec

@ -2,7 +2,7 @@
<package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<id>AvalonEdit.Sample</id> <id>AvalonEdit.Sample</id>
<version>4.1.0.8000</version> <version>4.2.0.8783</version>
<authors>Daniel Grunwald</authors> <authors>Daniel Grunwald</authors>
<owners>SharpDevelop</owners> <owners>SharpDevelop</owners>
<licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl> <licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl>
@ -16,7 +16,7 @@ StartupUri="/Samples/AvalonEdit/Window1.xaml"</description>
<summary>Sample code for AvalonEdit the WPF-based text editor used in SharpDevelop 4.0.</summary> <summary>Sample code for AvalonEdit the WPF-based text editor used in SharpDevelop 4.0.</summary>
<language>en-US</language> <language>en-US</language>
<dependencies> <dependencies>
<dependency id="AvalonEdit" version="4.1.0.8000" /> <dependency id="AvalonEdit" version="4.2.0.8783" />
</dependencies> </dependencies>
<frameworkAssemblies> <frameworkAssemblies>
<frameworkAssembly assemblyName="System.Windows.Forms" /> <frameworkAssembly assemblyName="System.Windows.Forms" />

BIN
src/AddIns/Misc/PackageManagement/Packages/AvalonEdit/AvalonEdit.4.1.0.8000.nupkg

Binary file not shown.

BIN
src/AddIns/Misc/PackageManagement/Packages/AvalonEdit/AvalonEdit.4.1.0.8000.symbols.nupkg

Binary file not shown.

2
src/AddIns/Misc/PackageManagement/Packages/AvalonEdit/AvalonEdit.nuspec

@ -2,7 +2,7 @@
<package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<id>AvalonEdit</id> <id>AvalonEdit</id>
<version>4.1.0.8000</version> <version>4.2.0.8783</version>
<authors>Daniel Grunwald</authors> <authors>Daniel Grunwald</authors>
<owners>SharpDevelop</owners> <owners>SharpDevelop</owners>
<licenseUrl>http://www.opensource.org/licenses/lgpl-2.1.php</licenseUrl> <licenseUrl>http://www.opensource.org/licenses/lgpl-2.1.php</licenseUrl>

4
src/AddIns/Misc/PackageManagement/Project/Src/EnvDTE/DTE.cs

@ -29,6 +29,10 @@ namespace ICSharpCode.PackageManagement.EnvDTE
ItemOperations = new ItemOperations(fileService); ItemOperations = new ItemOperations(fileService);
} }
public string Version {
get { return "10.0"; }
}
public Solution Solution { public Solution Solution {
get { get {
if (IsSolutionOpen) { if (IsSolutionOpen) {

10
src/AddIns/Misc/PackageManagement/Test/Src/EnvDTE/DTETests.cs

@ -137,5 +137,15 @@ namespace PackageManagement.Tests.EnvDTE
Assert.AreEqual("ProjectA", name); Assert.AreEqual("ProjectA", name);
} }
[Test]
public void Version_CheckVersion_Returns10()
{
CreateDTE();
string version = dte.Version;
Assert.AreEqual("10.0", version);
}
} }
} }

6
src/AddIns/Misc/SharpRefactoring/Project/Src/ContextActions/AddUsing.cs

@ -48,7 +48,7 @@ namespace SharpRefactoring.ContextActions
IProjectContent pc = context.ProjectContent; IProjectContent pc = context.ProjectContent;
SearchAllExtensionMethodsWithName(results, pc, rr.CallName); SearchAllExtensionMethodsWithName(results, pc, rr.CallName);
foreach (IProjectContent content in pc.ReferencedContents) foreach (IProjectContent content in pc.ThreadSafeGetReferencedContents())
SearchAllExtensionMethodsWithName(results, content, rr.CallName); SearchAllExtensionMethodsWithName(results, content, rr.CallName);
foreach (IClass c in results) { foreach (IClass c in results) {
@ -99,7 +99,7 @@ namespace SharpRefactoring.ContextActions
public string Search(UnknownMethodResolveResult rr, IProjectContent pc, List<IClass> results) public string Search(UnknownMethodResolveResult rr, IProjectContent pc, List<IClass> results)
{ {
SearchAttributesWithName(results, pc, rr.CallName); SearchAttributesWithName(results, pc, rr.CallName);
foreach (IProjectContent content in pc.ReferencedContents) foreach (IProjectContent content in pc.ThreadSafeGetReferencedContents())
SearchAttributesWithName(results, content, rr.CallName); SearchAttributesWithName(results, content, rr.CallName);
return rr.CallName; return rr.CallName;
} }
@ -107,7 +107,7 @@ namespace SharpRefactoring.ContextActions
public string Search(UnknownIdentifierResolveResult rr, IProjectContent pc, List<IClass> results) public string Search(UnknownIdentifierResolveResult rr, IProjectContent pc, List<IClass> results)
{ {
SearchAttributesWithName(results, pc, rr.Identifier); SearchAttributesWithName(results, pc, rr.Identifier);
foreach (IProjectContent content in pc.ReferencedContents) foreach (IProjectContent content in pc.ThreadSafeGetReferencedContents())
SearchAttributesWithName(results, content, rr.Identifier); SearchAttributesWithName(results, content, rr.Identifier);
return rr.Identifier; return rr.Identifier;
} }

4
src/AddIns/Misc/SharpRefactoring/Project/Src/MenuItemFactories/ResolveAttribute.cs

@ -42,7 +42,7 @@ namespace SharpRefactoring
var rr = context.ResolveResult as UnknownMethodResolveResult; var rr = context.ResolveResult as UnknownMethodResolveResult;
SearchAttributesWithName(results, pc, rr.CallName); SearchAttributesWithName(results, pc, rr.CallName);
foreach (IProjectContent content in pc.ReferencedContents) foreach (IProjectContent content in pc.ThreadSafeGetReferencedContents())
SearchAttributesWithName(results, content, rr.CallName); SearchAttributesWithName(results, content, rr.CallName);
name = rr.CallName; name = rr.CallName;
@ -52,7 +52,7 @@ namespace SharpRefactoring
var rr = context.ResolveResult as UnknownIdentifierResolveResult; var rr = context.ResolveResult as UnknownIdentifierResolveResult;
SearchAttributesWithName(results, pc, rr.Identifier); SearchAttributesWithName(results, pc, rr.Identifier);
foreach (IProjectContent content in pc.ReferencedContents) foreach (IProjectContent content in pc.ThreadSafeGetReferencedContents())
SearchAttributesWithName(results, content, rr.Identifier); SearchAttributesWithName(results, content, rr.Identifier);
name = rr.Identifier; name = rr.Identifier;

2
src/AddIns/Misc/SharpRefactoring/Project/Src/MenuItemFactories/ResolveExtensionMethod.cs

@ -38,7 +38,7 @@ namespace SharpRefactoring
SearchAllExtensionMethodsWithName(results, context.ProjectContent, rr.CallName); SearchAllExtensionMethodsWithName(results, context.ProjectContent, rr.CallName);
foreach (IProjectContent content in context.ProjectContent.ReferencedContents) foreach (IProjectContent content in context.ProjectContent.ThreadSafeGetReferencedContents())
SearchAllExtensionMethodsWithName(results, content, rr.CallName); SearchAllExtensionMethodsWithName(results, content, rr.CallName);
if (!results.Any()) if (!results.Any())

35
src/Libraries/AvalonEdit/Documentation/ICSharpCode.AvalonEdit.shfbproj

@ -33,9 +33,9 @@
</BuildLogFile> </BuildLogFile>
<FrameworkVersion>.NET 4.0.30319</FrameworkVersion> <FrameworkVersion>.NET 4.0.30319</FrameworkVersion>
<HelpTitle>AvalonEdit</HelpTitle> <HelpTitle>AvalonEdit</HelpTitle>
<CopyrightText>Copyright 2008-2011, Daniel Grunwald</CopyrightText> <CopyrightText>Copyright 2008-2012, Daniel Grunwald</CopyrightText>
<PresentationStyle>Prototype</PresentationStyle> <PresentationStyle>Prototype</PresentationStyle>
<HelpFileVersion>4.1.0.0</HelpFileVersion> <HelpFileVersion>4.2.0.0</HelpFileVersion>
<ComponentConfigurations> <ComponentConfigurations>
<ComponentConfig id="Code Block Component" enabled="True"> <ComponentConfig id="Code Block Component" enabled="True">
<component id="Code Block Component" type="SandcastleBuilder.Components.CodeBlockComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll"> <component id="Code Block Component" type="SandcastleBuilder.Components.CodeBlockComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll">
@ -66,15 +66,18 @@
<colorizer syntaxFile="{@SHFBFolder}Colorizer\highlight.xml" styleFile="{@SHFBFolder}Colorizer\highlight.xsl" copyImageUrl="../icons/CopyCode.gif" language="cs" numberLines="false" outlining="false" keepSeeTags="false" tabSize="0" defaultTitle="true" /> <colorizer syntaxFile="{@SHFBFolder}Colorizer\highlight.xml" styleFile="{@SHFBFolder}Colorizer\highlight.xsl" copyImageUrl="../icons/CopyCode.gif" language="cs" numberLines="false" outlining="false" keepSeeTags="false" tabSize="0" defaultTitle="true" />
</component> </component>
</ComponentConfig> </ComponentConfig>
<ComponentConfig id="IntelliSense Component" enabled="True"><component id="IntelliSense Component" type="SandcastleBuilder.Components.IntelliSenseComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll"> <ComponentConfig id="IntelliSense Component" enabled="True">
<component id="IntelliSense Component" type="SandcastleBuilder.Components.IntelliSenseComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll">
<!-- Output options (optional) <!-- Output options (optional)
Attributes: Attributes:
Include Namespaces (false by default) Include Namespaces (false by default)
Namespaces filename ("Namespaces" if not specified or empty) Namespaces filename ("Namespaces" if not specified or empty)
Directory (current folder if not specified or empty) --> Directory (current folder if not specified or empty) -->
<output includeNamespaces="false" namespacesFile="Namespaces" folder="{@OutputFolder}" /> <output includeNamespaces="false" namespacesFile="Namespaces" folder="{@OutputFolder}" />
</component></ComponentConfig> </component>
<ComponentConfig id="Cached MSDN URL References" enabled="True"><component id="Cached MSDN URL References" type="SandcastleBuilder.Components.CachedResolveReferenceLinksComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll" locale="{@Locale}" linkTarget="{@SdkLinkTarget}"> </ComponentConfig>
<ComponentConfig id="Cached MSDN URL References" enabled="True">
<component id="Cached MSDN URL References" type="SandcastleBuilder.Components.CachedResolveReferenceLinksComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll" locale="{@Locale}" linkTarget="{@SdkLinkTarget}">
<helpOutput format="HtmlHelp1"> <helpOutput format="HtmlHelp1">
<cache filename="{@LocalDataFolder}Cache\MsdnUrl.cache" /> <cache filename="{@LocalDataFolder}Cache\MsdnUrl.cache" />
<targets base="{@SandcastlePath}Data\Reflection" recurse="true" files="*.xml" type="{@HtmlSdkLinkType}" /> <targets base="{@SandcastlePath}Data\Reflection" recurse="true" files="*.xml" type="{@HtmlSdkLinkType}" />
@ -95,8 +98,10 @@
<targets base="{@SandcastlePath}Data\Reflection" recurse="true" files="*.xml" type="{@WebsiteSdkLinkType}" /> <targets base="{@SandcastlePath}Data\Reflection" recurse="true" files="*.xml" type="{@WebsiteSdkLinkType}" />
<targets files="reflection.xml" type="Local" /> <targets files="reflection.xml" type="Local" />
</helpOutput> </helpOutput>
</component></ComponentConfig> </component>
<ComponentConfig id="Post-transform Component" enabled="True"><component id="Post-transform Component" type="SandcastleBuilder.Components.PostTransformComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll"> </ComponentConfig>
<ComponentConfig id="Post-transform Component" enabled="True">
<component id="Post-transform Component" type="SandcastleBuilder.Components.PostTransformComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll">
<!-- Code colorizer files (required). <!-- Code colorizer files (required).
Attributes: Attributes:
Stylesheet file (required) Stylesheet file (required)
@ -113,21 +118,27 @@
width, altText, placement, and alignment attributes are width, altText, placement, and alignment attributes are
optional. --> optional. -->
<logoFile filename="" height="0" width="0" altText="" placement="left" alignment="left" /> <logoFile filename="" height="0" width="0" altText="" placement="left" alignment="left" />
</component></ComponentConfig> </component>
<ComponentConfig id="Cached Reflection Index Data" enabled="True"><component id="Cached Reflection Index Data" type="SandcastleBuilder.Components.CachedCopyFromIndexComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll"> </ComponentConfig>
<ComponentConfig id="Cached Reflection Index Data" enabled="True">
<component id="Cached Reflection Index Data" type="SandcastleBuilder.Components.CachedCopyFromIndexComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll">
<index name="reflection" value="/reflection/apis/api" key="@id" cache="10"> <index name="reflection" value="/reflection/apis/api" key="@id" cache="10">
<cache base="{@SandcastlePath}Data\Reflection" recurse="true" files="*.xml" cacheFile="{@LocalDataFolder}Cache\Reflection.cache" /> <cache base="{@SandcastlePath}Data\Reflection" recurse="true" files="*.xml" cacheFile="{@LocalDataFolder}Cache\Reflection.cache" />
<data files="reflection.xml" /> <data files="reflection.xml" />
</index> </index>
<copy name="reflection" source="*" target="/document/reference" /> <copy name="reflection" source="*" target="/document/reference" />
</component></ComponentConfig> </component>
<ComponentConfig id="Cached Framework Comments Index Data" enabled="True"><component id="Cached Framework Comments Index Data" type="SandcastleBuilder.Components.CachedCopyFromIndexComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll"> </ComponentConfig>
<ComponentConfig id="Cached Framework Comments Index Data" enabled="True">
<component id="Cached Framework Comments Index Data" type="SandcastleBuilder.Components.CachedCopyFromIndexComponent" assembly="{@SHFBFolder}SandcastleBuilder.Components.dll">
<index name="comments" value="/doc/members/member" key="@name" cache="100"> <index name="comments" value="/doc/members/member" key="@name" cache="100">
{@CachedFrameworkCommentList} {@CachedFrameworkCommentList}
{@CommentFileList} {@CommentFileList}
</index> </index>
<copy name="comments" source="*" target="/document/comments" /> <copy name="comments" source="*" target="/document/comments" />
</component></ComponentConfig></ComponentConfigurations> </component>
</ComponentConfig>
</ComponentConfigurations>
<DocumentationSources> <DocumentationSources>
<DocumentationSource sourceFile="..\ICSharpCode.AvalonEdit\ICSharpCode.AvalonEdit.csproj" /> <DocumentationSource sourceFile="..\ICSharpCode.AvalonEdit\ICSharpCode.AvalonEdit.csproj" />
</DocumentationSources> </DocumentationSources>

10
src/Libraries/AvalonEdit/Documentation/Welcome.aml

@ -41,13 +41,13 @@
<section> <section>
<title>System requirements</title> <title>System requirements</title>
<content> <content>
<para>AvalonEdit requires the <para>There are two versions of AvalonEdit - the normal one requires
<externalLink> <externalLink>
<linkText>.NET Framework 3.5 SP1</linkText> <linkText>.NET Framework 4.0</linkText>
<linkUri>http://www.microsoft.com/downloads/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&amp;DisplayLang=en</linkUri> <linkUri>http://msdn.microsoft.com/en-us/library/w0x726c2.aspx</linkUri>
<linkTarget>_blank</linkTarget> <linkTarget>_blank</linkTarget>
</externalLink>. </externalLink> or higher; but we also offer a modified version for .NET 3.5 SP1.
For compiling AvalonEdit inside Visual Studio 2008, VS08 SP1 is required. For compiling AvalonEdit, you will need a C# 4.0 compiler (SharpDevelop 4.x or Visual Studio 2010).
</para> </para>
<para>AvalonEdit requires FullTrust and will not run as XBAP.</para> <para>AvalonEdit requires FullTrust and will not run as XBAP.</para>
</content> </content>

3
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Caret.cs

@ -23,6 +23,7 @@ namespace ICSharpCode.AvalonEdit.Editing
{ {
readonly TextArea textArea; readonly TextArea textArea;
readonly TextView textView; readonly TextView textView;
readonly ImeSupport ime;
readonly CaretLayer caretAdorner; readonly CaretLayer caretAdorner;
bool visible; bool visible;
@ -31,6 +32,7 @@ namespace ICSharpCode.AvalonEdit.Editing
this.textArea = textArea; this.textArea = textArea;
this.textView = textArea.TextView; this.textView = textArea.TextView;
position = new TextViewPosition(1, 1, 0); position = new TextViewPosition(1, 1, 0);
ime = new ImeSupport(textArea);
caretAdorner = new CaretLayer(textView); caretAdorner = new CaretLayer(textView);
textView.InsertLayer(caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace); textView.InsertLayer(caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace);
@ -442,6 +444,7 @@ namespace ICSharpCode.AvalonEdit.Editing
} else { } else {
caretAdorner.Hide(); caretAdorner.Hide();
} }
ime.UpdateCompositionWindow();
} }
} }

35
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/CaretNavigationCommandHandler.cs

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Documents; using System.Windows.Documents;
using System.Windows.Input; using System.Windows.Input;
@ -41,21 +42,28 @@ namespace ICSharpCode.AvalonEdit.Editing
const ModifierKeys None = ModifierKeys.None; const ModifierKeys None = ModifierKeys.None;
const ModifierKeys Ctrl = ModifierKeys.Control; const ModifierKeys Ctrl = ModifierKeys.Control;
const ModifierKeys Shift = ModifierKeys.Shift; const ModifierKeys Shift = ModifierKeys.Shift;
const ModifierKeys Alt = ModifierKeys.Alt;
AddBinding(EditingCommands.MoveLeftByCharacter, None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft)); AddBinding(EditingCommands.MoveLeftByCharacter, None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(EditingCommands.SelectLeftByCharacter, Shift, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft)); AddBinding(EditingCommands.SelectLeftByCharacter, Shift, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, Alt | Shift, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, None, Key.Right, OnMoveCaret(CaretMovementType.CharRight)); AddBinding(EditingCommands.MoveRightByCharacter, None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, Shift, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight)); AddBinding(EditingCommands.SelectRightByCharacter, Shift, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, Alt | Shift, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, Ctrl, Key.Left, OnMoveCaret(CaretMovementType.WordLeft)); AddBinding(EditingCommands.MoveLeftByWord, Ctrl, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, Ctrl | Shift, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft)); AddBinding(EditingCommands.SelectLeftByWord, Ctrl | Shift, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, Ctrl | Alt | Shift, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, Ctrl, Key.Right, OnMoveCaret(CaretMovementType.WordRight)); AddBinding(EditingCommands.MoveRightByWord, Ctrl, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, Ctrl | Shift, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight)); AddBinding(EditingCommands.SelectRightByWord, Ctrl | Shift, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, Ctrl | Alt | Shift, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, None, Key.Up, OnMoveCaret(CaretMovementType.LineUp)); AddBinding(EditingCommands.MoveUpByLine, None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, Shift, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp)); AddBinding(EditingCommands.SelectUpByLine, Shift, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, Alt | Shift, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, None, Key.Down, OnMoveCaret(CaretMovementType.LineDown)); AddBinding(EditingCommands.MoveDownByLine, None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, Shift, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown)); AddBinding(EditingCommands.SelectDownByLine, Shift, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, Alt | Shift, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown)); AddBinding(EditingCommands.MoveDownByPage, None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, Shift, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown)); AddBinding(EditingCommands.SelectDownByPage, Shift, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
@ -64,8 +72,10 @@ namespace ICSharpCode.AvalonEdit.Editing
AddBinding(EditingCommands.MoveToLineStart, None, Key.Home, OnMoveCaret(CaretMovementType.LineStart)); AddBinding(EditingCommands.MoveToLineStart, None, Key.Home, OnMoveCaret(CaretMovementType.LineStart));
AddBinding(EditingCommands.SelectToLineStart, Shift, Key.Home, OnMoveCaretExtendSelection(CaretMovementType.LineStart)); AddBinding(EditingCommands.SelectToLineStart, Shift, Key.Home, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineStart, Alt | Shift, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(EditingCommands.MoveToLineEnd, None, Key.End, OnMoveCaret(CaretMovementType.LineEnd)); AddBinding(EditingCommands.MoveToLineEnd, None, Key.End, OnMoveCaret(CaretMovementType.LineEnd));
AddBinding(EditingCommands.SelectToLineEnd, Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.LineEnd)); AddBinding(EditingCommands.SelectToLineEnd, Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineEnd, Alt | Shift, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
AddBinding(EditingCommands.MoveToDocumentStart, Ctrl, Key.Home, OnMoveCaret(CaretMovementType.DocumentStart)); AddBinding(EditingCommands.MoveToDocumentStart, Ctrl, Key.Home, OnMoveCaret(CaretMovementType.DocumentStart));
AddBinding(EditingCommands.SelectToDocumentStart, Ctrl | Shift, Key.Home, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart)); AddBinding(EditingCommands.SelectToDocumentStart, Ctrl | Shift, Key.Home, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
@ -135,6 +145,31 @@ namespace ICSharpCode.AvalonEdit.Editing
}; };
} }
static ExecutedRoutedEventHandler OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) => {
TextArea textArea = GetTextArea(target);
if (textArea != null && textArea.Document != null) {
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) {
if (textArea.Selection.IsEmpty) {
textArea.Selection = new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position);
} else {
// Convert normal selection to rectangle selection
textArea.Selection = new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position);
}
}
// Now move the caret and extend the selection
TextViewPosition oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement #region Caret movement
static void MoveCaret(TextArea textArea, CaretMovementType direction) static void MoveCaret(TextArea textArea, CaretMovementType direction)
{ {

9
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/EmptySelection.cs

@ -7,6 +7,7 @@ using System.Runtime.CompilerServices;
using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Utils; using ICSharpCode.AvalonEdit.Utils;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.Editor; using ICSharpCode.NRefactory.Editor;
namespace ICSharpCode.AvalonEdit.Editing namespace ICSharpCode.AvalonEdit.Editing
@ -22,6 +23,14 @@ namespace ICSharpCode.AvalonEdit.Editing
return this; return this;
} }
public override TextViewPosition StartPosition {
get { return new TextViewPosition(TextLocation.Empty); }
}
public override TextViewPosition EndPosition {
get { return new TextViewPosition(TextLocation.Empty); }
}
public override ISegment SurroundingSegment { public override ISegment SurroundingSegment {
get { return null; } get { return null; }
} }

178
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeNativeWrapper.cs

@ -0,0 +1,178 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
using Draw = System.Drawing;
namespace ICSharpCode.AvalonEdit.Editing
{
/// <summary>
/// Native API required for IME support.
/// </summary>
static class ImeNativeWrapper
{
[StructLayout(LayoutKind.Sequential)]
struct CompositionForm
{
public int dwStyle;
public POINT ptCurrentPos;
public RECT rcArea;
}
[StructLayout(LayoutKind.Sequential)]
struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
class LOGFONT
{
public int lfHeight = 0;
public int lfWidth = 0;
public int lfEscapement = 0;
public int lfOrientation = 0;
public int lfWeight = 0;
public byte lfItalic = 0;
public byte lfUnderline = 0;
public byte lfStrikeOut = 0;
public byte lfCharSet = 0;
public byte lfOutPrecision = 0;
public byte lfClipPrecision = 0;
public byte lfQuality = 0;
public byte lfPitchAndFamily = 0;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string lfFaceName = null;
}
const int CPS_CANCEL = 0x4;
const int NI_COMPOSITIONSTR = 0x15;
const int GCS_COMPSTR = 0x0008;
public const int WM_IME_COMPOSITION = 0x10F;
public const int WM_INPUTLANGCHANGE = 0x51;
[DllImport("imm32.dll")]
static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("imm32.dll")]
static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("imm32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ImmNotifyIME(IntPtr hIMC, int dwAction, int dwIndex, int dwValue = 0);
[DllImport("imm32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("imm32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ImmSetCompositionWindow(IntPtr hIMC, ref CompositionForm form);
[DllImport("imm32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ImmSetCompositionFont(IntPtr hIMC, ref LOGFONT font);
[DllImport("imm32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ImmGetCompositionFont(IntPtr hIMC, out LOGFONT font);
public static IntPtr AssociateContext(HwndSource source, IntPtr hIMC)
{
if (source == null)
throw new ArgumentNullException("source");
return ImmAssociateContext(source.Handle, hIMC);
}
public static bool NotifyIme(IntPtr hIMC)
{
return ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL);
}
public static IntPtr GetContext(HwndSource source)
{
if (source == null)
return IntPtr.Zero;
return ImmGetContext(source.Handle);
}
public static bool ReleaseContext(HwndSource source, IntPtr hIMC)
{
return source != null && hIMC != IntPtr.Zero && ImmReleaseContext(source.Handle, hIMC);
}
public static bool SetCompositionWindow(HwndSource source, IntPtr hIMC, TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
Rect textViewBounds = textArea.TextView.GetBounds();
Rect characterBounds = textArea.TextView.GetCharacterBounds(textArea.Caret.Position, source);
if (source != null) {
Matrix transformToDevice = source.CompositionTarget.TransformToDevice;
textViewBounds.Transform(transformToDevice);
characterBounds.Transform(transformToDevice);
}
CompositionForm form = new CompositionForm();
form.dwStyle = 0x0020;
form.ptCurrentPos.x = (int)Math.Max(characterBounds.Left, textViewBounds.Left);
form.ptCurrentPos.y = (int)Math.Max(characterBounds.Top, textViewBounds.Top);
form.rcArea.left = (int)textViewBounds.Left;
form.rcArea.top = (int)textViewBounds.Top;
form.rcArea.right = (int)textViewBounds.Right;
form.rcArea.bottom = (int)textViewBounds.Bottom;
return ImmSetCompositionWindow(hIMC, ref form);
}
public static bool SetCompositionFont(HwndSource source, IntPtr hIMC, TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
// LOGFONT font = new LOGFONT();
// ImmGetCompositionFont(hIMC, out font);
return false;
}
static Rect GetBounds(this TextView textView)
{
Point location = textView.TranslatePoint(new Point(0,0), textView);
return new Rect(location, new Size(textView.ActualWidth, textView.ActualHeight));
}
static readonly Rect EMPTY_RECT = new Rect(0, 0, 0, 0);
static Rect GetCharacterBounds(this TextView textView, TextViewPosition pos, HwndSource source)
{
VisualLine vl = textView.GetVisualLine(pos.Line);
if (vl == null) return EMPTY_RECT;
TextLine line = vl.GetTextLine(pos.VisualColumn);
double offset = vl.GetTextLineVisualYPosition(line, VisualYPosition.LineTop) - textView.ScrollOffset.Y;
Rect r = line.GetTextBounds(pos.VisualColumn, 1).First().Rectangle;
r.Offset(-textView.ScrollOffset.X, offset);
// this may happen during layout changes in AvalonDock, so we just return an empty rectangle
// in those cases. It should be refreshed immediately.
if (!source.RootVisual.IsAncestorOf(textView)) return EMPTY_RECT;
Point pointOnRootVisual = textView.TransformToAncestor(source.RootVisual).Transform(r.Location);
Point pointOnHwnd = pointOnRootVisual.TransformToDevice(source.RootVisual);
r.Location = pointOnHwnd;
return r;
}
}
}

125
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/ImeSupport.cs

@ -0,0 +1,125 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
namespace ICSharpCode.AvalonEdit.Editing
{
class ImeSupport : IDisposable
{
TextArea textArea;
IntPtr currentContext;
IntPtr previousContext;
HwndSource hwndSource;
public ImeSupport(TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
this.textArea = textArea;
InputMethod.SetIsInputMethodSuspended(this.textArea, true);
textArea.GotKeyboardFocus += TextAreaGotKeyboardFocus;
textArea.LostKeyboardFocus += TextAreaLostKeyboardFocus;
textArea.OptionChanged += TextAreaOptionChanged;
currentContext = IntPtr.Zero;
previousContext = IntPtr.Zero;
}
void TextAreaOptionChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "EnableImeSupport" && textArea.IsKeyboardFocusWithin) {
CreateContext();
}
}
public void Dispose()
{
if (textArea != null) {
textArea.GotKeyboardFocus -= TextAreaGotKeyboardFocus;
textArea.LostKeyboardFocus -= TextAreaLostKeyboardFocus;
textArea = null;
}
ClearContext();
}
void ClearContext()
{
if (hwndSource != null) {
hwndSource.RemoveHook(WndProc);
ImeNativeWrapper.AssociateContext(hwndSource, previousContext);
previousContext = IntPtr.Zero;
ImeNativeWrapper.ReleaseContext(hwndSource, currentContext);
hwndSource = null;
currentContext = IntPtr.Zero;
}
}
void TextAreaGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (this.textArea == null)
return;
if (e.OriginalSource != this.textArea)
return;
CreateContext();
}
void CreateContext()
{
if (this.textArea == null)
return;
if (!textArea.Options.EnableImeSupport)
return;
hwndSource = (HwndSource)PresentationSource.FromVisual(this.textArea);
if (hwndSource != null) {
currentContext = ImeNativeWrapper.GetContext(hwndSource);
previousContext = ImeNativeWrapper.AssociateContext(hwndSource, currentContext);
// ImeNativeWrapper.SetCompositionFont(hwndSource, currentContext, textArea);
hwndSource.AddHook(WndProc);
}
}
void TextAreaLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (e.OriginalSource != this.textArea)
return;
if (currentContext != IntPtr.Zero)
ImeNativeWrapper.NotifyIme(currentContext);
ClearContext();
}
IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg) {
case ImeNativeWrapper.WM_INPUTLANGCHANGE:
ClearContext();
CreateContext();
break;
case ImeNativeWrapper.WM_IME_COMPOSITION:
UpdateCompositionWindow();
break;
}
return IntPtr.Zero;
}
public void UpdateCompositionWindow()
{
if (currentContext != IntPtr.Zero && textArea != null) {
ImeNativeWrapper.SetCompositionWindow(hwndSource, currentContext, textArea);
}
}
}
}

149
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/RectangleSelection.cs

@ -7,8 +7,9 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.TextFormatting; using System.Windows.Media.TextFormatting;
using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering; using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils; using ICSharpCode.AvalonEdit.Utils;
@ -22,20 +23,70 @@ namespace ICSharpCode.AvalonEdit.Editing
/// </summary> /// </summary>
public sealed class RectangleSelection : Selection public sealed class RectangleSelection : Selection
{ {
#region Commands
/// <summary>
/// Expands the selection left by one character, creating a rectangular selection.
/// Key gesture: Alt+Shift+Left
/// </summary>
public static readonly RoutedUICommand BoxSelectLeftByCharacter = Command("BoxSelectLeftByCharacter");
/// <summary>
/// Expands the selection right by one character, creating a rectangular selection.
/// Key gesture: Alt+Shift+Right
/// </summary>
public static readonly RoutedUICommand BoxSelectRightByCharacter = Command("BoxSelectRightByCharacter");
/// <summary>
/// Expands the selection left by one word, creating a rectangular selection.
/// Key gesture: Ctrl+Alt+Shift+Left
/// </summary>
public static readonly RoutedUICommand BoxSelectLeftByWord = Command("BoxSelectLeftByWord");
/// <summary>
/// Expands the selection left by one word, creating a rectangular selection.
/// Key gesture: Ctrl+Alt+Shift+Right
/// </summary>
public static readonly RoutedUICommand BoxSelectRightByWord = Command("BoxSelectRightByWord");
/// <summary>
/// Expands the selection up by one line, creating a rectangular selection.
/// Key gesture: Alt+Shift+Up
/// </summary>
public static readonly RoutedUICommand BoxSelectUpByLine = Command("BoxSelectUpByLine");
/// <summary>
/// Expands the selection up by one line, creating a rectangular selection.
/// Key gesture: Alt+Shift+Down
/// </summary>
public static readonly RoutedUICommand BoxSelectDownByLine = Command("BoxSelectDownByLine");
/// <summary>
/// Expands the selection to the start of the line, creating a rectangular selection.
/// Key gesture: Alt+Shift+Home
/// </summary>
public static readonly RoutedUICommand BoxSelectToLineStart = Command("BoxSelectToLineStart");
/// <summary>
/// Expands the selection to the end of the line, creating a rectangular selection.
/// Key gesture: Alt+Shift+End
/// </summary>
public static readonly RoutedUICommand BoxSelectToLineEnd = Command("BoxSelectToLineEnd");
static RoutedUICommand Command(string name)
{
return new RoutedUICommand(name, name, typeof(RectangleSelection));
}
#endregion
TextDocument document; TextDocument document;
readonly int startLine, endLine; readonly int startLine, endLine;
readonly double startXPos, endXPos; readonly double startXPos, endXPos;
readonly int topLeftOffset, bottomRightOffset; readonly int topLeftOffset, bottomRightOffset;
readonly TextViewPosition start, end;
readonly List<SelectionSegment> segments = new List<SelectionSegment>(); readonly List<SelectionSegment> segments = new List<SelectionSegment>();
void InitDocument() #region Constructors
{
document = textArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
}
/// <summary> /// <summary>
/// Creates a new rectangular selection. /// Creates a new rectangular selection.
/// </summary> /// </summary>
@ -50,6 +101,9 @@ namespace ICSharpCode.AvalonEdit.Editing
CalculateSegments(); CalculateSegments();
this.topLeftOffset = this.segments.First().StartOffset; this.topLeftOffset = this.segments.First().StartOffset;
this.bottomRightOffset = this.segments.Last().EndOffset; this.bottomRightOffset = this.segments.Last().EndOffset;
this.start = start;
this.end = end;
} }
private RectangleSelection(TextArea textArea, int startLine, double startXPos, TextViewPosition end) private RectangleSelection(TextArea textArea, int startLine, double startXPos, TextViewPosition end)
@ -63,6 +117,9 @@ namespace ICSharpCode.AvalonEdit.Editing
CalculateSegments(); CalculateSegments();
this.topLeftOffset = this.segments.First().StartOffset; this.topLeftOffset = this.segments.First().StartOffset;
this.bottomRightOffset = this.segments.Last().EndOffset; this.bottomRightOffset = this.segments.Last().EndOffset;
this.start = GetStart();
this.end = end;
} }
private RectangleSelection(TextArea textArea, TextViewPosition start, int endLine, double endXPos) private RectangleSelection(TextArea textArea, TextViewPosition start, int endLine, double endXPos)
@ -76,6 +133,16 @@ namespace ICSharpCode.AvalonEdit.Editing
CalculateSegments(); CalculateSegments();
this.topLeftOffset = this.segments.First().StartOffset; this.topLeftOffset = this.segments.First().StartOffset;
this.bottomRightOffset = this.segments.Last().EndOffset; this.bottomRightOffset = this.segments.Last().EndOffset;
this.start = start;
this.end = GetEnd();
}
void InitDocument()
{
document = textArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
} }
static double GetXPos(TextArea textArea, TextViewPosition pos) static double GetXPos(TextArea textArea, TextViewPosition pos)
@ -87,11 +154,43 @@ namespace ICSharpCode.AvalonEdit.Editing
return visualLine.GetTextLineVisualXPosition(textLine, vc); return visualLine.GetTextLineVisualXPosition(textLine, vc);
} }
int GetVisualColumnFromXPos(int line, double xPos) void CalculateSegments()
{ {
var vl = textArea.TextView.GetOrConstructVisualLine(textArea.Document.GetLineByNumber(line)); DocumentLine nextLine = document.GetLineByNumber(Math.Min(startLine, endLine));
return vl.GetVisualColumn(new Point(xPos, 0), true); do {
VisualLine vl = textArea.TextView.GetOrConstructVisualLine(nextLine);
int startVC = vl.GetVisualColumn(new Point(startXPos, 0), true);
int endVC = vl.GetVisualColumn(new Point(endXPos, 0), true);
int baseOffset = vl.FirstDocumentLine.Offset;
int startOffset = baseOffset + vl.GetRelativeOffset(startVC);
int endOffset = baseOffset + vl.GetRelativeOffset(endVC);
segments.Add(new SelectionSegment(startOffset, startVC, endOffset, endVC));
nextLine = vl.LastDocumentLine.NextLine;
} while (nextLine != null && nextLine.LineNumber <= Math.Max(startLine, endLine));
}
TextViewPosition GetStart()
{
SelectionSegment segment = (startLine < endLine ? segments.First() : segments.Last());
if (startXPos < endXPos) {
return new TextViewPosition(document.GetLocation(segment.StartOffset), segment.StartVisualColumn);
} else {
return new TextViewPosition(document.GetLocation(segment.EndOffset), segment.EndVisualColumn);
}
}
TextViewPosition GetEnd()
{
SelectionSegment segment = (startLine < endLine ? segments.Last() : segments.First());
if (startXPos < endXPos) {
return new TextViewPosition(document.GetLocation(segment.EndOffset), segment.EndVisualColumn);
} else {
return new TextViewPosition(document.GetLocation(segment.StartOffset), segment.StartVisualColumn);
}
} }
#endregion
/// <inheritdoc/> /// <inheritdoc/>
public override string GetText() public override string GetText()
@ -135,22 +234,14 @@ namespace ICSharpCode.AvalonEdit.Editing
get { return segments; } get { return segments; }
} }
/// <inheritdoc/>
public override TextViewPosition StartPosition {
get { return start; }
}
void CalculateSegments() /// <inheritdoc/>
{ public override TextViewPosition EndPosition {
DocumentLine nextLine = document.GetLineByNumber(Math.Min(startLine, endLine)); get { return end; }
do {
VisualLine vl = textArea.TextView.GetOrConstructVisualLine(nextLine);
int startVC = vl.GetVisualColumn(new Point(startXPos, 0), true);
int endVC = vl.GetVisualColumn(new Point(endXPos, 0), true);
int baseOffset = vl.FirstDocumentLine.Offset;
int startOffset = baseOffset + vl.GetRelativeOffset(startVC);
int endOffset = baseOffset + vl.GetRelativeOffset(endVC);
segments.Add(new SelectionSegment(startOffset, startVC, endOffset, endVC));
nextLine = vl.LastDocumentLine.NextLine;
} while (nextLine != null && nextLine.LineNumber <= Math.Max(startLine, endLine));
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -175,6 +266,12 @@ namespace ICSharpCode.AvalonEdit.Editing
return new RectangleSelection(textArea, startLine, startXPos, endPosition); return new RectangleSelection(textArea, startLine, startXPos, endPosition);
} }
int GetVisualColumnFromXPos(int line, double xPos)
{
var vl = textArea.TextView.GetOrConstructVisualLine(textArea.Document.GetLineByNumber(line));
return vl.GetVisualColumn(new Point(xPos, 0), true);
}
/// <inheritdoc/> /// <inheritdoc/>
public override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e) public override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
{ {

10
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/Selection.cs

@ -65,6 +65,16 @@ namespace ICSharpCode.AvalonEdit.Editing
this.textArea = textArea; this.textArea = textArea;
} }
/// <summary>
/// Gets the start position of the selection.
/// </summary>
public abstract TextViewPosition StartPosition { get; }
/// <summary>
/// Gets the end position of the selection.
/// </summary>
public abstract TextViewPosition EndPosition { get; }
/// <summary> /// <summary>
/// Gets the selected text segments. /// Gets the selected text segments.
/// </summary> /// </summary>

14
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Editing/SimpleSelection.cs

@ -70,18 +70,12 @@ namespace ICSharpCode.AvalonEdit.Editing
} }
} }
/// <summary> public override TextViewPosition StartPosition {
/// Gets the start offset. get { return start; }
/// </summary>
public int StartOffset {
get { return startOffset; }
} }
/// <summary> public override TextViewPosition EndPosition {
/// Gets the end offset. get { return end; }
/// </summary>
public int EndOffset {
get { return endOffset; }
} }
/// <inheritdoc/> /// <inheritdoc/>

8
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/DocumentHighlighter.cs

@ -312,11 +312,14 @@ namespace ICSharpCode.AvalonEdit.Highlighting
Debug.Assert(position == firstMatch.Index); Debug.Assert(position == firstMatch.Index);
if (firstMatch == endSpanMatch) { if (firstMatch == endSpanMatch) {
PopColor(); // pop SpanColor
HighlightingSpan poppedSpan = spanStack.Peek(); HighlightingSpan poppedSpan = spanStack.Peek();
if (!poppedSpan.SpanColorIncludesEnd)
PopColor(); // pop SpanColor
PushColor(poppedSpan.EndColor); PushColor(poppedSpan.EndColor);
position = firstMatch.Index + firstMatch.Length; position = firstMatch.Index + firstMatch.Length;
PopColor(); // pop EndColor PopColor(); // pop EndColor
if (poppedSpan.SpanColorIncludesEnd)
PopColor(); // pop SpanColor
spanStack = spanStack.Pop(); spanStack = spanStack.Pop();
currentRuleSet = this.CurrentRuleSet; currentRuleSet = this.CurrentRuleSet;
//FreeMatchArray(matches); //FreeMatchArray(matches);
@ -342,9 +345,12 @@ namespace ICSharpCode.AvalonEdit.Highlighting
currentRuleSet = this.CurrentRuleSet; currentRuleSet = this.CurrentRuleSet;
storedMatchArrays.Push(matches); storedMatchArrays.Push(matches);
matches = AllocateMatchArray(currentRuleSet.Spans.Count); matches = AllocateMatchArray(currentRuleSet.Spans.Count);
if (newSpan.SpanColorIncludesStart)
PushColor(newSpan.SpanColor);
PushColor(newSpan.StartColor); PushColor(newSpan.StartColor);
position = firstMatch.Index + firstMatch.Length; position = firstMatch.Index + firstMatch.Length;
PopColor(); PopColor();
if (!newSpan.SpanColorIncludesStart)
PushColor(newSpan.SpanColor); PushColor(newSpan.SpanColor);
} }
endSpanMatch = null; endSpanMatch = null;

12
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/HighlightingSpan.cs

@ -43,6 +43,18 @@ namespace ICSharpCode.AvalonEdit.Highlighting
/// </summary> /// </summary>
public HighlightingColor EndColor { get; set; } public HighlightingColor EndColor { get; set; }
/// <summary>
/// Gets/Sets whether the span color includes the start.
/// The default is <c>false</c>.
/// </summary>
public bool SpanColorIncludesStart { get; set; }
/// <summary>
/// Gets/Sets whether the span color includes the end.
/// The default is <c>false</c>.
/// </summary>
public bool SpanColorIncludesEnd { get; set; }
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {

146
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/PowerShell.xshd

@ -0,0 +1,146 @@
<?xml version="1.0"?>
<SyntaxDefinition name="PowerShell" extensions=".ps1;.psm1;.psd1" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = &quot;Hello, World!&quot;"/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a)"/>
<Color name="Variable" foreground="Maroon" exampleText="$param = 1" />
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" />
<Color name="GotoKeywords" foreground="Navy" />
<Color name="ReferenceTypes" foreground="Red" />
<Color name="Command" fontWeight="bold" foreground="MidnightBlue" />
<Color name="Operators" foreground="#FF8515EA" exampleText="-eq"/>
<RuleSet ignoreCase="true">
<Span color="Comment">
<Begin>\#</Begin>
</Span>
<Span color="Comment" multiline="true">
<Begin>&lt;\#</Begin>
<End>\#&gt;</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin color="String">@"</Begin>
<End>"@</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Keywords color="Keywords">
<Word>while</Word>
<Word>param</Word>
<Word>end</Word>
<Word>define</Word>
<Word>else</Word>
<Word>from</Word>
<Word>foreach</Word>
<Word>var</Word>
<Word>dynamicparam</Word>
<Word>filter</Word>
<Word>dp</Word>
<Word>until</Word>
<Word>for</Word>
<Word>exit</Word>
<Word>switch</Word>
<Word>process</Word>
<Word>begin</Word>
<Word>elseif</Word>
<Word>if</Word>
<Word>in</Word>
<Word>data</Word>
<Word>class</Word>
<Word>using</Word>
<Word>function</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>catch</Word>
<Word>finally</Word>
<Word>throw</Word>
<Word>trap</Word>
<Word>try</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ReferenceTypes">
<Word>class</Word>
</Keywords>
<Keywords color="Operators">
<Word>-not</Word>
<Word>-band</Word>
<Word>-bor</Word>
<Word>-replace</Word>
<Word>-ireplace</Word>
<Word>-creplace</Word>
<Word>-and</Word>
<Word>-or</Word>
<Word>-is</Word>
<Word>-isnot</Word>
<Word>-as</Word>
<Word>-lt</Word>
<Word>-le</Word>
<Word>-gt</Word>
<Word>-ge</Word>
<Word>-eq</Word>
<Word>-ne</Word>
<Word>-contains</Word>
<Word>-notcontains</Word>
<Word>-like</Word>
<Word>-notlike</Word>
<Word>-match</Word>
<Word>-notmatch</Word>
</Keywords>
<Rule color="Variable">
\$[\d\w_]+
</Rule>
<Rule color="Command">
[\w]+-[\w]+
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*&lt;&gt;^+~!|&amp;]+
</Rule>
</RuleSet>
</SyntaxDefinition>

3
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/Resources.cs

@ -33,13 +33,14 @@ namespace ICSharpCode.AvalonEdit.Highlighting
hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp" , ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp" , ".hpp" }, "CPP-Mode.xshd");
hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd");
hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd");
hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd");
hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd");
hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd");
hlm.RegisterHighlighting("VBNET", new[] { ".vb" }, "VBNET-Mode.xshd"); hlm.RegisterHighlighting("VBNET", new[] { ".vb" }, "VBNET-Mode.xshd");
hlm.RegisterHighlighting("XML", (".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;" + hlm.RegisterHighlighting("XML", (".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;" +
".xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;" + ".xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;" +
".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" +
".xft;.map;.wsdl;.disco").Split(';'), ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'),
"XML-Mode.xshd"); "XML-Mode.xshd");
} }
} }

2
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Resources/XML-Mode.xshd

@ -1,4 +1,4 @@
<SyntaxDefinition name="XML" extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.booproj;.build;.xfrm;.targets;.xaml;.xpt;.xft;.map;.wsdl;.disco" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"> <SyntaxDefinition name="XML" extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.booproj;.build;.xfrm;.targets;.xaml;.xpt;.xft;.map;.wsdl;.disco;.ps1xml;.nuspec" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color foreground="Green" name="Comment" exampleText="&lt;!-- comment --&gt;" /> <Color foreground="Green" name="Comment" exampleText="&lt;!-- comment --&gt;" />
<Color foreground="Blue" name="CData" exampleText="&lt;![CDATA[data]]&gt;" /> <Color foreground="Blue" name="CData" exampleText="&lt;![CDATA[data]]&gt;" />
<Color foreground="Blue" name="DocType" exampleText="&lt;!DOCTYPE rootElement&gt;" /> <Color foreground="Blue" name="DocType" exampleText="&lt;!DOCTYPE rootElement&gt;" />

19
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Highlighting/Xshd/XmlHighlightingDefinition.cs

@ -317,22 +317,11 @@ namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
StartExpression = CreateRegex(span, span.BeginRegex, span.BeginRegexType), StartExpression = CreateRegex(span, span.BeginRegex, span.BeginRegexType),
EndExpression = CreateRegex(span, endRegex, span.EndRegexType), EndExpression = CreateRegex(span, endRegex, span.EndRegexType),
RuleSet = GetRuleSet(span, span.RuleSetReference), RuleSet = GetRuleSet(span, span.RuleSetReference),
StartColor = MergeColor(wholeSpanColor, GetColor(span, span.BeginColorReference)), StartColor = GetColor(span, span.BeginColorReference),
SpanColor = wholeSpanColor, SpanColor = wholeSpanColor,
EndColor = MergeColor(wholeSpanColor, GetColor(span, span.EndColorReference)), EndColor = GetColor(span, span.EndColorReference),
}; SpanColorIncludesStart = true,
} SpanColorIncludesEnd = true
static HighlightingColor MergeColor(HighlightingColor baseColor, HighlightingColor newColor)
{
if (baseColor == null)
return newColor;
if (newColor == null)
return baseColor;
return new HighlightingColor {
Foreground = newColor.Foreground ?? baseColor.Foreground,
FontWeight = newColor.FontWeight ?? baseColor.FontWeight,
FontStyle = newColor.FontStyle ?? baseColor.FontStyle,
}; };
} }

5
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/ICSharpCode.AvalonEdit.csproj

@ -146,7 +146,9 @@
<Compile Include="Editing\EmptySelection.cs"> <Compile Include="Editing\EmptySelection.cs">
<DependentUpon>Selection.cs</DependentUpon> <DependentUpon>Selection.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="Editing\ImeNativeWrapper.cs" />
<Compile Include="Editing\SelectionSegment.cs" /> <Compile Include="Editing\SelectionSegment.cs" />
<Compile Include="Editing\ImeSupport.cs" />
<Compile Include="Folding\AbstractFoldingStrategy.cs" /> <Compile Include="Folding\AbstractFoldingStrategy.cs" />
<Compile Include="Folding\FoldingElementGenerator.cs" /> <Compile Include="Folding\FoldingElementGenerator.cs" />
<Compile Include="Folding\FoldingManager.cs" /> <Compile Include="Folding\FoldingManager.cs" />
@ -440,4 +442,7 @@
<Resource Include="CodeCompletion\Images\Struct.png" /> <Resource Include="CodeCompletion\Images\Struct.png" />
<Resource Include="CodeCompletion\Images\VirtualMethod.png" /> <Resource Include="CodeCompletion\Images\VirtualMethod.png" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Highlighting\Resources\PowerShell.xshd" />
</ItemGroup>
</Project> </Project>

17
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/TextEditorOptions.cs

@ -381,5 +381,22 @@ namespace ICSharpCode.AvalonEdit
} }
} }
} }
bool enableImeSupport = true;
/// <summary>
/// Gets/Sets whether the support for Input Method Editors (IME)
/// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled.
/// </summary>
[DefaultValue(true)]
public virtual bool EnableImeSupport {
get { return enableImeSupport; }
set {
if (enableImeSupport != value) {
enableImeSupport = value;
OnPropertyChanged("EnableImeSupport");
}
}
}
} }
} }

65
src/Libraries/ICSharpCode.Decompiler/Ast/AstBuilder.cs

@ -157,15 +157,10 @@ namespace ICSharpCode.Decompiler.Ast
if (!transformationsHaveRun) if (!transformationsHaveRun)
RunTransformations(); RunTransformations();
astCompileUnit.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true }, null); astCompileUnit.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true });
var outputFormatter = new TextOutputFormatter(output); var outputFormatter = new TextOutputFormatter(output);
var formattingPolicy = new CSharpFormattingOptions(); var formattingPolicy = context.Settings.CSharpFormattingOptions;
// disable whitespace in front of parentheses: astCompileUnit.AcceptVisitor(new CSharpOutputVisitor(outputFormatter, formattingPolicy));
formattingPolicy.SpaceBeforeMethodCallParentheses = false;
formattingPolicy.SpaceBeforeMethodDeclarationParentheses = false;
formattingPolicy.SpaceBeforeConstructorDeclarationParentheses = false;
formattingPolicy.SpaceBeforeDelegateDeclarationParentheses = false;
astCompileUnit.AcceptVisitor(new CSharpOutputVisitor(outputFormatter, formattingPolicy), null);
} }
public void AddAssembly(AssemblyDefinition assemblyDefinition, bool onlyAssemblyLevel = false) public void AddAssembly(AssemblyDefinition assemblyDefinition, bool onlyAssemblyLevel = false)
@ -185,7 +180,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
} }
} }
}, AttributedNode.AttributeRole); }, EntityDeclaration.AttributeRole);
} }
ConvertCustomAttributes(astCompileUnit, assemblyDefinition, "assembly"); ConvertCustomAttributes(astCompileUnit, assemblyDefinition, "assembly");
@ -225,7 +220,7 @@ namespace ICSharpCode.Decompiler.Ast
Arguments = { forwardedType } Arguments = { forwardedType }
} }
} }
}, AttributedNode.AttributeRole); }, EntityDeclaration.AttributeRole);
} }
} }
} }
@ -283,7 +278,7 @@ namespace ICSharpCode.Decompiler.Ast
/// </summary> /// </summary>
/// <param name="typeDef"></param> /// <param name="typeDef"></param>
/// <returns>TypeDeclaration or DelegateDeclaration.</returns> /// <returns>TypeDeclaration or DelegateDeclaration.</returns>
public AttributedNode CreateType(TypeDefinition typeDef) public EntityDeclaration CreateType(TypeDefinition typeDef)
{ {
// create type // create type
TypeDefinition oldCurrentType = context.CurrentType; TypeDefinition oldCurrentType = context.CurrentType;
@ -313,7 +308,7 @@ namespace ICSharpCode.Decompiler.Ast
astType.TypeParameters.AddRange(MakeTypeParameters(genericParameters)); astType.TypeParameters.AddRange(MakeTypeParameters(genericParameters));
astType.Constraints.AddRange(MakeConstraints(genericParameters)); astType.Constraints.AddRange(MakeConstraints(genericParameters));
AttributedNode result = astType; EntityDeclaration result = astType;
if (typeDef.IsEnum) { if (typeDef.IsEnum) {
long expectedEnumMemberValue = 0; long expectedEnumMemberValue = 0;
bool forcePrintingInitializers = IsFlagsEnum(typeDef); bool forcePrintingInitializers = IsFlagsEnum(typeDef);
@ -321,7 +316,7 @@ namespace ICSharpCode.Decompiler.Ast
if (!field.IsStatic) { if (!field.IsStatic) {
// the value__ field // the value__ field
if (field.FieldType != typeDef.Module.TypeSystem.Int32) { if (field.FieldType != typeDef.Module.TypeSystem.Int32) {
astType.AddChild(ConvertType(field.FieldType), TypeDeclaration.BaseTypeRole); astType.AddChild(ConvertType(field.FieldType), Roles.BaseType);
} }
} else { } else {
EnumMemberDeclaration enumMember = new EnumMemberDeclaration(); EnumMemberDeclaration enumMember = new EnumMemberDeclaration();
@ -332,7 +327,7 @@ namespace ICSharpCode.Decompiler.Ast
enumMember.AddChild(new PrimitiveExpression(field.Constant), EnumMemberDeclaration.InitializerRole); enumMember.AddChild(new PrimitiveExpression(field.Constant), EnumMemberDeclaration.InitializerRole);
} }
expectedEnumMemberValue = memberValue + 1; expectedEnumMemberValue = memberValue + 1;
astType.AddChild(enumMember, TypeDeclaration.MemberRole); astType.AddChild(enumMember, Roles.TypeMemberRole);
} }
} }
} else if (typeDef.BaseType != null && typeDef.BaseType.FullName == "System.MulticastDelegate") { } else if (typeDef.BaseType != null && typeDef.BaseType.FullName == "System.MulticastDelegate") {
@ -354,10 +349,10 @@ namespace ICSharpCode.Decompiler.Ast
} else { } else {
// Base type // Base type
if (typeDef.BaseType != null && !typeDef.IsValueType && typeDef.BaseType.FullName != "System.Object") { if (typeDef.BaseType != null && !typeDef.IsValueType && typeDef.BaseType.FullName != "System.Object") {
astType.AddChild(ConvertType(typeDef.BaseType), TypeDeclaration.BaseTypeRole); astType.AddChild(ConvertType(typeDef.BaseType), Roles.BaseType);
} }
foreach (var i in typeDef.Interfaces) foreach (var i in typeDef.Interfaces)
astType.AddChild(ConvertType(i), TypeDeclaration.BaseTypeRole); astType.AddChild(ConvertType(i), Roles.BaseType);
AddTypeMembers(astType, typeDef); AddTypeMembers(astType, typeDef);
@ -726,18 +721,18 @@ namespace ICSharpCode.Decompiler.Ast
continue; continue;
var nestedType = CreateType(nestedTypeDef); var nestedType = CreateType(nestedTypeDef);
SetNewModifier(nestedType); SetNewModifier(nestedType);
astType.AddChild(nestedType, TypeDeclaration.MemberRole); astType.AddChild(nestedType, Roles.TypeMemberRole);
} }
// Add fields // Add fields
foreach(FieldDefinition fieldDef in typeDef.Fields) { foreach(FieldDefinition fieldDef in typeDef.Fields) {
if (MemberIsHidden(fieldDef, context.Settings)) continue; if (MemberIsHidden(fieldDef, context.Settings)) continue;
astType.AddChild(CreateField(fieldDef), TypeDeclaration.MemberRole); astType.AddChild(CreateField(fieldDef), Roles.TypeMemberRole);
} }
// Add events // Add events
foreach(EventDefinition eventDef in typeDef.Events) { foreach(EventDefinition eventDef in typeDef.Events) {
astType.AddChild(CreateEvent(eventDef), TypeDeclaration.MemberRole); astType.AddChild(CreateEvent(eventDef), Roles.TypeMemberRole);
} }
// Add properties // Add properties
@ -756,7 +751,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
} }
AttributedNode CreateMethod(MethodDefinition methodDef) EntityDeclaration CreateMethod(MethodDefinition methodDef)
{ {
MethodDeclaration astMethod = new MethodDeclaration(); MethodDeclaration astMethod = new MethodDeclaration();
astMethod.AddAnnotation(methodDef); astMethod.AddAnnotation(methodDef);
@ -860,7 +855,7 @@ namespace ICSharpCode.Decompiler.Ast
astMethod.Body = CreateMethodBody(methodDef, astMethod.Parameters); astMethod.Body = CreateMethodBody(methodDef, astMethod.Parameters);
ConvertAttributes(astMethod, methodDef); ConvertAttributes(astMethod, methodDef);
if (methodDef.IsStatic && methodDef.DeclaringType.IsBeforeFieldInit && !astMethod.Body.IsNull) { if (methodDef.IsStatic && methodDef.DeclaringType.IsBeforeFieldInit && !astMethod.Body.IsNull) {
astMethod.Body.InsertChildAfter(null, new Comment(" Note: this type is marked as 'beforefieldinit'."), AstNode.Roles.Comment); astMethod.Body.InsertChildAfter(null, new Comment(" Note: this type is marked as 'beforefieldinit'."), Roles.Comment);
} }
return astMethod; return astMethod;
} }
@ -878,7 +873,7 @@ namespace ICSharpCode.Decompiler.Ast
return m & ~Modifiers.Private; return m & ~Modifiers.Private;
} }
MemberDeclaration CreateProperty(PropertyDefinition propDef) EntityDeclaration CreateProperty(PropertyDefinition propDef)
{ {
PropertyDeclaration astProp = new PropertyDeclaration(); PropertyDeclaration astProp = new PropertyDeclaration();
astProp.AddAnnotation(propDef); astProp.AddAnnotation(propDef);
@ -937,7 +932,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
ConvertCustomAttributes(astProp, propDef); ConvertCustomAttributes(astProp, propDef);
MemberDeclaration member = astProp; EntityDeclaration member = astProp;
if(propDef.IsIndexer()) if(propDef.IsIndexer())
member = ConvertPropertyToIndexer(astProp, propDef); member = ConvertPropertyToIndexer(astProp, propDef);
if(!accessor.HasOverrides && !accessor.DeclaringType.IsInterface) if(!accessor.HasOverrides && !accessor.DeclaringType.IsInterface)
@ -960,7 +955,7 @@ namespace ICSharpCode.Decompiler.Ast
return astIndexer; return astIndexer;
} }
AttributedNode CreateEvent(EventDefinition eventDef) EntityDeclaration CreateEvent(EventDefinition eventDef)
{ {
if (eventDef.AddMethod != null && eventDef.AddMethod.IsAbstract) { if (eventDef.AddMethod != null && eventDef.AddMethod.IsAbstract) {
// An abstract event cannot be custom // An abstract event cannot be custom
@ -1018,7 +1013,7 @@ namespace ICSharpCode.Decompiler.Ast
FieldDeclaration astField = new FieldDeclaration(); FieldDeclaration astField = new FieldDeclaration();
astField.AddAnnotation(fieldDef); astField.AddAnnotation(fieldDef);
VariableInitializer initializer = new VariableInitializer(CleanName(fieldDef.Name)); VariableInitializer initializer = new VariableInitializer(CleanName(fieldDef.Name));
astField.AddChild(initializer, FieldDeclaration.Roles.Variable); astField.AddChild(initializer, Roles.Variable);
astField.ReturnType = ConvertType(fieldDef.FieldType, fieldDef); astField.ReturnType = ConvertType(fieldDef.FieldType, fieldDef);
astField.Modifiers = ConvertModifiers(fieldDef); astField.Modifiers = ConvertModifiers(fieldDef);
if (fieldDef.HasConstant) { if (fieldDef.HasConstant) {
@ -1098,7 +1093,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
#region ConvertAttributes #region ConvertAttributes
void ConvertAttributes(AttributedNode attributedNode, TypeDefinition typeDefinition) void ConvertAttributes(EntityDeclaration attributedNode, TypeDefinition typeDefinition)
{ {
ConvertCustomAttributes(attributedNode, typeDefinition); ConvertCustomAttributes(attributedNode, typeDefinition);
ConvertSecurityAttributes(attributedNode, typeDefinition); ConvertSecurityAttributes(attributedNode, typeDefinition);
@ -1154,7 +1149,7 @@ namespace ICSharpCode.Decompiler.Ast
#endregion #endregion
} }
void ConvertAttributes(AttributedNode attributedNode, MethodDefinition methodDefinition) void ConvertAttributes(EntityDeclaration attributedNode, MethodDefinition methodDefinition)
{ {
ConvertCustomAttributes(attributedNode, methodDefinition); ConvertCustomAttributes(attributedNode, methodDefinition);
ConvertSecurityAttributes(attributedNode, methodDefinition); ConvertSecurityAttributes(attributedNode, methodDefinition);
@ -1254,7 +1249,7 @@ namespace ICSharpCode.Decompiler.Ast
ConvertAttributes(attributedNode, methodDefinition.MethodReturnType, methodDefinition.Module); ConvertAttributes(attributedNode, methodDefinition.MethodReturnType, methodDefinition.Module);
} }
void ConvertAttributes(AttributedNode attributedNode, MethodReturnType methodReturnType, ModuleDefinition module) void ConvertAttributes(EntityDeclaration attributedNode, MethodReturnType methodReturnType, ModuleDefinition module)
{ {
ConvertCustomAttributes(attributedNode, methodReturnType, "return"); ConvertCustomAttributes(attributedNode, methodReturnType, "return");
if (methodReturnType.HasMarshalInfo) { if (methodReturnType.HasMarshalInfo) {
@ -1263,7 +1258,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
} }
internal static void ConvertAttributes(AttributedNode attributedNode, FieldDefinition fieldDefinition, string attributeTarget = null) internal static void ConvertAttributes(EntityDeclaration attributedNode, FieldDefinition fieldDefinition, string attributeTarget = null)
{ {
ConvertCustomAttributes(attributedNode, fieldDefinition); ConvertCustomAttributes(attributedNode, fieldDefinition);
@ -1402,14 +1397,14 @@ namespace ICSharpCode.Decompiler.Ast
var section = new AttributeSection(); var section = new AttributeSection();
section.AttributeTarget = attributeTarget; section.AttributeTarget = attributeTarget;
section.Attributes.Add(attribute); section.Attributes.Add(attribute);
attributedNode.AddChild(section, AttributedNode.AttributeRole); attributedNode.AddChild(section, EntityDeclaration.AttributeRole);
} }
} else if (attributes.Count > 0) { } else if (attributes.Count > 0) {
// use single section for all attributes // use single section for all attributes
var section = new AttributeSection(); var section = new AttributeSection();
section.AttributeTarget = attributeTarget; section.AttributeTarget = attributeTarget;
section.Attributes.AddRange(attributes); section.Attributes.AddRange(attributes);
attributedNode.AddChild(section, AttributedNode.AttributeRole); attributedNode.AddChild(section, EntityDeclaration.AttributeRole);
} }
} }
} }
@ -1462,14 +1457,14 @@ namespace ICSharpCode.Decompiler.Ast
var section = new AttributeSection(); var section = new AttributeSection();
section.AttributeTarget = attributeTarget; section.AttributeTarget = attributeTarget;
section.Attributes.Add(attribute); section.Attributes.Add(attribute);
attributedNode.AddChild(section, AttributedNode.AttributeRole); attributedNode.AddChild(section, EntityDeclaration.AttributeRole);
} }
} else if (attributes.Count > 0) { } else if (attributes.Count > 0) {
// use single section for all attributes // use single section for all attributes
var section = new AttributeSection(); var section = new AttributeSection();
section.AttributeTarget = attributeTarget; section.AttributeTarget = attributeTarget;
section.Attributes.AddRange(attributes); section.Attributes.AddRange(attributes);
attributedNode.AddChild(section, AttributedNode.AttributeRole); attributedNode.AddChild(section, EntityDeclaration.AttributeRole);
} }
} }
@ -1594,7 +1589,7 @@ namespace ICSharpCode.Decompiler.Ast
/// Sets new modifier if the member hides some other member from a base type. /// Sets new modifier if the member hides some other member from a base type.
/// </summary> /// </summary>
/// <param name="member">The node of the member which new modifier state should be determined.</param> /// <param name="member">The node of the member which new modifier state should be determined.</param>
static void SetNewModifier(AttributedNode member) static void SetNewModifier(EntityDeclaration member)
{ {
try { try {
bool addNewModifier = false; bool addNewModifier = false;
@ -1614,7 +1609,7 @@ namespace ICSharpCode.Decompiler.Ast
} }
} }
private static bool HidesBaseMember(AttributedNode member) private static bool HidesBaseMember(EntityDeclaration member)
{ {
var memberDefinition = member.Annotation<IMemberDefinition>(); var memberDefinition = member.Annotation<IMemberDefinition>();
bool addNewModifier = false; bool addNewModifier = false;

7
src/Libraries/ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs

@ -543,12 +543,15 @@ namespace ICSharpCode.Decompiler.Ast
} }
return arg1; return arg1;
} }
case ILCode.Castclass:
return arg1.CastTo(operandAsTypeRef);
case ILCode.Unbox_Any: case ILCode.Unbox_Any:
// unboxing does not require a cast if the argument was an isinst instruction // unboxing does not require a cast if the argument was an isinst instruction
if (arg1 is AsExpression && byteCode.Arguments[0].Code == ILCode.Isinst && TypeAnalysis.IsSameType(operand as TypeReference, byteCode.Arguments[0].Operand as TypeReference)) if (arg1 is AsExpression && byteCode.Arguments[0].Code == ILCode.Isinst && TypeAnalysis.IsSameType(operand as TypeReference, byteCode.Arguments[0].Operand as TypeReference))
return arg1; return arg1;
else
goto case ILCode.Castclass;
case ILCode.Castclass:
if ((byteCode.Arguments[0].InferredType != null && byteCode.Arguments[0].InferredType.IsGenericParameter) || ((Cecil.TypeReference)operand).IsGenericParameter)
return arg1.CastTo(new PrimitiveType("object")).CastTo(operandAsTypeRef);
else else
return arg1.CastTo(operandAsTypeRef); return arg1.CastTo(operandAsTypeRef);
case ILCode.Isinst: case ILCode.Isinst:

9
src/Libraries/ICSharpCode.Decompiler/Ast/CommentStatement.cs

@ -38,6 +38,15 @@ namespace ICSharpCode.Decompiler.Ast
this.comment = comment; this.comment = comment;
} }
public override void AcceptVisitor(IAstVisitor visitor)
{
}
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return default(T);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{ {
return default(S); return default(S);

16
src/Libraries/ICSharpCode.Decompiler/Ast/TextOutputFormatter.cs

@ -82,7 +82,7 @@ namespace ICSharpCode.Decompiler.Ast
{ {
AstNode node = nodeStack.Peek(); AstNode node = nodeStack.Peek();
MemberReference memberRef = node.Annotation<MemberReference>(); MemberReference memberRef = node.Annotation<MemberReference>();
if (memberRef == null && node.Role == AstNode.Roles.TargetExpression && (node.Parent is InvocationExpression || node.Parent is ObjectCreateExpression)) { if (memberRef == null && node.Role == Roles.TargetExpression && (node.Parent is InvocationExpression || node.Parent is ObjectCreateExpression)) {
memberRef = node.Parent.Annotation<MemberReference>(); memberRef = node.Parent.Annotation<MemberReference>();
} }
return memberRef; return memberRef;
@ -168,7 +168,7 @@ namespace ICSharpCode.Decompiler.Ast
// Attach member reference to token only if there's no identifier in the current node. // Attach member reference to token only if there's no identifier in the current node.
MemberReference memberRef = GetCurrentMemberReference(); MemberReference memberRef = GetCurrentMemberReference();
var node = nodeStack.Peek(); var node = nodeStack.Peek();
if (memberRef != null && node.GetChildByRole(AstNode.Roles.Identifier).IsNull) if (memberRef != null && node.GetChildByRole(Roles.Identifier).IsNull)
output.WriteReference(token, memberRef); output.WriteReference(token, memberRef);
else else
output.Write(token); output.Write(token);
@ -282,7 +282,7 @@ namespace ICSharpCode.Decompiler.Ast
nodeStack.Push(node); nodeStack.Push(node);
startLocations.Push(output.Location); startLocations.Push(output.Location);
if (node is AttributedNode && node.GetChildByRole(AstNode.Roles.Identifier).IsNull) if (node is EntityDeclaration && node.Annotation<MemberReference>() != null && node.GetChildByRole(Roles.Identifier).IsNull)
output.WriteDefinition("", node.Annotation<MemberReference>(), false); output.WriteDefinition("", node.Annotation<MemberReference>(), false);
MemberMapping mapping = node.Annotation<MemberMapping>(); MemberMapping mapping = node.Annotation<MemberMapping>();
@ -330,15 +330,7 @@ namespace ICSharpCode.Decompiler.Ast
private static bool IsDefinition(AstNode node) private static bool IsDefinition(AstNode node)
{ {
return return node is EntityDeclaration;
node is FieldDeclaration ||
node is ConstructorDeclaration ||
node is DestructorDeclaration ||
node is EventDeclaration ||
node is DelegateDeclaration ||
node is OperatorDeclaration||
node is MemberDeclaration ||
node is TypeDeclaration;
} }
} }
} }

2
src/Libraries/ICSharpCode.Decompiler/Ast/Transforms/ConvertConstructorCallIntoInitializer.cs

@ -123,7 +123,7 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
if (allSame) { if (allSame) {
foreach (var ctor in instanceCtorsNotChainingWithThis) foreach (var ctor in instanceCtorsNotChainingWithThis)
ctor.Body.First().Remove(); ctor.Body.First().Remove();
fieldOrEventDecl.GetChildrenByRole(AstNode.Roles.Variable).Single().Initializer = initializer.Detach(); fieldOrEventDecl.GetChildrenByRole(Roles.Variable).Single().Initializer = initializer.Detach();
} }
} while (allSame); } while (allSame);
} }

4
src/Libraries/ICSharpCode.Decompiler/Ast/Transforms/IntroduceUnsafeModifier.cs

@ -38,8 +38,8 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) { for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
result |= child.AcceptVisitor(this, data); result |= child.AcceptVisitor(this, data);
} }
if (result && node is AttributedNode && !(node is Accessor)) { if (result && node is EntityDeclaration && !(node is Accessor)) {
((AttributedNode)node).Modifiers |= Modifiers.Unsafe; ((EntityDeclaration)node).Modifiers |= Modifiers.Unsafe;
return false; return false;
} }
return result; return result;

2
src/Libraries/ICSharpCode.Decompiler/Ast/Transforms/ReplaceMethodCallsWithOperators.cs

@ -140,7 +140,7 @@ namespace ICSharpCode.Decompiler.Ast.Transforms
invocationExpression.ReplaceWith(arguments[0]); invocationExpression.ReplaceWith(arguments[0]);
return; return;
} }
if (methodRef.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == AstNode.Roles.Condition) { if (methodRef.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == Roles.Condition) {
invocationExpression.ReplaceWith(arguments[0]); invocationExpression.ReplaceWith(arguments[0]);
return; return;
} }

2
src/Libraries/ICSharpCode.Decompiler/CecilExtensions.cs

@ -133,6 +133,8 @@ namespace ICSharpCode.Decompiler
/// </summary> /// </summary>
public static int GetEndOffset(this Instruction inst) public static int GetEndOffset(this Instruction inst)
{ {
if (inst == null)
throw new ArgumentNullException("inst");
return inst.Offset + inst.GetSize(); return inst.Offset + inst.GetSize();
} }

23
src/Libraries/ICSharpCode.Decompiler/DecompilerSettings.cs

@ -18,6 +18,7 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using ICSharpCode.NRefactory.CSharp;
namespace ICSharpCode.Decompiler namespace ICSharpCode.Decompiler
{ {
@ -271,6 +272,26 @@ namespace ICSharpCode.Decompiler
} }
#endregion #endregion
CSharpFormattingOptions csharpFormattingOptions;
public CSharpFormattingOptions CSharpFormattingOptions {
get {
if (csharpFormattingOptions == null) {
csharpFormattingOptions = FormattingOptionsFactory.CreateAllman();
csharpFormattingOptions.IndentSwitchBody = false;
}
return csharpFormattingOptions;
}
set {
if (value == null)
throw new ArgumentNullException();
if (csharpFormattingOptions != value) {
csharpFormattingOptions = value;
OnPropertyChanged("CSharpFormattingOptions");
}
}
}
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) protected virtual void OnPropertyChanged(string propertyName)
@ -283,6 +304,8 @@ namespace ICSharpCode.Decompiler
public DecompilerSettings Clone() public DecompilerSettings Clone()
{ {
DecompilerSettings settings = (DecompilerSettings)MemberwiseClone(); DecompilerSettings settings = (DecompilerSettings)MemberwiseClone();
if (csharpFormattingOptions != null)
settings.csharpFormattingOptions = csharpFormattingOptions.Clone();
settings.PropertyChanged = null; settings.PropertyChanged = null;
return settings; return settings;
} }

11
src/Libraries/ICSharpCode.Decompiler/Disassembler/ReflectionDisassembler.cs

@ -809,6 +809,7 @@ namespace ICSharpCode.Decompiler.Disassembler
{ TypeAttributes.SpecialName, "specialname" }, { TypeAttributes.SpecialName, "specialname" },
{ TypeAttributes.Import, "import" }, { TypeAttributes.Import, "import" },
{ TypeAttributes.Serializable, "serializable" }, { TypeAttributes.Serializable, "serializable" },
{ TypeAttributes.WindowsRuntime, "windowsruntime" },
{ TypeAttributes.BeforeFieldInit, "beforefieldinit" }, { TypeAttributes.BeforeFieldInit, "beforefieldinit" },
{ TypeAttributes.HasSecurity, null }, { TypeAttributes.HasSecurity, null },
}; };
@ -1075,7 +1076,10 @@ namespace ICSharpCode.Decompiler.Disassembler
public void WriteAssemblyHeader(AssemblyDefinition asm) public void WriteAssemblyHeader(AssemblyDefinition asm)
{ {
output.Write(".assembly " + DisassemblerHelpers.Escape(asm.Name.Name)); output.Write(".assembly ");
if (asm.Name.IsWindowsRuntime)
output.Write("windowsruntime ");
output.Write(DisassemblerHelpers.Escape(asm.Name.Name));
OpenBlock(false); OpenBlock(false);
WriteAttributes(asm.CustomAttributes); WriteAttributes(asm.CustomAttributes);
WriteSecurityDeclarations(asm); WriteSecurityDeclarations(asm);
@ -1103,7 +1107,10 @@ namespace ICSharpCode.Decompiler.Disassembler
output.WriteLine(".module extern {0}", DisassemblerHelpers.Escape(mref.Name)); output.WriteLine(".module extern {0}", DisassemblerHelpers.Escape(mref.Name));
} }
foreach (var aref in module.AssemblyReferences) { foreach (var aref in module.AssemblyReferences) {
output.Write(".assembly extern {0}", DisassemblerHelpers.Escape(aref.Name)); output.Write(".assembly extern ");
if (aref.IsWindowsRuntime)
output.Write("windowsruntime ");
output.Write(DisassemblerHelpers.Escape(aref.Name));
OpenBlock(false); OpenBlock(false);
if (aref.PublicKeyToken != null) { if (aref.PublicKeyToken != null) {
output.Write(".publickeytoken = "); output.Write(".publickeytoken = ");

11
src/Libraries/ICSharpCode.Decompiler/FlowAnalysis/ControlFlowNode.cs

@ -253,8 +253,11 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
switch (NodeType) { switch (NodeType) {
case ControlFlowNodeType.Normal: case ControlFlowNodeType.Normal:
int endOffset = End.GetEndOffset(); writer.Write("Block #{0}", BlockIndex);
writer.Write("Block #{0}: IL_{1:x4} to IL_{2:x4}", BlockIndex, Start.Offset, endOffset); if (Start != null)
writer.Write(": IL_{0:x4}", Start.Offset);
if (End != null)
writer.Write(" to IL_{0:x4}", End.GetEndOffset());
break; break;
case ControlFlowNodeType.CatchHandler: case ControlFlowNodeType.CatchHandler:
case ControlFlowNodeType.FinallyOrFaultHandler: case ControlFlowNodeType.FinallyOrFaultHandler:
@ -277,6 +280,10 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
writer.WriteLine(); writer.WriteLine();
Disassembler.DisassemblerHelpers.WriteTo(inst, new PlainTextOutput(writer)); Disassembler.DisassemblerHelpers.WriteTo(inst, new PlainTextOutput(writer));
} }
if (UserData != null) {
writer.WriteLine();
writer.Write(UserData.ToString());
}
return writer.ToString(); return writer.ToString();
} }

36
src/Libraries/ICSharpCode.Decompiler/ILAst/LoopsAndConditions.cs

@ -101,7 +101,7 @@ namespace ICSharpCode.Decompiler.ILAst
// Find all branches // Find all branches
foreach(ILLabel target in node.GetSelfAndChildrenRecursive<ILExpression>(e => e.IsBranch()).SelectMany(e => e.GetBranchTargets())) { foreach(ILLabel target in node.GetSelfAndChildrenRecursive<ILExpression>(e => e.IsBranch()).SelectMany(e => e.GetBranchTargets())) {
ControlFlowNode destination; ControlFlowNode destination;
// Labels which are out of out scope will not be int the collection // Labels which are out of out scope will not be in the collection
// Insert self edge only if we are sure we are a loop // Insert self edge only if we are sure we are a loop
if (labelToCfNode.TryGetValue(target, out destination) && (destination != source || target == node.Body.FirstOrDefault())) { if (labelToCfNode.TryGetValue(target, out destination) && (destination != source || target == node.Body.FirstOrDefault())) {
ControlFlowEdge edge = new ControlFlowEdge(source, destination, JumpType.Normal); ControlFlowEdge edge = new ControlFlowEdge(source, destination, JumpType.Normal);
@ -228,15 +228,10 @@ namespace ICSharpCode.Decompiler.ILAst
// Do not modify entry data // Do not modify entry data
scope = new HashSet<ControlFlowNode>(scope); scope = new HashSet<ControlFlowNode>(scope);
HashSet<ControlFlowNode> agenda = new HashSet<ControlFlowNode>(); Stack<ControlFlowNode> agenda = new Stack<ControlFlowNode>();
agenda.Add(entryNode); agenda.Push(entryNode);
while(agenda.Any()) { while(agenda.Count > 0) {
ControlFlowNode node = agenda.First(); ControlFlowNode node = agenda.Pop();
// Attempt for a good order
while(agenda.Contains(node.ImmediateDominator)) {
node = node.ImmediateDominator;
}
agenda.Remove(node);
// Find a block that represents a simple condition // Find a block that represents a simple condition
if (scope.Contains(node)) { if (scope.Contains(node)) {
@ -364,18 +359,12 @@ namespace ICSharpCode.Decompiler.ILAst
labelToCfNode.TryGetValue(falseLabel, out falseTarget); labelToCfNode.TryGetValue(falseLabel, out falseTarget);
// Pull in the conditional code // Pull in the conditional code
HashSet<ControlFlowNode> frontiers = new HashSet<ControlFlowNode>(); if (trueTarget != null && HasSingleEdgeEnteringBlock(trueTarget)) {
if (trueTarget != null)
frontiers.UnionWith(trueTarget.DominanceFrontier.Except(new [] { trueTarget }));
if (falseTarget != null)
frontiers.UnionWith(falseTarget.DominanceFrontier.Except(new [] { falseTarget }));
if (trueTarget != null && !frontiers.Contains(trueTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, trueTarget); HashSet<ControlFlowNode> content = FindDominatedNodes(scope, trueTarget);
scope.ExceptWith(content); scope.ExceptWith(content);
ilCond.TrueBlock.Body.AddRange(FindConditions(content, trueTarget)); ilCond.TrueBlock.Body.AddRange(FindConditions(content, trueTarget));
} }
if (falseTarget != null && !frontiers.Contains(falseTarget)) { if (falseTarget != null && HasSingleEdgeEnteringBlock(falseTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, falseTarget); HashSet<ControlFlowNode> content = FindDominatedNodes(scope, falseTarget);
scope.ExceptWith(content); scope.ExceptWith(content);
ilCond.FalseBlock.Body.AddRange(FindConditions(content, falseTarget)); ilCond.FalseBlock.Body.AddRange(FindConditions(content, falseTarget));
@ -390,9 +379,9 @@ namespace ICSharpCode.Decompiler.ILAst
} }
} }
// Using the dominator tree should ensure we find the the widest loop first // depth-first traversal of dominator tree
foreach(var child in node.DominatorTreeChildren) { for (int i = node.DominatorTreeChildren.Count - 1; i >= 0; i--) {
agenda.Add(child); agenda.Push(node.DominatorTreeChildren[i]);
} }
} }
@ -404,6 +393,11 @@ namespace ICSharpCode.Decompiler.ILAst
return result; return result;
} }
static bool HasSingleEdgeEnteringBlock(ControlFlowNode node)
{
return node.Incoming.Count(edge => !node.Dominates(edge.Source)) == 1;
}
static HashSet<ControlFlowNode> FindDominatedNodes(HashSet<ControlFlowNode> scope, ControlFlowNode head) static HashSet<ControlFlowNode> FindDominatedNodes(HashSet<ControlFlowNode> scope, ControlFlowNode head)
{ {
HashSet<ControlFlowNode> agenda = new HashSet<ControlFlowNode>(); HashSet<ControlFlowNode> agenda = new HashSet<ControlFlowNode>();

25
src/Libraries/ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs

@ -985,12 +985,24 @@ namespace ICSharpCode.Decompiler.ILAst
InferTypeForExpression(right, typeSystem.IntPtr); InferTypeForExpression(right, typeSystem.IntPtr);
return leftPreferred; return leftPreferred;
} }
if (IsEnum(leftPreferred)) {
//E+U=E
left.InferredType = left.ExpectedType = leftPreferred;
InferTypeForExpression(right, GetEnumUnderlyingType(leftPreferred));
return leftPreferred;
}
TypeReference rightPreferred = DoInferTypeForExpression(right, expectedType); TypeReference rightPreferred = DoInferTypeForExpression(right, expectedType);
if (rightPreferred is PointerType) { if (rightPreferred is PointerType) {
InferTypeForExpression(left, typeSystem.IntPtr); InferTypeForExpression(left, typeSystem.IntPtr);
right.InferredType = right.ExpectedType = rightPreferred; right.InferredType = right.ExpectedType = rightPreferred;
return rightPreferred; return rightPreferred;
} }
if (IsEnum(rightPreferred)) {
//U+E=E
right.InferredType = right.ExpectedType = rightPreferred;
InferTypeForExpression(left, GetEnumUnderlyingType(rightPreferred));
return rightPreferred;
}
return InferBinaryArguments(left, right, expectedType, leftPreferred: leftPreferred, rightPreferred: rightPreferred); return InferBinaryArguments(left, right, expectedType, leftPreferred: leftPreferred, rightPreferred: rightPreferred);
} }
@ -1004,6 +1016,19 @@ namespace ICSharpCode.Decompiler.ILAst
InferTypeForExpression(right, typeSystem.IntPtr); InferTypeForExpression(right, typeSystem.IntPtr);
return leftPreferred; return leftPreferred;
} }
if (IsEnum(leftPreferred)) {
if (expectedType != null && IsEnum(expectedType)) {
// E-U=E
left.InferredType = left.ExpectedType = leftPreferred;
InferTypeForExpression(right, GetEnumUnderlyingType(leftPreferred));
return leftPreferred;
} else {
// E-E=U
left.InferredType = left.ExpectedType = leftPreferred;
InferTypeForExpression(right, leftPreferred);
return GetEnumUnderlyingType(leftPreferred);
}
}
return InferBinaryArguments(left, right, expectedType, leftPreferred: leftPreferred); return InferBinaryArguments(left, right, expectedType, leftPreferred: leftPreferred);
} }

4
src/Libraries/ICSharpCode.Decompiler/Properties/AssemblyInfo.cs

@ -19,8 +19,8 @@ using System.Runtime.InteropServices;
// If you need to expose a type to COM, use [ComVisible(true)] on that type. // If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.0.0.1489")] [assembly: AssemblyVersion("2.0.0.1595")]
[assembly: AssemblyInformationalVersion("2.0.0.1489-774e3cd8")] [assembly: AssemblyInformationalVersion("2.0.0.1595-5773d3d2")]
[assembly: NeutralResourcesLanguage("en-US")] [assembly: NeutralResourcesLanguage("en-US")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly",

81
src/Libraries/ICSharpCode.Decompiler/Tests/ControlFlow.cs

@ -0,0 +1,81 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
public static class ControlFlow
{
public static void EmptyIf(string input, List<string> value, Dictionary<int, string> _headers)
{
if (value.Contains("test"))
{
}
_headers.Add(2, "result");
}
public static void NormalIf(string input, List<string> value, Dictionary<int, string> _headers)
{
if (value.Contains("test"))
{
_headers.Add(1, "result");
}
else
{
_headers.Add(1, "else");
}
_headers.Add(2, "end");
}
public static void NormalIf2(string input, List<string> value, Dictionary<int, string> _headers)
{
if (value.Contains("test"))
{
_headers.Add(1, "result");
}
_headers.Add(2, "end");
}
public static void NormalIf3(string input, List<string> value, Dictionary<int, string> _headers)
{
if (value.Contains("test"))
{
_headers.Add(1, "result");
}
else
{
_headers.Add(1, "else");
}
}
public static void Test(string input, List<string> value, Dictionary<int, string> _headers)
{
foreach (string current in value)
{
_headers.Add(0, current);
}
if (value.Contains("test"))
{
_headers.Add(1, "result");
}
else
{
_headers.Add(1, "else");
}
}
}

55
src/Libraries/ICSharpCode.Decompiler/Tests/Generics.cs

@ -107,4 +107,59 @@ public static class Generics
// Tests references to inner classes in generic classes // Tests references to inner classes in generic classes
return d.Keys.GetEnumerator(); return d.Keys.GetEnumerator();
} }
public static bool IsString<T>(T input)
{
return input is string;
}
public static string AsString<T>(T input)
{
return input as string;
}
public static string CastToString<T>(T input)
{
return (string)((object)input);
}
public static T CastFromString<T>(string input)
{
return (T)((object)input);
}
public static bool IsInt<T>(T input)
{
return input is int;
}
public static int CastToInt<T>(T input)
{
return (int)((object)input);
}
public static T CastFromInt<T>(int input)
{
return (T)((object)input);
}
public static bool IsNullableInt<T>(T input)
{
return input is int?;
}
public static int? AsNullableInt<T>(T input)
{
return input as int?;
}
public static int? CastToNullableInt<T>(T input)
{
return (int?)((object)input);
}
public static T CastFromNullableInt<T>(int? input)
{
return (T)((object)input);
}
} }

2
src/Libraries/ICSharpCode.Decompiler/Tests/Helpers/RemoveCompilerAttribute.cs

@ -15,7 +15,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
var section = (AttributeSection)attribute.Parent; var section = (AttributeSection)attribute.Parent;
SimpleType type = attribute.Type as SimpleType; SimpleType type = attribute.Type as SimpleType;
if (section.AttributeTarget == "assembly" && if (section.AttributeTarget == "assembly" &&
(type.Identifier == "CompilationRelaxations" || type.Identifier == "RuntimeCompatibility" || type.Identifier == "SecurityPermission" || type.Identifier == "AssemblyVersion")) (type.Identifier == "CompilationRelaxations" || type.Identifier == "RuntimeCompatibility" || type.Identifier == "SecurityPermission" || type.Identifier == "AssemblyVersion" || type.Identifier == "Debuggable"))
{ {
attribute.Remove(); attribute.Remove();
if (section.Attributes.Count == 0) if (section.Attributes.Count == 0)

12
src/Libraries/ICSharpCode.Decompiler/Tests/ICSharpCode.Decompiler.Tests.csproj

@ -64,7 +64,10 @@
<ItemGroup> <ItemGroup>
<Compile Include="CallOverloadedMethod.cs" /> <Compile Include="CallOverloadedMethod.cs" />
<Compile Include="CheckedUnchecked.cs" /> <Compile Include="CheckedUnchecked.cs" />
<Compile Include="ControlFlow.cs" />
<Compile Include="ExpressionTrees.cs" /> <Compile Include="ExpressionTrees.cs" />
<None Include="IL\SequenceOfNestedIfs.Output.cs" />
<Compile Include="IL\ILTests.cs" />
<Compile Include="LiftedOperators.cs" /> <Compile Include="LiftedOperators.cs" />
<Compile Include="CustomShortCircuitOperators.cs" /> <Compile Include="CustomShortCircuitOperators.cs" />
<Compile Include="Helpers\CodeAssert.cs" /> <Compile Include="Helpers\CodeAssert.cs" />
@ -77,6 +80,10 @@
<Compile Include="UnsafeCode.cs" /> <Compile Include="UnsafeCode.cs" />
<Compile Include="Types\S_TypeDeclarations.cs" /> <Compile Include="Types\S_TypeDeclarations.cs" />
<Compile Include="YieldReturn.cs" /> <Compile Include="YieldReturn.cs" />
<None Include="IL\SequenceOfNestedIfs.dll" />
<None Include="IL\SequenceOfNestedIfs.il" />
<None Include="IL\StackTests.exe" />
<None Include="IL\StackTests.il" />
<None Include="packages.config" /> <None Include="packages.config" />
<None Include="Types\S_EnumSamples.cs" /> <None Include="Types\S_EnumSamples.cs" />
<None Include="CustomAttributes\S_AssemblyCustomAttribute.cs" /> <None Include="CustomAttributes\S_AssemblyCustomAttribute.cs" />
@ -117,10 +124,11 @@
<Name>ICSharpCode.Decompiler</Name> <Name>ICSharpCode.Decompiler</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup>
<Folder Include="IL" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="BooleanConsumedAsInteger.il" /> <None Include="BooleanConsumedAsInteger.il" />
<None Include="StackTests\StackTests.il" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
</Project> </Project>

51
src/Libraries/ICSharpCode.Decompiler/Tests/IL/ILTests.cs

@ -0,0 +1,51 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using ICSharpCode.Decompiler.Ast;
using ICSharpCode.Decompiler.Tests.Helpers;
using Mono.Cecil;
using NUnit.Framework;
namespace ICSharpCode.Decompiler.Tests
{
[TestFixture]
public class ILTests
{
const string path = "../../Tests/IL";
[Test]
public void SequenceOfNestedIfs()
{
Run("SequenceOfNestedIfs.dll", "SequenceOfNestedIfs.Output.cs");
}
void Run(string compiledFile, string expectedOutputFile)
{
string expectedOutput = File.ReadAllText(Path.Combine(path, expectedOutputFile));
var assembly = AssemblyDefinition.ReadAssembly(Path.Combine(path, compiledFile));
AstBuilder decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule));
decompiler.AddAssembly(assembly);
new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit);
StringWriter output = new StringWriter();
decompiler.GenerateCode(new PlainTextOutput(output));
CodeAssert.AreEqual(expectedOutput, output.ToString());
}
}
}

53
src/Libraries/ICSharpCode.Decompiler/Tests/IL/SequenceOfNestedIfs.Output.cs

@ -0,0 +1,53 @@
using System;
[Serializable]
public class Material
{
public static implicit operator bool(Material m)
{
return m == null;
}
}
[Serializable]
public class SequenceOfNestedIfs
{
public bool _clear;
public Material _material;
public override bool CheckShader()
{
return false;
}
public override void CreateMaterials()
{
if (!this._clear)
{
if (!this.CheckShader())
{
return;
}
this._material = new Material();
}
if (!this._material)
{
if (!this.CheckShader())
{
return;
}
this._material = new Material();
}
if (!this._material)
{
if (!this.CheckShader())
{
return;
}
this._material = new Material();
}
if (!this._material)
{
if (this.CheckShader())
{
this._material = new Material();
}
}
}
}

BIN
src/Libraries/ICSharpCode.Decompiler/Tests/IL/SequenceOfNestedIfs.dll

Binary file not shown.

140
src/Libraries/ICSharpCode.Decompiler/Tests/IL/SequenceOfNestedIfs.il

@ -0,0 +1,140 @@
// Metadata version: v2.0.50727
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 2:0:0:0
}
.assembly SequenceOfNestedIfs
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows.
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module SequenceOfNestedIfs
// MVID: {DCEC8A87-5679-4EBE-89A3-51274D8B5446}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
// Image base: 0x01D60000
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi serializable beforefieldinit Material
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Material::.ctor
.method public hidebysig specialname static
bool op_Implicit(class Material m) cil managed
{
// Code size 11 (0xb)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldnull
IL_0008: ceq
IL_000a: ret
} // end of method Material::op_Implicit
} // end of class Material
.class public auto ansi serializable beforefieldinit SequenceOfNestedIfs
extends [mscorlib]System.Object
{
.field public bool _clear
.field public class Material _material
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method SequenceOfNestedIfs::.ctor
.method public hidebysig virtual instance bool
CheckShader() cil managed
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: ret
} // end of method SequenceOfNestedIfs::CheckShader
.method public hidebysig virtual instance void
CreateMaterials() cil managed
{
// Code size 168 (0xa8)
.maxstack 13
IL_0000: ldarg.0
IL_0001: ldfld bool SequenceOfNestedIfs::_clear
IL_0006: brtrue IL_0026
IL_000b: ldarg.0
IL_000c: callvirt instance bool SequenceOfNestedIfs::CheckShader()
IL_0011: brtrue IL_001b
IL_0016: br IL_00a7
IL_001b: ldarg.0
IL_001c: newobj instance void Material::.ctor()
IL_0021: stfld class Material SequenceOfNestedIfs::_material
IL_0026: ldarg.0
IL_0027: ldfld class Material SequenceOfNestedIfs::_material
IL_002c: call bool Material::op_Implicit(class Material)
IL_0031: brtrue IL_0051
IL_0036: ldarg.0
IL_0037: callvirt instance bool SequenceOfNestedIfs::CheckShader()
IL_003c: brtrue IL_0046
IL_0041: br IL_00a7
IL_0046: ldarg.0
IL_0047: newobj instance void Material::.ctor()
IL_004c: stfld class Material SequenceOfNestedIfs::_material
IL_0051: ldarg.0
IL_0052: ldfld class Material SequenceOfNestedIfs::_material
IL_0057: call bool Material::op_Implicit(class Material)
IL_005c: brtrue IL_007c
IL_0061: ldarg.0
IL_0062: callvirt instance bool SequenceOfNestedIfs::CheckShader()
IL_0067: brtrue IL_0071
IL_006c: br IL_00a7
IL_0071: ldarg.0
IL_0072: newobj instance void Material::.ctor()
IL_0077: stfld class Material SequenceOfNestedIfs::_material
IL_007c: ldarg.0
IL_007d: ldfld class Material SequenceOfNestedIfs::_material
IL_0082: call bool Material::op_Implicit(class Material)
IL_0087: brtrue IL_00a7
IL_008c: ldarg.0
IL_008d: callvirt instance bool SequenceOfNestedIfs::CheckShader()
IL_0092: brtrue IL_009c
IL_0097: br IL_00a7
IL_009c: ldarg.0
IL_009d: newobj instance void Material::.ctor()
IL_00a2: stfld class Material SequenceOfNestedIfs::_material
IL_00a7: ret
} // end of method SequenceOfNestedIfs::CreateMaterials
} // end of class SequenceOfNestedIfs

0
src/Libraries/ICSharpCode.Decompiler/Tests/StackTests/StackTests.exe → src/Libraries/ICSharpCode.Decompiler/Tests/IL/StackTests.exe

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save