Yes, this one is the initial commit :)

This commit is contained in:
Súper JMN 2015-04-28 13:29:30 +02:00
Родитель 86295f98aa
Коммит aabcf77b24
203 изменённых файлов: 9578 добавлений и 1287 удалений

30
.gitignore поставляемый
Просмотреть файл

@ -1,11 +1,18 @@
# Created by https://www.gitignore.io
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
@ -18,14 +25,14 @@ bld/
[Bb]in/
[Oo]bj/
# Roslyn cache directories
*.ide/
# Visual Studo 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
#NUNIT
# NUNIT
*.VisualState.xml
TestResult.xml
@ -136,7 +143,7 @@ publish/
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# If using the old MSBuild-Integrated Package Restore, uncomment this:
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
@ -147,8 +154,7 @@ csx/
AppPackages/
# Others
sql/
*.Cache
*.[Cc]ache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
@ -158,6 +164,7 @@ ClientBin/
*.pfx
*.publishsettings
node_modules/
bower_components/
# RIA/Silverlight projects
Generated_Code/
@ -181,3 +188,14 @@ UpgradeLog*.htm
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
*.FileListAbsolute.txt

205
GitTemplate.12.xaml Normal file
Просмотреть файл

@ -0,0 +1,205 @@
<Activity mc:Ignorable="sads sap sap2010" x:Class="TfsBuild.Process" this:Process.AutomatedTests="[{ New Microsoft.TeamFoundation.Build.Common.BuildParameter(&quot; { &quot;&quot;AssemblyFileSpec&quot;&quot;: &quot;&quot;**\\*test*.dll;**\\*test*.appx&quot;&quot;, &quot;&quot;RunSettingsFileName&quot;&quot;: null, &quot;&quot;TestCaseFilter&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;RunSettingsForTestRun&quot;&quot;: { &quot;&quot;ServerRunSettingsFile&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;TypeRunSettings&quot;&quot;: &quot;&quot;Default&quot;&quot;, &quot;&quot;HasRunSettingsFile&quot;&quot;: false }, &quot;&quot;HasRunSettingsFile&quot;&quot;: false, &quot;&quot;HasTestCaseFilter&quot;&quot;: false, &quot;&quot;ExecutionPlatform&quot;&quot;: &quot;&quot;X86&quot;&quot;, &quot;&quot;FailBuildOnFailure&quot;&quot;: false, &quot;&quot;RunName&quot;&quot;: &quot;&quot;&quot;&quot; } &quot;) }]" this:Process.AdvancedTestSettings="[New Microsoft.TeamFoundation.Build.Common.BuildParameter(&quot; { &quot;&quot;DisableTests&quot;&quot;: false, &quot;&quot;PreActionScriptPath&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;PreActionScriptArguments&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;PostActionScriptPath&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;PostActionScriptArguments&quot;&quot;: &quot;&quot;&quot;&quot; } &quot;)]" this:Process.BuildNumberFormat="[&quot;$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)&quot;]" this:Process.CleanRepository="[True]" this:Process.AdvancedBuildSettings="[New Microsoft.TeamFoundation.Build.Common.BuildParameter(&quot; { &quot;&quot;MSBuildArguments&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;MSBuildPlatform&quot;&quot;: &quot;&quot;Auto&quot;&quot;, &quot;&quot;PreActionScriptPath&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;PreActionScriptArguments&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;PostActionScriptPath&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;PostActionScriptArguments&quot;&quot;: &quot;&quot;&quot;&quot;, &quot;&quot;RunCodeAnalysis&quot;&quot;: &quot;&quot;AsConfigured&quot;&quot; } &quot;)]" this:Process.AgentSettings="[New Microsoft.TeamFoundation.Build.Common.BuildParameter(&quot; { &quot;&quot;MaxExecutionTime&quot;&quot;: &quot;&quot;00:00:00&quot;&quot;, &quot;&quot;MaxWaitTime&quot;&quot;: &quot;&quot;04:00:00&quot;&quot;, &quot;&quot;Name&quot;&quot;: &quot;&quot;*&quot;&quot;, &quot;&quot;Tags&quot;&quot;: [], &quot;&quot;TagComparison&quot;&quot;: &quot;&quot;MatchExactly&quot;&quot; } &quot;)]" this:Process.CleanBuild="[True]" this:Process.OutputLocation="[&quot;SingleFolder&quot;]" this:Process.CreateWorkItem="[True]" this:Process.UpdateAssociatedWorkItems="[True]" this:Process.SupportedReasons="Manual, IndividualCI, BatchedCI, Schedule, ScheduleForced, UserCreated" this:Process.BuildProcessVersion="12.0"
xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mt="clr-namespace:Microsoft.TeamFoundation;assembly=Microsoft.TeamFoundation.Common"
xmlns:mtba="clr-namespace:Microsoft.TeamFoundation.Build.Activities;assembly=Microsoft.TeamFoundation.Build.Activities"
xmlns:mtbac="clr-namespace:Microsoft.TeamFoundation.Build.Activities.Core;assembly=Microsoft.TeamFoundation.Build.Activities"
xmlns:mtbag="clr-namespace:Microsoft.TeamFoundation.Build.Activities.Git;assembly=Microsoft.TeamFoundation.Build.Activities"
xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Common;assembly=Microsoft.TeamFoundation.Build.Common"
xmlns:mtbc1="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client"
xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow"
xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow"
xmlns:mtbwt="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Tracking;assembly=Microsoft.TeamFoundation.Build.Workflow"
xmlns:mttbb="clr-namespace:Microsoft.TeamFoundation.TestImpact.BuildIntegration.BuildActivities;assembly=Microsoft.TeamFoundation.TestImpact.BuildIntegration"
xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client"
xmlns:mtvc1="clr-namespace:Microsoft.TeamFoundation.VersionControl.Common;assembly=Microsoft.TeamFoundation.VersionControl.Common"
xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:sad="clr-namespace:System.Activities.Debugger;assembly=System.Activities"
xmlns:sads="http://schemas.microsoft.com/netfx/2010/xaml/activities/debugger"
xmlns:sap="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation"
xmlns:sap2010="http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation"
xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib"
xmlns:sl="clr-namespace:System.Linq;assembly=System.Core"
xmlns:this="clr-namespace:TfsBuild"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="ProjectsToBuild" Type="InArgument(s:String[])" />
<x:Property Name="ConfigurationsToBuild" Type="InArgument(s:String[])" />
<x:Property Name="AutomatedTests" Type="InArgument(mtbc:BuildParameter[])" />
<x:Property Name="AdvancedTestSettings" Type="InArgument(mtbc:BuildParameter)" />
<x:Property Name="BuildNumberFormat" Type="InArgument(x:String)" />
<x:Property Name="CleanRepository" Type="InArgument(x:Boolean)" />
<x:Property Name="AdvancedBuildSettings" Type="InArgument(mtbc:BuildParameter)" />
<x:Property Name="AgentSettings" Type="InArgument(mtbc:BuildParameter)" />
<x:Property Name="CleanBuild" Type="InArgument(x:Boolean)" />
<x:Property Name="CheckoutOverride" Type="InArgument(x:String)" />
<x:Property Name="OutputLocation" Type="InArgument(x:String)" />
<x:Property Name="SymbolStorePath" Type="InArgument(x:String)" />
<x:Property Name="CreateWorkItem" Type="InArgument(x:Boolean)" />
<x:Property Name="UpdateAssociatedWorkItems" Type="InArgument(x:Boolean)" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="SupportedReasons" Type="mtbc1:BuildReason" />
<x:Property Name="BuildProcessVersion" Type="x:String" />
</x:Members>
<this:Process.ProjectsToBuild>
<InArgument x:TypeArguments="s:String[]" />
</this:Process.ProjectsToBuild>
<this:Process.ConfigurationsToBuild>
<InArgument x:TypeArguments="s:String[]" />
</this:Process.ConfigurationsToBuild>
<this:Process.CheckoutOverride>
<InArgument x:TypeArguments="x:String" />
</this:Process.CheckoutOverride>
<this:Process.SymbolStorePath>
<InArgument x:TypeArguments="x:String" />
</this:Process.SymbolStorePath>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection>
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#100 Git" Description="Set this to true to start with a clean repository on each build." DisplayName="1. Clean repository" ParameterName="CleanRepository" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#100 Git" Description="Specify the id of a checkout to override the default branch and commit." DisplayName="2. Checkout override" ParameterName="CheckoutOverride" />
<mtbw:ProcessParameterMetadata Category="#200 Build" Description="Relative paths to the solution/project files you want to build." DisplayName="1. Projects" Editor="Microsoft.TeamFoundation.Build.Controls.BuildProjectListRelativePathEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="ProjectsToBuild" Required="True" />
<mtbw:ProcessParameterMetadata Category="#200 Build" Description="Specify the configurations you want to build (i.e. Debug|x86)." DisplayName="2. Configurations" Editor="Microsoft.TeamFoundation.Build.Controls.PlatformConfigurationListEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="ConfigurationsToBuild" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#200 Build" Description="Set this to true to perform a clean build." DisplayName="3. Clean build" ParameterName="CleanBuild" />
<mtbw:ProcessParameterMetadata Category="#200 Build" Description="Specify the type of location that outputs should be created in: SingleFolder, PerProject, AsConfigured." DisplayName="4. Output location" Editor="@DropDownList=SingleFolder,PerProject,AsConfigured" ParameterName="OutputLocation" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#200 Build" Description="" DisplayName="5. Advanced" ParameterName="AdvancedBuildSettings" ValueFormatString=" " />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify additional MSBuild arguments." DisplayName="MSBuild arguments" ParameterName="AdvancedBuildSettings.MSBuildArguments" />
<mtbw:ProcessParameterMetadata Description="Specify the MSBuild platform to use. Defaults to the OS." DisplayName="MSBuild platform" Editor="@DropDownList=Auto,X86" ParameterName="AdvancedBuildSettings.MSBuildPlatform" />
<mtbw:ProcessParameterMetadata Description="Specify the path to a custom script that runs before the MSBuild activity starts." DisplayName="Pre-build script path" Editor="Microsoft.TeamFoundation.Build.Controls.GitLocalFileBrowserEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AdvancedBuildSettings.PreActionScriptPath" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify the command line arguments to pass to the script that runs before the MSBuild activity starts." DisplayName="Pre-build script arguments" ParameterName="AdvancedBuildSettings.PreActionScriptArguments" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify the path to a custom script that runs after the MSBuild activity successfully completes." DisplayName="Post-build script path" Editor="Microsoft.TeamFoundation.Build.Controls.GitLocalFileBrowserEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AdvancedBuildSettings.PostActionScriptPath" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify the command line arguments to pass to the script that runs after the MSBuild activity successfully completes." DisplayName="Post-build script arguments" ParameterName="AdvancedBuildSettings.PostActionScriptArguments" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify AsConfigured to run code analysis according to project settings; Never to never run code analysis; Always to always run code analysis." DisplayName="Perform code analysis" Editor="@DropDownList=Never,AsConfigured,Always" ParameterName="AdvancedBuildSettings.RunCodeAnalysis" />
<mtbw:ProcessParameterMetadata Category="#250 Test" Description="Specify the test assemblies or test metadata files on which to run tests. You can skip running these tests by setting the Disable Tests setting to True." DisplayName="1. Automated tests" Editor="Microsoft.TeamFoundation.Build.Controls.AgileTestSpecListEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AutomatedTests" ValueFormatString="{}{Count} set(s) of tests specified." />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" DisplayName="Test source" Editor="Microsoft.TeamFoundation.Build.Controls.AgileTestSpecEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AutomatedTests.[Item]" ValueFormatString="{}{RunName} - Run tests in test sources matching {AssemblyFileSpec}, Target platform: '{ExecutionPlatform}'" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the search pattern for locating test sources - e.g., **\\*test*.dll." DisplayName="Test sources spec" ParameterName="AutomatedTests.AssemblyFileSpec" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Never" ParameterName="AutomatedTests.HasRunSettingsFile" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Never" ParameterName="AutomatedTests.HasTestCaseFilter" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Never" ParameterName="AutomatedTests.RunSettingsFileName" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Use the specified filter to select tests to run based on filter criteria. You can use the format &lt;property&gt;Operator&lt;value&gt; to construct your filter where Operator is one of =, != or ~ (Operator ~ has 'contains' semantics and is applicable for string properties like DisplayName). You can also use the logical operator |, to construct your filter and parenthesis () for grouping. For example, (FullyQualifiedName~Nightly|Name=MyTestMethod)" DisplayName="Test case filter" ParameterName="AutomatedTests.TestCaseFilter" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify run settings to be used for running the tests." DisplayName="Run settings" ParameterName="AutomatedTests.RunSettingsForTestRun" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the Run Settings file to use with the test sources." DisplayName="Run settings file" Editor="Microsoft.TeamFoundation.Build.Controls.GitRunSettingsFileBrowserEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AutomatedTests.RunSettingsForTestRun.ServerRunSettingsFile" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Select the type of run settings to use with test sources. Values are Default, CodeCoverageEnabled, CodeCoverageEnabledForAspNetApps, UserSpecified." DisplayName="Type of run settings" Editor="@DropDownList=Default,CodeCoverageEnabled,CodeCoverageEnabledForAspNetApps,UserSpecified" ParameterName="AutomatedTests.RunSettingsForTestRun.TypeRunSettings" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Never" ParameterName="AutomatedTests.RunSettingsForTestRun.HasRunSettingsFile" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify target platform for test execution. X86 or X64" DisplayName="Target platform for test execution" Editor="@DropDownList=X86,X64" ParameterName="AutomatedTests.ExecutionPlatform" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Set this to true to fail any builds where these tests do not pass. The default is to mark the build as partially succeeded if the tests fail." DisplayName="Fail build on test failure" ParameterName="AutomatedTests.FailBuildOnFailure" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the name the test run is published as." DisplayName="Test run name" ParameterName="AutomatedTests.RunName" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#250 Test" Description="" DisplayName="2. Advanced" ParameterName="AdvancedTestSettings" ValueFormatString=" " />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#250 Test" Description="Specify True to skip running all tests with the build; False to run tests as defined by the Automated Tests setting." DisplayName="Disable tests" ParameterName="AdvancedTestSettings.DisableTests" />
<mtbw:ProcessParameterMetadata Description="Specify the path to a custom script that runs before the RunAgileTestRunner activity starts." DisplayName="Pre-test script path" Editor="Microsoft.TeamFoundation.Build.Controls.GitLocalFileBrowserEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AdvancedTestSettings.PreActionScriptPath" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify the command line arguments to pass to the script that runs before the RunAgileTestRunner activity starts." DisplayName="Pre-test script arguments" ParameterName="AdvancedTestSettings.PreActionScriptArguments" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify the path to a custom script that runs after the RunAgileTestRunner activity successfully completes." DisplayName="Post-test script path" Editor="Microsoft.TeamFoundation.Build.Controls.GitLocalFileBrowserEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AdvancedTestSettings.PostActionScriptPath" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Description="Specify the command line arguments to pass to the script that runs after the RunAgileTestRunner activity successfully completes." DisplayName="Post-test script arguments" ParameterName="AdvancedTestSettings.PostActionScriptArguments" ValueFormatString="" />
<mtbw:ProcessParameterMetadata Category="#300 Publish Symbols" Description="Specify the path to the symbol store share. When this value is set, source indexing is a part of the build. Source indexing is never performed for private builds." DisplayName="Path to publish symbols" ParameterName="SymbolStorePath" />
<mtbw:ProcessParameterMetadata Category="#400 Advanced" Description="Specify the format for the number of this build." DisplayName="Build number format" Editor="Microsoft.TeamFoundation.Build.Controls.BuildNumberFormatEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="BuildNumberFormat" />
<mtbw:ProcessParameterMetadata Category="#400 Advanced" Description="Specify the Name and/or Tags (and other properties) that will be used to select an appropriate Agent for the build." DisplayName="Agent settings" ParameterName="AgentSettings" ValueFormatString="Use agent where Name={Name} and Tags={Tags} ({TagComparison})" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the maximum amount of time that you want to allow for this part of the work flow to run. The default value is zero which means there is no timeout." DisplayName="Maximum agent execution time" Editor="@Type=TimeSpan" ParameterName="AgentSettings.MaxExecutionTime" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the maximum amount of time that you want to allow waiting for an agent. The default value is zero which means there is no timeout." DisplayName="Maximum agent reservation wait time" Editor="@Type=TimeSpan" ParameterName="AgentSettings.MaxWaitTime" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the agent to use for this remote execution by display name (this is not the computer name). Supported wildcard characters include '*' and '?'." DisplayName="Name filter" Editor="Microsoft.TeamFoundation.Build.Controls.BuildAgentSelectionEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AgentSettings.Name" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the comparison method to use for tags when selecting a build agent. MatchExactly, MatchAtLeast" DisplayName="Tag comparison operator" Editor="@DropDownList=MatchExactly,MatchAtLeast" ParameterName="AgentSettings.TagComparison" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Description="Specify the tags used to select the build agent." DisplayName="Tags filter" Editor="Microsoft.TeamFoundation.Build.Controls.TagsEditor, Microsoft.TeamFoundation.Build.Controls" ParameterName="AgentSettings.Tags" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#400 Advanced" Description="Set this to true to create a work item when the build fails." DisplayName="Create work item on failure" ParameterName="CreateWorkItem" />
<mtbw:ProcessParameterMetadata BrowsableWhen="Always" Category="#400 Advanced" Description="Set this to true to update the associated work items by setting the Fixed In Build field to the build number of this build." DisplayName="Update work items with build number" ParameterName="UpdateAssociatedWorkItems" />
</mtbw:ProcessParameterMetadataCollection>
</this:Process.Metadata>
<sap2010:WorkflowViewState.IdRef>TfsBuild.Process_1</sap2010:WorkflowViewState.IdRef>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<Sequence DisplayName="Overall build process" sap2010:WorkflowViewState.IdRef="Sequence_2">
<mtbac:SetBuildNumber DropLocation="{x:Null}" BuildNumberFormat="[BuildNumberFormat]" DisplayName="Update build number" sap2010:WorkflowViewState.IdRef="SetBuildNumber_1" />
<mtbwa:AgentScope DataToIgnore="" DisplayName="Run on agent" sap2010:WorkflowViewState.IdRef="AgentScope_1" MaxExecutionTime="[AgentSettings.GetValue(Of TimeSpan)(&quot;MaxExecutionTime&quot;, New System.TimeSpan(0,0,0))]" MaxWaitTime="[AgentSettings.GetValue(Of TimeSpan)(&quot;MaxWaitTime&quot;, New System.TimeSpan(4,0,0))]" ReservationSpec="[AgentSettings.CreateAgentReservationSpec()]" mva:VisualBasic.Settings="Assembly references and imported namespaces serialized as XML namespaces">
<mtbac:InitializeEnvironment BinariesFolder="bin" DisplayName="Initialize environment" sap2010:WorkflowViewState.IdRef="InitializeEnvironment_1" SourceFolder="src" TestResultsFolder="tst" />
<mtbag:GitPull CheckoutSubmodules="{x:Null}" CleanRepository="[CleanRepository]" Commit="[CheckoutOverride]" DisplayName="Pull sources from Git repo" Enabled="True" sap2010:WorkflowViewState.IdRef="GitPull_1" />
<mtba:AssociateChanges DisplayName="Associate the changesets that occurred since the last good build" Enabled="True" sap2010:WorkflowViewState.IdRef="AssociateChanges_1" UpdateWorkItems="[UpdateAssociatedWorkItems]" />
<TryCatch DisplayName="Try" sap2010:WorkflowViewState.IdRef="TryCatch_1" mtbwt:BuildTrackingParticipant.Importance="Low">
<TryCatch.Try>
<Sequence DisplayName="Compile, Test and Publish" sap2010:WorkflowViewState.IdRef="Sequence_1">
<mtba:RunScript Arguments="[AdvancedBuildSettings.GetValue(Of String)(&quot;PreActionScriptArguments&quot;, String.Empty)]" DisplayName="Run optional script before MSBuild" Enabled="True" FilePath="[AdvancedBuildSettings.GetValue(Of String)(&quot;PreActionScriptPath&quot;, String.Empty)]" sap2010:WorkflowViewState.IdRef="RunScript_1" />
<mtba:RunMSBuild CleanBuild="[CleanBuild]" CommandLineArguments="[String.Format(&quot;/p:SkipInvalidConfigurations=true {0}&quot;, AdvancedBuildSettings.GetValue(Of String)(&quot;MSBuildArguments&quot;, String.Empty))]" ConfigurationsToBuild="[ConfigurationsToBuild]" DisplayName="Run MSBuild" Enabled="True" sap2010:WorkflowViewState.IdRef="RunMSBuild_1" MSBuildMultiProc="True" OutputLocation="[OutputLocation]" ProjectsToBuild="[ProjectsToBuild]" RestoreNuGetPackages="True" RunCodeAnalysis="[AdvancedBuildSettings.GetValue(Of String)(&quot;RunCodeAnalysis&quot;, &quot;AsConfigured&quot;)]" ToolPlatform="[AdvancedBuildSettings.GetValue(Of String)(&quot;MSBuildPlatform&quot;, &quot;Auto&quot;)]" ToolVersion="14.0" Verbosity="Normal" />
<mtba:RunScript Arguments="[AdvancedBuildSettings.GetValue(Of String)(&quot;PostActionScriptArguments&quot;, String.Empty)]" DisplayName="Run optional script after MSBuild" Enabled="True" FilePath="[AdvancedBuildSettings.GetValue(Of String)(&quot;PostActionScriptPath&quot;, String.Empty)]" sap2010:WorkflowViewState.IdRef="RunScript_2" />
<mtba:RunScript Arguments="[AdvancedTestSettings.GetValue(Of String)(&quot;PreActionScriptArguments&quot;, String.Empty)]" DisplayName="Run optional script before Test Runner" Enabled="True" FilePath="[AdvancedTestSettings.GetValue(Of String)(&quot;PreActionScriptPath&quot;, String.Empty)]" sap2010:WorkflowViewState.IdRef="RunScript_3" />
<mtba:RunAgileTestRunner ConfigurationsToTest="[ConfigurationsToBuild]" DisplayName="Run VS Test Runner" Enabled="[Not AdvancedTestSettings.GetValue(Of Boolean)(&quot;DisableTests&quot;, false)]" sap2010:WorkflowViewState.IdRef="RunAgileTestRunner_1" TestSpecs="[AutomatedTests]" />
<mtba:RunScript Arguments="[AdvancedTestSettings.GetValue(Of String)(&quot;PostActionScriptArguments&quot;, String.Empty)]" DisplayName="Run optional script after Test Runner" Enabled="True" FilePath="[AdvancedTestSettings.GetValue(Of String)(&quot;PostActionScriptPath&quot;, String.Empty)]" sap2010:WorkflowViewState.IdRef="RunScript_4" />
<mtba:RunPublishSymbols DisplayName="Publish Symbols" Enabled="True" sap2010:WorkflowViewState.IdRef="RunPublishSymbols_1" SymbolStorePath="[SymbolStorePath]" />
</Sequence>
</TryCatch.Try>
<TryCatch.Catches>
<Catch x:TypeArguments="s:Exception" sap2010:WorkflowViewState.IdRef="Catch`1_1">
<ActivityAction x:TypeArguments="s:Exception">
<ActivityAction.Argument>
<DelegateInArgument x:TypeArguments="s:Exception" Name="ex" />
</ActivityAction.Argument>
<Sequence DisplayName="Handle Exception" sap2010:WorkflowViewState.IdRef="Sequence_3">
<mtba:CreateBuildFailureBug DisplayName="Create a bug for the build failure" Enabled="[CreateWorkItem]" sap2010:WorkflowViewState.IdRef="CreateBuildFailureBug_1" />
<Rethrow DisplayName="Rethrow the exception so the build will stop" sap2010:WorkflowViewState.IdRef="Rethrow_1" />
</Sequence>
</ActivityAction>
</Catch>
</TryCatch.Catches>
<TryCatch.Finally>
<Sequence DisplayName="Perform Final Actions On Agent" sap2010:WorkflowViewState.IdRef="Sequence_4">
<mtbac:DropBinaries DestinationPath="{x:Null}" DisplayName="Copy binaries to drop" Enabled="True" sap2010:WorkflowViewState.IdRef="DropBinaries_1" />
<mtbac:ResetEnvironment DisplayName="Reset the Environment" sap2010:WorkflowViewState.IdRef="ResetEnvironment_1" />
</Sequence>
</TryCatch.Finally>
</TryCatch>
</mtbwa:AgentScope>
<sads:DebugSymbol.Symbol>d0BDOlxVc2Vyc1xKZXPDunNcU291cmNlXFJlcG9zXEFiZXJyYXRpb1JlYWRlclxHaXRUZW1wbGF0ZS4xMi54YW1sSgGPDAHeEAELAcIHAeQKAQoB4wsB6gsBCQH7FAGCFQEIAWIBngcBBwHCFAHdFAEGAfsQAYMUAQUBqxUBshUBBAGdFAGkFAEDAYULAcQLAQJrA5MBDgIBAWwFbLIBAgFZbQWRARgCAQJsRWxaAgFabfABbcwCAgEHbYIBbeMBAgEFbd0CbYsDAgEDbgduxQECAVVvB2/aAQIBT3AHcOEBAgFLcQeQARICAQlupQFuqgECAVhuM244AgFXbr0BbsIBAgFWb0RvVwIBU29fb3MCAVFvpQFvqwECAVBwwQFw3gECAU1wdXB7AgFMcwt7FgIBE4sBC44BFgIBD4MBD4YBGgIBCnQNdN8CAgFFdQ118gUCATF2DXbgAgIBK3cNd+ECAgEleA14pwICAR55DXniAgIBGHoNeq4BAgEUjAENjAGiAQIBEY0BDY0BgAECARCEARGEAbUBAgEMhQERhQGDAQIBC3TCAXTIAQIBSnQndIgBAgFIdNIBdK4CAgFGdbsDdc4DAgFDdYIDdYgDAgFCdecFde8FAgFBde0EdckFAgE/dfsDdd8EAgE9dU116AECATt1/wF1mAICATl1mAN1qgMCATd1uwJ1wQICATZ11gV13AUCATV1KXU3AgEzdeQDdeoDAgEydsIBdsgBAgEwdid2iQECAS520gF2rwICASx3xQF3ywECASp3J3eHAQIBKHfVAXewAgIBJniSAnikAgIBI3h+eNABAgEheDt4VAIBH3nFAXnLAQIBHXkneYgBAgEbedUBebECAgEZepgBeqsBAgEWekt6UQIBFYwBaIwBbgIBEoQBZoQBeAIBDQ==</sads:DebugSymbol.Symbol>
</Sequence>
<sap2010:WorkflowViewState.ViewStateManager>
<sap2010:ViewStateManager>
<sap2010:ViewStateData Id="SetBuildNumber_1" sap:VirtualizedContainerService.HintSize="439.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="InitializeEnvironment_1" sap:VirtualizedContainerService.HintSize="418.036363636364,21.8181818181818" />
<sap2010:ViewStateData Id="GitPull_1" sap:VirtualizedContainerService.HintSize="418.036363636364,21.8181818181818" />
<sap2010:ViewStateData Id="AssociateChanges_1" sap:VirtualizedContainerService.HintSize="418.036363636364,21.8181818181818" />
<sap2010:ViewStateData Id="RunScript_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="RunMSBuild_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="RunScript_2" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="RunScript_3" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="RunAgileTestRunner_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="RunScript_4" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="RunPublishSymbols_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="Sequence_1" sap:VirtualizedContainerService.HintSize="221.672727272727,517.527272727273">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
</sap2010:ViewStateData>
<sap2010:ViewStateData Id="CreateBuildFailureBug_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="Rethrow_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="Sequence_3" sap:VirtualizedContainerService.HintSize="221.672727272727,207.709090909091">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
</sap2010:ViewStateData>
<sap2010:ViewStateData Id="Catch`1_1" sap:VirtualizedContainerService.HintSize="404.072727272727,21.8181818181818">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">False</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
</sap2010:ViewStateData>
<sap2010:ViewStateData Id="DropBinaries_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="ResetEnvironment_1" sap:VirtualizedContainerService.HintSize="199.854545454545,21.8181818181818" />
<sap2010:ViewStateData Id="Sequence_4" sap:VirtualizedContainerService.HintSize="221.672727272727,207.709090909091">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
</sap2010:ViewStateData>
<sap2010:ViewStateData Id="TryCatch_1" sap:VirtualizedContainerService.HintSize="418.036363636364,752.290909090909" />
<sap2010:ViewStateData Id="AgentScope_1" sap:VirtualizedContainerService.HintSize="439.854545454545,1062.10909090909" />
<sap2010:ViewStateData Id="Sequence_2" sap:VirtualizedContainerService.HintSize="461.672727272727,1248">
<sap:WorkflowViewStateService.ViewState>
<scg:Dictionary x:TypeArguments="x:String, x:Object">
<x:Boolean x:Key="IsExpanded">True</x:Boolean>
</scg:Dictionary>
</sap:WorkflowViewStateService.ViewState>
</sap2010:ViewStateData>
<sap2010:ViewStateData Id="TfsBuild.Process_1" sap:VirtualizedContainerService.HintSize="501.818181818182,1328.29090909091" />
</sap2010:ViewStateManager>
</sap2010:WorkflowViewState.ViewStateManager>
</Activity>

Просмотреть файл

@ -13,7 +13,7 @@
<DefaultLanguage>en-US</DefaultLanguage>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile>Profile44</TargetFrameworkProfile>
<TargetFrameworkProfile>Profile151</TargetFrameworkProfile>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -37,6 +37,7 @@
<!-- A reference to the entire .NET Framework is automatically included -->
</ItemGroup>
<ItemGroup>
<Compile Include="StackingLinkedList.cs" />
<Compile Include="Guard.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReflectionExtensions.cs" />

Просмотреть файл

@ -1,7 +1,5 @@
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
@ -10,7 +8,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MissU")]
[assembly: AssemblyProduct("OmniXAML")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

Просмотреть файл

@ -7,6 +7,7 @@
public static class ReflectionExtensions
{
// code adjusted to prevent horizontal overflow
public static string GetFullPropertyName<T, TProperty>(this Expression<Func<T, TProperty>> propertySelector)
{
MemberExpression memberExp;
@ -25,15 +26,22 @@
return string.Join(".", memberNames.ToArray());
}
// code adjusted to prevent horizontal overflow
private static bool TryFindMemberExpression(this Expression exp, out MemberExpression memberExp)
{
memberExp = exp as MemberExpression;
if (memberExp != null)
{
// heyo! that was easy enough
return true;
}
// if the compiler created an automatic conversion,
// it'll look something like...
// obj => Convert(obj.Property) [e.g., int -> object]
// OR:
// obj => ConvertChecked(obj.Property) [e.g., int -> long]
// ...which are the cases checked in IsConversion
if (IsConversion(exp) && exp is UnaryExpression)
{
memberExp = ((UnaryExpression)exp).Operand as MemberExpression;

Просмотреть файл

@ -0,0 +1,23 @@
namespace Glass
{
using System.Collections.Generic;
public class StackingLinkedList<T>
{
private readonly LinkedList<T> linkedList = new LinkedList<T>();
public void Push(T item)
{
linkedList.AddLast(item);
}
public LinkedListNode<T> Current => linkedList.Last;
public void Pop()
{
linkedList.RemoveLast();
}
public int Count => linkedList.Count;
}
}

Просмотреть файл

@ -1,8 +0,0 @@
namespace OmniXaml.Tests.Classes
{
public class Item
{
public string Title { get; set; }
public string Text { get; set; }
}
}

Просмотреть файл

@ -1,111 +0,0 @@
namespace OmniXaml.Tests.Parsers
{
using System;
using OmniXaml.Parsers.ProtoParser;
using Typing;
internal class ProtoNodeBuilder
{
private readonly IXamlTypeRepository typeRepository;
public ProtoNodeBuilder(IXamlTypeRepository typeRepository)
{
this.typeRepository = typeRepository;
}
public ProtoXamlNode None()
{
return new ProtoXamlNode
{
Namespace = null,
XamlType = null,
NodeType = ProtoNodeType.None
};
}
public ProtoXamlNode NamespacePrefixDeclaration(string ns, string prefix)
{
return new ProtoXamlNode
{
Namespace = ns,
XamlType = null,
NodeType = ProtoNodeType.PrefixDefinition,
Prefix = prefix,
};
}
private ProtoXamlNode WithElement(Type type, string ns, bool isEmtpy)
{
return new ProtoXamlNode
{
Namespace = ns,
XamlType = XamlType.Builder.Create(type, typeRepository),
NodeType = isEmtpy ? ProtoNodeType.EmptyElement : ProtoNodeType.Element,
};
}
public ProtoXamlNode ElementNonCollapsed(Type type, string ns)
{
return WithElement(type, ns, false);
}
public ProtoXamlNode ElementCollapsed(Type type, string ns)
{
return WithElement(type, ns, true);
}
public ProtoXamlNode PropertyCollapsed(string ns)
{
return Property(ns, true);
}
public ProtoXamlNode AttachableProperty<TParent>(string name)
{
var type = typeof(TParent);
var xamlType = typeRepository.Get(type);
var member = xamlType.GetAttachableMember(name);
return new ProtoXamlNode
{
Namespace = null,
NodeType = ProtoNodeType.Attribute,
XamlType = null,
PropertyAttribute = member
};
}
public ProtoXamlNode PropertyNonCollapsed(string ns)
{
return Property(ns, false);
}
private ProtoXamlNode Property(string ns, bool isCollapsed)
{
return new ProtoXamlNode
{
Namespace = ns,
XamlType = null,
NodeType =
isCollapsed
? ProtoNodeType.EmptyPropertyElement
: ProtoNodeType.PropertyElement
};
}
public ProtoXamlNode EndTag()
{
return new ProtoXamlNode
{
Namespace = null,
XamlType = null,
NodeType = ProtoNodeType.EndTag
};
}
public ProtoXamlNode Text()
{
return new ProtoXamlNode { Namespace = null, NodeType = ProtoNodeType.Text, XamlType = null, };
}
}
}

Просмотреть файл

@ -1,61 +0,0 @@
namespace OmniXaml.Tests.Parsers.SuperXamlPullParserTests
{
using System.Collections.Generic;
using System.Linq;
using Classes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OmniXaml.Parsers.Xaml;
[TestClass]
public class ParsingTests : GivenAWiringContext
{
private readonly ProtoNodeBuilder protoBuilder;
private readonly XamlNodeBuilder builder;
private readonly SuperXamlPullParser sut;
public ParsingTests()
{
protoBuilder = new ProtoNodeBuilder(WiringContext.TypeContext);
builder = new XamlNodeBuilder(WiringContext.TypeContext);
sut = new SuperXamlPullParser();
}
[TestMethod]
public void NamespaceDeclarationOnly()
{
var input = new List<ProtoXamlNode>
{
protoBuilder.NamespacePrefixDeclaration("root", ""),
};
var expectedNodes = new List<XamlNode>
{
builder.NamespaceDeclaration("root", ""),
};
var actualNodes = sut.Parse(input);
XamlNodesAssert.AreEssentiallyTheSame(expectedNodes, actualNodes.ToList());
}
[TestMethod]
public void SingleInstanceCollapsed()
{
var input = new List<ProtoXamlNode>
{
protoBuilder.ElementCollapsed(typeof(DummyClass), string.Empty),
};
var expectedNodes = new List<XamlNode>
{
builder.StartObject<DummyClass>(),
builder.EndObject(),
};
var actualNodes = sut.Parse(input);
XamlNodesAssert.AreEssentiallyTheSame(expectedNodes, actualNodes.ToList());
}
}
}

Просмотреть файл

@ -5,15 +5,19 @@ VisualStudioVersion = 14.0.22609.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniXaml", "OmniXaml\OmniXaml.csproj", "{0D9CC1DE-84C3-40D7-9CC5-B7751E0B25D1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniXaml.Tests", "Tests\OmniXaml.Tests\OmniXaml.Tests.csproj", "{4A7491E9-E218-45F5-BF42-430247765630}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{FCCAF8EF-B08E-4442-90B6-A41903CFB93A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Glass", "..\Glass\Glass.csproj", "{B719FF91-BC7A-4145-8597-811D504FCFEF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniXaml.Tests.Classes", "OmniXaml.Tests.Classes\OmniXaml.Tests.Classes.csproj", "{E6FDA529-90C2-4DDA-9080-7E7EEF64B2CA}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniXaml.Tests.Classes", "Tests\OmniXaml.Tests.Classes\OmniXaml.Tests.Classes.csproj", "{E6FDA529-90C2-4DDA-9080-7E7EEF64B2CA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xaml.Tests.Resources", "..\Xaml.Tests.Resources\Xaml.Tests.Resources.csproj", "{9B517520-4D99-4BF5-8219-A643F718F6DD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniXaml.Tests", "OmniXaml.Tests\OmniXaml.Tests.csproj", "{4A7491E9-E218-45F5-BF42-430247765630}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniXaml.Tests.Wpf", "Tests\OmniXaml.Tests.Wpf\OmniXaml.Tests.Wpf.csproj", "{952C2CB6-BB38-471A-AD55-D68FCAC4A5CF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApplication", "TestApplication\TestApplication.csproj", "{A49A57C4-6DB5-44A0-869B-39EED7884A0B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -25,6 +29,10 @@ Global
{0D9CC1DE-84C3-40D7-9CC5-B7751E0B25D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0D9CC1DE-84C3-40D7-9CC5-B7751E0B25D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0D9CC1DE-84C3-40D7-9CC5-B7751E0B25D1}.Release|Any CPU.Build.0 = Release|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Release|Any CPU.Build.0 = Release|Any CPU
{B719FF91-BC7A-4145-8597-811D504FCFEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B719FF91-BC7A-4145-8597-811D504FCFEF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B719FF91-BC7A-4145-8597-811D504FCFEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -37,18 +45,23 @@ Global
{9B517520-4D99-4BF5-8219-A643F718F6DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9B517520-4D99-4BF5-8219-A643F718F6DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9B517520-4D99-4BF5-8219-A643F718F6DD}.Release|Any CPU.Build.0 = Release|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A7491E9-E218-45F5-BF42-430247765630}.Release|Any CPU.Build.0 = Release|Any CPU
{952C2CB6-BB38-471A-AD55-D68FCAC4A5CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{952C2CB6-BB38-471A-AD55-D68FCAC4A5CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{952C2CB6-BB38-471A-AD55-D68FCAC4A5CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{952C2CB6-BB38-471A-AD55-D68FCAC4A5CF}.Release|Any CPU.Build.0 = Release|Any CPU
{A49A57C4-6DB5-44A0-869B-39EED7884A0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A49A57C4-6DB5-44A0-869B-39EED7884A0B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A49A57C4-6DB5-44A0-869B-39EED7884A0B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A49A57C4-6DB5-44A0-869B-39EED7884A0B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{4A7491E9-E218-45F5-BF42-430247765630} = {FCCAF8EF-B08E-4442-90B6-A41903CFB93A}
{B719FF91-BC7A-4145-8597-811D504FCFEF} = {FCCAF8EF-B08E-4442-90B6-A41903CFB93A}
{E6FDA529-90C2-4DDA-9080-7E7EEF64B2CA} = {FCCAF8EF-B08E-4442-90B6-A41903CFB93A}
{9B517520-4D99-4BF5-8219-A643F718F6DD} = {FCCAF8EF-B08E-4442-90B6-A41903CFB93A}
{4A7491E9-E218-45F5-BF42-430247765630} = {FCCAF8EF-B08E-4442-90B6-A41903CFB93A}
{952C2CB6-BB38-471A-AD55-D68FCAC4A5CF} = {FCCAF8EF-B08E-4442-90B6-A41903CFB93A}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,83 @@
namespace OmniXaml.Assembler
{
using Glass;
using Typing;
internal class CurrentScopeProxy
{
private readonly StackingLinkedList<Scope> stackingLinkedList;
public CurrentScopeProxy(StackingLinkedList<Scope> stackingLinkedList)
{
this.stackingLinkedList = stackingLinkedList;
}
public object Instance
{
get
{
return stackingLinkedList.Peek().Instance;
}
set
{
stackingLinkedList.Peek().Instance = value;
}
}
public XamlType Type
{
get
{
return stackingLinkedList.Peek().XamlType;
}
set
{
stackingLinkedList.Peek().XamlType = value;
}
}
public XamlMember Property
{
get
{
return stackingLinkedList.Peek().Member;
}
set
{
stackingLinkedList.Peek().Member = value;
}
}
public object Collection
{
get
{
return stackingLinkedList.Peek().Collection;
}
set
{
stackingLinkedList.Peek().Collection = value;
}
}
public bool IsPropertyValueSet
{
set
{
stackingLinkedList.Peek().IsPropertyValueSet = value;
}
}
public bool IsObjectFromMember
{
get
{
return stackingLinkedList.Peek().IsObjectFromMember;
}
set
{
stackingLinkedList.Peek().IsObjectFromMember = value;
}
}
}
}

Просмотреть файл

@ -0,0 +1,16 @@
namespace OmniXaml.Assembler
{
using Glass;
public static class LinkedListStackExtensions
{
public static T Peek<T>(this StackingLinkedList<T> stackingLinkedList)
{
return stackingLinkedList.Current.Value;
}
public static T PeekPrevious<T>(this StackingLinkedList<T> stackingLinkedList)
{
return stackingLinkedList.Current.Previous.Value;
}
}
}

Просмотреть файл

@ -0,0 +1,138 @@
namespace OmniXaml.Assembler.NodeWriters
{
using System;
using System.Globalization;
using System.Reflection;
using TypeConversion;
using Typing;
public class EndMemberWriter
{
private readonly ObjectAssembler objectAssembler;
private readonly ITypeConverterProvider typeConverterProvider;
private readonly IXamlTypeRepository xamlTypeRepository;
private readonly StateBag bag;
public EndMemberWriter(ObjectAssembler objectAssembler,
WiringContext wiringContext)
{
this.objectAssembler = objectAssembler;
typeConverterProvider = wiringContext.ConverterProvider;
xamlTypeRepository = wiringContext.TypeContext;
bag = objectAssembler.Bag;
}
private bool IsLeafMember => bag.Current.Type == null;
public void WriteEndMember()
{
objectAssembler.SetUnfinishedResult();
var xamlMember = bag.Current.Type != null ? bag.Current.Property : bag.Parent.Property;
if (IsLeafMember)
{
var currentInstance = bag.Current.Instance;
var valueWasAssigned = true;
if (currentInstance != null)
{
var markupExtension = currentInstance as MarkupExtension;
if (markupExtension != null)
{
bag.Current.Instance = markupExtension;
var xamlType = xamlTypeRepository.Get(currentInstance.GetType());
if (!xamlType.CanAssignTo(xamlMember.Type))
{
AssignValueFromMarkupExtension(bag);
valueWasAssigned = false;
}
}
else
{
var xamlTypeOfCurrentInstance = xamlTypeRepository.Get(currentInstance.GetType());
var isString = Equals(xamlTypeOfCurrentInstance, CoreTypes.String);
var canAssign = xamlTypeOfCurrentInstance.CanAssignTo(xamlMember.Type);
if (isString || !canAssign)
{
valueWasAssigned = TryCreateCompatibleInstanceForCurrentMember(bag, bag.Current.Instance, xamlMember.Type.UnderlyingType);
}
}
}
objectAssembler.Result = bag.Current.Instance;
if (valueWasAssigned)
{
EndObjectWriter.AssignCurrentInstanceToParent(bag);
}
bag.PopScope();
}
bag.Current.Property = null;
bag.Current.IsPropertyValueSet = false;
}
private void AssignValueFromMarkupExtension(StateBag stateBag)
{
throw new NotImplementedException();
}
private bool TryCreateCompatibleInstanceForCurrentMember(StateBag stateBag, object instanceToConvert, Type destinationType)
{
var convertedValue = ConvertValueIfNecessary(instanceToConvert, destinationType);
stateBag.Current.Instance = convertedValue;
return true;
}
private object ConvertValueIfNecessary(object value, Type targetType)
{
object converted;
var success = TrySpecialConversion(value, targetType, out converted);
if (success)
{
return converted;
}
var typeConverter = typeConverterProvider.GetTypeConverter(targetType);
if (typeConverter != null)
{
var anotherValue = typeConverter.ConvertFrom(CultureInfo.InvariantCulture, value);
return anotherValue;
}
throw new ValueConversionException($"Cannot convert {value} to type {targetType}");
}
private static bool TrySpecialConversion(object value, Type targetType, out object converted)
{
var type = value.GetType();
if (type == typeof(string) && targetType == typeof(string))
{
converted = value;
return true;
}
if (type == typeof(string) && targetType == typeof(object))
{
converted = value.ToString();
return true;
}
if (targetType.GetTypeInfo().IsEnum)
{
converted = Enum.Parse(targetType, value.ToString());
return true;
}
converted = null;
return false;
}
private static bool IsMarkupExtension(object currentInstance) => (currentInstance as MarkupExtension) == null;
}
}

Просмотреть файл

@ -0,0 +1,100 @@
namespace OmniXaml.Assembler.NodeWriters
{
using System.Reflection;
using Typing;
public class EndObjectWriter
{
private readonly ObjectAssembler assembler;
private readonly StateBag bag;
private readonly IXamlTypeRepository typeRepository;
public EndObjectWriter(ObjectAssembler assembler, IXamlTypeRepository typeRepository)
{
this.assembler = assembler;
this.typeRepository = typeRepository;
bag = assembler.Bag;
}
public void WriteEndObject()
{
if (!bag.Current.IsObjectFromMember)
{
if (bag.Current.Instance == null)
{
assembler.PrepareNewInstanceBecauseWeWantToConfigureIt(bag);
}
if (IsMarkupExtension(bag.Current.Type))
{
AssignValueFromMarkupExtension(bag);
}
}
if (bag.LiveDepth > 1)
{
AssignCurrentInstanceToParent(bag);
}
assembler.Result = bag.Current.Instance;
bag.PopScope();
}
// TODO: This may be a duplicate (EndMemberWriter also uses it)
private void AssignValueFromMarkupExtension(StateBag stateBag)
{
var markupExtension = (MarkupExtension) stateBag.Current.Instance;
var providedValue = markupExtension.ProvideValue(null);
stateBag.Current.Type = typeRepository.Get(providedValue.GetType());
stateBag.Current.Instance = providedValue;
AssignCurrentInstanceToParent(bag);
}
private static bool IsMarkupExtension(XamlType type)
{
var underlyingType = type.UnderlyingType.GetTypeInfo();
var meType = typeof (MarkupExtension).GetTypeInfo();
return meType.IsAssignableFrom(underlyingType);
}
internal static void AssignCurrentInstanceToParent(StateBag bag)
{
var parentProperty = bag.Parent.Property;
var currentInstance = bag.Current.Instance;
var parentPropertyType = parentProperty.Type;
if (IsAssignmentBeingMadeToContainer(parentProperty, parentPropertyType))
{
AssignInstanceToParentCollection(bag.Parent.Collection, bag.Current.Instance);
}
else if (bag.Parent.Instance != null)
{
if (!bag.Current.IsObjectFromMember)
{
ApplyPropertyValue(bag, parentProperty, currentInstance, true);
}
}
}
private static bool IsAssignmentBeingMadeToContainer(XamlMember parentProperty, XamlType type)
{
return parentProperty.IsDirective && type.IsContainer;
}
private static void AssignInstanceToParentCollection(object parentCollection, object instance)
{
TypeOperations.Add(parentCollection, instance);
}
private static void ApplyPropertyValue(StateBag bag, XamlMember parentProperty, object value, bool onParent)
{
var instance = onParent ? bag.Parent.Instance : bag.Current.Instance;
TypeOperations.SetValue(instance, parentProperty, value);
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
namespace OmniXaml.Assembler.NodeWriters
{
internal class GetObjectWriter
{
private readonly ObjectAssembler objectAssembler;
private readonly StateBag bag;
public GetObjectWriter(ObjectAssembler objectAssembler)
{
this.objectAssembler = objectAssembler;
bag = objectAssembler.Bag;
}
public void WriteGetObject()
{
objectAssembler.SetUnfinishedResult();
var property = bag.Current.Type != null || bag.Depth <= 1
? bag.Current.Property
: bag.Parent.Property;
if (bag.Current.Type != null)
{
bag.PushScope();
}
bag.Current.IsObjectFromMember = true;
var parentInstance = bag.Parent.Instance;
bag.Current.Type = property.Type;
var valueOfProperty = TypeOperations.GetValue(parentInstance, property);
bag.Current.Instance = valueOfProperty;
if (property.Type.IsContainer)
{
bag.Current.Collection = valueOfProperty;
}
}
}
}

Просмотреть файл

@ -0,0 +1,10 @@
namespace OmniXaml.Assembler.NodeWriters
{
public class NamespaceWriter
{
public void WriteNamespace(object ns)
{
// TODO: Implement this!
}
}
}

Просмотреть файл

@ -0,0 +1,26 @@
namespace OmniXaml.Assembler.NodeWriters
{
using Typing;
internal class StartMemberWriter
{
private readonly ObjectAssembler objectAssembler;
private readonly StateBag bag;
public StartMemberWriter(ObjectAssembler objectAssembler)
{
this.objectAssembler = objectAssembler;
bag = objectAssembler.Bag;
}
public void WriteStartMember(XamlMember property)
{
bag.Current.Property = property;
if (bag.Current.Instance == null)
{
objectAssembler.PrepareNewInstanceBecauseWeWantToConfigureIt(bag);
}
}
}
}

Просмотреть файл

@ -0,0 +1,31 @@
namespace OmniXaml.Assembler.NodeWriters
{
using Typing;
public class StartObjectWriter
{
private readonly ObjectAssembler objectAssembler;
private readonly StateBag bag;
public StartObjectWriter(ObjectAssembler objectAssembler)
{
this.objectAssembler = objectAssembler;
bag = objectAssembler.Bag;
}
private bool IsThereAnotherObjectBeingConfigured => bag.Current.Type != null;
public void WriteStartObject(XamlType type)
{
objectAssembler.SetUnfinishedResult();
if (IsThereAnotherObjectBeingConfigured)
{
bag.PushScope();
}
bag.Current.Type = type;
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
namespace OmniXaml.Assembler.NodeWriters
{
public class ValueWriter
{
private readonly ObjectAssembler objectAssembler;
private readonly StateBag bag;
public ValueWriter(ObjectAssembler objectAssembler)
{
this.objectAssembler = objectAssembler;
bag = objectAssembler.Bag;
}
public void WriteValue(object value)
{
objectAssembler.SetUnfinishedResult();
bag.PushScope();
bag.Current.Instance = value;
}
}
}

Просмотреть файл

@ -0,0 +1,79 @@
namespace OmniXaml.Assembler
{
using System;
using Glass;
using NodeWriters;
public class ObjectAssembler : IObjectAssembler
{
private readonly EndMemberWriter endMemberWriter;
private readonly EndObjectWriter endObjectWriter;
private readonly GetObjectWriter getObjectWriter;
private readonly NamespaceWriter namespaceWriter;
private readonly StartMemberWriter startMemberWriter;
private readonly StartObjectWriter startObjectWriter;
private readonly TypeOperations typeOperations;
private readonly ValueWriter valueWriter;
public ObjectAssembler(WiringContext wiringContext)
{
typeOperations = new TypeOperations(wiringContext.TypeContext.TypeFactory);
startMemberWriter = new StartMemberWriter(this);
getObjectWriter = new GetObjectWriter(this);
startObjectWriter = new StartObjectWriter(this);
valueWriter = new ValueWriter(this);
namespaceWriter = new NamespaceWriter();
endMemberWriter = new EndMemberWriter(this, wiringContext);
endObjectWriter = new EndObjectWriter(this, wiringContext.TypeContext);
}
internal StateBag Bag { get; } = new StateBag();
public object Result { get; internal set; }
public void WriteNode(IXamlReader reader)
{
Guard.ThrowIfNull(reader, nameof(reader));
switch (reader.NodeType)
{
case XamlNodeType.None:
break;
case XamlNodeType.StartObject:
startObjectWriter.WriteStartObject(reader.Type);
break;
case XamlNodeType.EndObject:
endObjectWriter.WriteEndObject();
break;
case XamlNodeType.StartMember:
startMemberWriter.WriteStartMember(reader.Member);
break;
case XamlNodeType.EndMember:
endMemberWriter.WriteEndMember();
break;
case XamlNodeType.Value:
valueWriter.WriteValue(reader.Value);
break;
case XamlNodeType.GetObject:
getObjectWriter.WriteGetObject();
break;
case XamlNodeType.NamespaceDeclaration:
namespaceWriter.WriteNamespace(reader.Namespace);
break;
default:
throw new InvalidOperationException($"Cannot handle this kind of node type: {reader.NodeType}");
}
}
public void SetUnfinishedResult()
{
Result = null;
}
internal void PrepareNewInstanceBecauseWeWantToConfigureIt(StateBag bag)
{
var newInstance = typeOperations.Create(bag.Current.Type);
bag.Current.Instance = newInstance;
}
}
}

Просмотреть файл

@ -0,0 +1,35 @@
namespace OmniXaml.Assembler
{
using Glass;
using Typing;
internal class ParentScopeProxy
{
private readonly StackingLinkedList<Scope> stackingLinkedList;
public ParentScopeProxy(StackingLinkedList<Scope> stackingLinkedList)
{
this.stackingLinkedList = stackingLinkedList;
}
public object Instance => stackingLinkedList.PeekPrevious().Instance;
public XamlMember Property => stackingLinkedList.PeekPrevious().Member;
public XamlType Type => stackingLinkedList.PeekPrevious().XamlType;
public object Collection => stackingLinkedList.PeekPrevious().Collection;
public bool IsPropertyValueSet
{
get
{
return stackingLinkedList.PeekPrevious().IsPropertyValueSet;
}
set
{
stackingLinkedList.PeekPrevious().IsPropertyValueSet = value;
}
}
}
}

Просмотреть файл

@ -0,0 +1,14 @@
namespace OmniXaml.Assembler
{
using Typing;
internal class Scope
{
public XamlType XamlType { get; set; }
public XamlMember Member { get; set; }
public object Instance { get; set; }
public bool IsPropertyValueSet { get; set; }
public bool IsObjectFromMember { get; set; }
public object Collection { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,33 @@
namespace OmniXaml.Assembler
{
using Glass;
internal class StateBag
{
private readonly StackingLinkedList<Scope> stackingLinkedList = new StackingLinkedList<Scope>();
public StateBag()
{
stackingLinkedList.Push(new Scope());
SavedDepth = 0;
Current = new CurrentScopeProxy(stackingLinkedList);
Parent = new ParentScopeProxy(stackingLinkedList);
}
public int Depth => stackingLinkedList.Count;
public int LiveDepth => Depth - SavedDepth;
public int SavedDepth { get; }
public CurrentScopeProxy Current { get; }
public ParentScopeProxy Parent { get; }
public void PushScope()
{
stackingLinkedList.Push(new Scope());
}
public void PopScope()
{
stackingLinkedList.Pop();
}
}
}

Просмотреть файл

@ -0,0 +1,53 @@
namespace OmniXaml.Assembler
{
using System.Collections;
using System.Reflection;
using Typing;
public class TypeOperations
{
private readonly ITypeFactory typeFactory;
public TypeOperations(ITypeFactory typeFactory)
{
this.typeFactory = typeFactory;
}
public static void Add(object collection, object instance)
{
var list = (IList)collection;
list.Add(instance);
}
public static object GetValue(object parentInstance, XamlMember property)
{
var prop = parentInstance.GetType().GetRuntimeProperty(property.Name);
return prop.GetValue(parentInstance);
}
public static void SetValue(object instance, XamlMember parentProperty, object value)
{
if (parentProperty.IsAttachable)
{
var underlyingType = parentProperty.DeclaringType.UnderlyingType;
var prop = underlyingType.GetTypeInfo().GetDeclaredMethod("Set" + parentProperty.Name);
prop.Invoke(null, new[] { instance, value});
}
else
{
var prop = instance.GetType().GetRuntimeProperty(parentProperty.Name);
prop.SetValue(instance, value);
}
}
public object Create(XamlType xamlType)
{
if (xamlType.IsUnreachable)
{
throw new XamlReaderException($"The underlying type is null for this XAML Type: {xamlType}");
}
return typeFactory.Create(xamlType.UnderlyingType);
}
}
}

Просмотреть файл

@ -13,7 +13,7 @@
public ContentPropertyAttribute(string name)
{
this.Name = name;
Name = name;
}
}
}

Просмотреть файл

@ -10,9 +10,9 @@ namespace OmniXaml
public ClrMapping(Assembly assembly, string xamlNamespace, string clrNamespace)
{
this.Assembly = assembly;
this.XamlNamespace = xamlNamespace;
this.ClrNamespace = clrNamespace;
Assembly = assembly;
XamlNamespace = xamlNamespace;
ClrNamespace = clrNamespace;
}
}
}

Просмотреть файл

@ -0,0 +1,34 @@
namespace OmniXaml
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Catalogs;
public class DefaultXamlNamespaceTypeResolver : IXamlNamespaceTypeResolver
{
private readonly HashSet<ClrMapping> xamlMappings = new HashSet<ClrMapping>();
public Type Resolve(string typeName, string requestedXamlNs)
{
var mapping = xamlMappings.FirstOrDefault(clrMapping => clrMapping.XamlNamespace == requestedXamlNs);
if (mapping == null)
{
throw new TypeNotFoundException(string.Format("The type {0} has not been found in the namespace {1}", typeName, requestedXamlNs));
}
return mapping.Assembly.GetType(mapping.ClrNamespace + "." + typeName);
}
public void AddCatalog(ClrMappingCatalog catalog)
{
throw new NotImplementedException();
}
public void Map(string xamlNs, Assembly assembly, string clrNs)
{
xamlMappings.Add(new ClrMapping(assembly, xamlNs, clrNs));
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
namespace OmniXaml
{
public interface IXamlObjectWriter
public interface IObjectAssembler
{
void WriteNode(IXamlReader reader);

Просмотреть файл

@ -0,0 +1,9 @@
namespace OmniXaml
{
using System;
public interface ITypeProvider
{
Type GetType(string typeName, string clrNamespace, string assemblyName);
}
}

Просмотреть файл

@ -22,5 +22,35 @@ namespace OmniXaml
get { return prefix; }
set { prefix = value; }
}
protected bool Equals(NamespaceDeclaration other)
{
return string.Equals(ns, other.ns) && string.Equals(prefix, other.prefix);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((NamespaceDeclaration) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((ns != null ? ns.GetHashCode() : 0)*397) ^ (prefix != null ? prefix.GetHashCode() : 0);
}
}
}
}

Просмотреть файл

@ -52,20 +52,36 @@
<Compile Include="ClrMapping.cs" />
<Compile Include="ContentPropertyProvider.cs" />
<Compile Include="DefaultTypeFactory.cs" />
<Compile Include="DefaultXamlNamespaceTypeResolver.cs" />
<Compile Include="IContentPropertyProvider.cs" />
<Compile Include="IMarkupExtension.cs" />
<Compile Include="ITypeContext.cs" />
<Compile Include="ITypeFactory.cs" />
<Compile Include="ITypeProvider.cs" />
<Compile Include="IValueConverter.cs" />
<Compile Include="IXamlLoader.cs" />
<Compile Include="IXamlNamespaceTypeResolver.cs" />
<Compile Include="IXamlObjectWriter.cs" />
<Compile Include="IObjectAssembler.cs" />
<Compile Include="IXamlReader.cs" />
<Compile Include="MarkupExtension.cs" />
<Compile Include="NamespaceDeclaration.cs" />
<Compile Include="Parsers\Xaml\SuperXamlPullParser.cs" />
<Compile Include="Parsers\ProtoParser\ProtoNodeType.cs" />
<Compile Include="Assembler\LinkedListStackExtensions.cs" />
<Compile Include="Assembler\CurrentScopeProxy.cs" />
<Compile Include="Assembler\NodeWriters\EndMemberWriter.cs" />
<Compile Include="Assembler\NodeWriters\EndObjectWriter.cs" />
<Compile Include="Assembler\NodeWriters\GetObjectWriter.cs" />
<Compile Include="Assembler\NodeWriters\NamespaceWriter.cs" />
<Compile Include="Assembler\NodeWriters\StartMemberWriter.cs" />
<Compile Include="Assembler\NodeWriters\StartObjectWriter.cs" />
<Compile Include="Assembler\NodeWriters\ValueWriter.cs" />
<Compile Include="Assembler\Scope.cs" />
<Compile Include="Assembler\ParentScopeProxy.cs" />
<Compile Include="Assembler\StateBag.cs" />
<Compile Include="Assembler\TypeOperations.cs" />
<Compile Include="Assembler\ObjectAssembler.cs" />
<Compile Include="Parsers\MarkupExtensions\AssignmentNode.cs" />
<Compile Include="Parsers\MarkupExtensions\IdentifierNode.cs" />
<Compile Include="Parsers\MarkupExtensions\MarkupExtensionNodeToXamlNodesConverter.cs" />
<Compile Include="Parsers\MarkupExtensions\MarkupExtensionNode.cs" />
<Compile Include="Parsers\MarkupExtensions\MarkupExtensionParser.cs" />
<Compile Include="Parsers\MarkupExtensions\Option.cs" />
@ -74,14 +90,29 @@
<Compile Include="Parsers\MarkupExtensions\PropertyOption.cs" />
<Compile Include="Parsers\MarkupExtensions\StringNode.cs" />
<Compile Include="Parsers\MarkupExtensions\TreeNode.cs" />
<Compile Include="Parsers\Inject.cs" />
<Compile Include="Parsers\XamlNodes\XamlNodesPullParser.cs" />
<Compile Include="Parsers\ProtoParser\AttributeType.cs" />
<Compile Include="Parsers\ProtoParser\NodeType.cs" />
<Compile Include="Parsers\ProtoParser\UnboundAttribute.cs" />
<Compile Include="Parsers\ProtoParser\XamlAttribute.cs" />
<Compile Include="Parsers\ProtoParser\ProtoParserException.cs" />
<Compile Include="Parsers\XamlParseException.cs" />
<Compile Include="Parsers\ProtoParser\ProtoParser.cs" />
<Compile Include="Parsers\ProtoParser\Scope.cs" />
<Compile Include="Parsers\ProtoParser\ProtoParserNode.cs" />
<Compile Include="Parsers\ProtoParser\Context.cs" />
<Compile Include="Parsers\ProtoParser\TextBuffer.cs" />
<Compile Include="ProtoXamlNode.cs" />
<Compile Include="TypeContext.cs" />
<Compile Include="TypeContextBuilder.cs" />
<Compile Include="TypeConversion\BuiltInConverters\BooleanConverter.cs" />
<Compile Include="TypeConversion\BuiltInConverters\EnumTypeConverter.cs" />
<Compile Include="TypeConversion\ITypeConverter.cs" />
<Compile Include="TypeConversion\ITypeConverterProvider.cs" />
<Compile Include="TypeConversion\ITypeDescriptorContext.cs" />
<Compile Include="TypeConversion\NumberTypeConverter.cs" />
<Compile Include="TypeConversion\StringTypeConverter.cs" />
<Compile Include="TypeConversion\BuiltInConverters\NumberTypeConverter.cs" />
<Compile Include="TypeConversion\BuiltInConverters\StringTypeConverter.cs" />
<Compile Include="TypeConversion\TypeConverterAttribute.cs" />
<Compile Include="TypeConversion\TypeConverterProvider.cs" />
<Compile Include="TypeNotFoundException.cs" />
@ -103,13 +134,16 @@
<Compile Include="Typing\XamlType.cs" />
<Compile Include="Typing\XamlTypeName.cs" />
<Compile Include="Typing\XamlTypeRepository.cs" />
<Compile Include="ValueConversionException.cs" />
<Compile Include="WiringContext.cs" />
<Compile Include="WiringContextBuilder.cs" />
<Compile Include="XamlElement.cs" />
<Compile Include="XamlNode.cs" />
<Compile Include="XamlNodeType.cs" />
<Compile Include="XamlReader.cs" />
<Compile Include="XamlReaderException.cs" />
<Compile Include="XamlToObjectWiringContext.cs" />
<Compile Include="XmlNode.cs" />
<Compile Include="XamlXmlLoader.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

Просмотреть файл

@ -0,0 +1,56 @@
namespace OmniXaml.Parsers
{
using Glass;
using Typing;
internal static class Inject
{
public static XamlNode StartOfObject(XamlType xamlType)
{
Guard.ThrowIfNull(xamlType, nameof(xamlType));
return new XamlNode(XamlNodeType.StartObject, xamlType);
}
public static XamlNode EndOfObject()
{
return new XamlNode(XamlNodeType.EndObject);
}
public static XamlNode PrefixDefinitionOfNamespace(ProtoXamlNode protoXamlNode)
{
var namespaceDeclaration = new NamespaceDeclaration(protoXamlNode.Namespace, protoXamlNode.Prefix);
return new XamlNode(XamlNodeType.NamespaceDeclaration, namespaceDeclaration);
}
public static XamlNode StartOfMember(XamlMember member)
{
return new XamlNode(XamlNodeType.StartMember, member);
}
public static XamlNode Value(string value)
{
return new XamlNode(XamlNodeType.Value, value);
}
public static XamlNode EndOfMember()
{
return new XamlNode(XamlNodeType.EndMember);
}
public static XamlNode GetObject()
{
return new XamlNode(XamlNodeType.GetObject);
}
public static XamlNode Items()
{
return new XamlNode(XamlNodeType.StartMember, CoreTypes.Items);
}
public static XamlNode MarkupExtensionArguments()
{
return new XamlNode(XamlNodeType.StartMember, CoreTypes.MarkupExtensionArguments);
}
}
}

Просмотреть файл

@ -0,0 +1,49 @@
namespace OmniXaml.Parsers.MarkupExtensions
{
public class IdentifierNode
{
public string Prefix { get; }
public string TypeName { get; }
public IdentifierNode(string typeName)
{
TypeName = typeName + "Extension";
}
public IdentifierNode(string prefix, string typeName)
{
Prefix = prefix;
TypeName = typeName;
}
protected bool Equals(IdentifierNode other)
{
return string.Equals(Prefix, other.Prefix) && string.Equals(TypeName, other.TypeName);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((IdentifierNode) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Prefix != null ? Prefix.GetHashCode() : 0)*397) ^ (TypeName != null ? TypeName.GetHashCode() : 0);
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
namespace OmniXaml.Parsers.MarkupExtensions
{
using System.Collections.Generic;
using System.Linq;
using Typing;
public class MarkupExtensionNodeToXamlNodesConverter
{
private readonly WiringContext wiringContext;
public MarkupExtensionNodeToXamlNodesConverter(WiringContext wiringContext)
{
this.wiringContext = wiringContext;
}
public IEnumerable<XamlNode> Convert(MarkupExtensionNode tree)
{
var xamlType = wiringContext.TypeContext.GetByPrefix(string.Empty, tree.Identifier.TypeName);
yield return Inject.StartOfObject(xamlType);
foreach (var xamlNode in ParseArguments(tree.Options.OfType<PositionalOption>())) yield return xamlNode;
foreach (var xamlNode in ParseProperties(tree.Options.OfType<PropertyOption>(), xamlType)) yield return xamlNode;
yield return Inject.EndOfObject();
}
private static IEnumerable<XamlNode> ParseArguments(IEnumerable<PositionalOption> options)
{
var positionalOptions = options.ToList();
if (positionalOptions.Any())
{
yield return Inject.MarkupExtensionArguments();
foreach (var option in positionalOptions)
{
yield return Inject.Value(option.Identifier);
}
yield return Inject.EndOfMember();
}
}
private static IEnumerable<XamlNode> ParseProperties(IEnumerable<PropertyOption> options, XamlType xamlType)
{
foreach (var option in options)
{
var member = xamlType.GetMember(option.Property);
yield return Inject.StartOfMember(member);
var stringNode = option.Value as StringNode;
if (stringNode != null)
{
yield return Inject.Value(stringNode.Value);
}
yield return Inject.EndOfMember();
}
}
}
}

Просмотреть файл

@ -1,7 +1,7 @@
namespace OmniXaml.Parsers.MarkupExtensions
{
using System.Linq;
using global::Sprache;
using Sprache;
public static class MarkupExtensionParser
{
@ -67,51 +67,4 @@ namespace OmniXaml.Parsers.MarkupExtensions
private static readonly Parser<TreeNode> AssignmentSource = MarkupExtension.Or(StringValueNode);
}
public class IdentifierNode
{
public string Prefix { get; }
public string TypeName { get; }
public IdentifierNode(string typeName)
{
this.TypeName = typeName;
}
public IdentifierNode(string prefix, string typeName)
{
this.Prefix = prefix;
this.TypeName = typeName;
}
protected bool Equals(IdentifierNode other)
{
return string.Equals(Prefix, other.Prefix) && string.Equals(TypeName, other.TypeName);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return Equals((IdentifierNode) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Prefix != null ? Prefix.GetHashCode() : 0)*397) ^ (TypeName != null ? TypeName.GetHashCode() : 0);
}
}
}
}

Просмотреть файл

@ -3,7 +3,7 @@ namespace OmniXaml.Parsers.MarkupExtensions
using System.Diagnostics;
[DebuggerDisplay("{ToString()}")]
class PositionalOption : Option
public class PositionalOption : Option
{
public string Identifier { get; }

Просмотреть файл

@ -3,7 +3,7 @@ namespace OmniXaml.Parsers.MarkupExtensions
using System.Diagnostics;
[DebuggerDisplay("{ToString()}")]
class PropertyOption : Option
public class PropertyOption : Option
{
public string Property { get; }
public TreeNode Value { get; }

Просмотреть файл

@ -1,17 +1,17 @@
namespace OmniXaml.Parsers.MarkupExtensions
{
internal class StringNode : TreeNode
public class StringNode : TreeNode
{
private readonly string str;
public string Value { get; }
public StringNode(string str)
public StringNode(string value)
{
this.str = str;
Value = value;
}
protected bool Equals(StringNode other)
{
return string.Equals(str, other.str);
return string.Equals(Value, other.Value);
}
public override bool Equals(object obj)
@ -24,7 +24,7 @@ namespace OmniXaml.Parsers.MarkupExtensions
{
return true;
}
if (obj.GetType() != this.GetType())
if (obj.GetType() != GetType())
{
return false;
}
@ -33,7 +33,7 @@ namespace OmniXaml.Parsers.MarkupExtensions
public override int GetHashCode()
{
return (str != null ? str.GetHashCode() : 0);
return (Value != null ? Value.GetHashCode() : 0);
}
}
}

Просмотреть файл

@ -0,0 +1,15 @@
namespace OmniXaml.Parsers.ProtoParser
{
internal enum AttributeType
{
Namespace,
Property,
CtorDirective,
Name,
Directive,
XmlSpace,
Event,
AttachableProperty,
Unknown
}
}

Просмотреть файл

@ -0,0 +1,56 @@
namespace OmniXaml.Parsers.ProtoParser
{
using System.Collections.Generic;
using Typing;
internal class Context
{
private readonly Stack<Scope> stack;
public Context()
{
stack = new Stack<Scope>();
stack.Push(new Scope(null, null));
}
public int Depth => stack.Count - 1;
public XamlType CurrentType => stack.Count != 0 ? stack.Peek().XamlType : null;
public string CurrentTypeNamespace => stack.Count != 0 ? stack.Peek().Namespace : null;
public XamlMember CurrentProperty
{
get
{
return stack.Count != 0 ? stack.Peek().XamlProperty : null;
}
set
{
stack.Peek().XamlProperty = value;
}
}
public bool IsCurrentlyInsideContent
{
get
{
return stack.Count != 0 && stack.Peek().IsInsideContent;
}
set
{
stack.Peek().IsInsideContent = value;
}
}
public void Push(XamlType type, string ns)
{
stack.Push(new Scope(type, ns));
}
public void Pop()
{
stack.Pop();
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
namespace OmniXaml.Parsers.ProtoParser
{
public enum ProtoNodeType
public enum NodeType
{
None,
Element,

Просмотреть файл

@ -0,0 +1,433 @@
namespace OmniXaml.Parsers.ProtoParser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Typing;
public class ProtoParser
{
private readonly Queue<ProtoParserNode> nodes = new Queue<ProtoParserNode>();
private readonly Context stack;
private readonly ITypeContext typingCore;
private ProtoParserNode currentNode;
private TextBuffer textBuffer;
private XmlReader xmlReader;
public ProtoParser(ITypeContext typingCore)
{
this.typingCore = typingCore;
stack = new Context();
}
private XamlType Type => currentNode.Type;
private bool HasTextInBuffer
{
get
{
if (textBuffer != null)
{
return !textBuffer.IsEmpty;
}
return false;
}
}
private TextBuffer TextBuffer => textBuffer ?? (textBuffer = new TextBuffer());
private NodeType NodeType => currentNode.NodeType;
private string Namespace => currentNode.TypeNamespace;
private string Prefix => currentNode.Prefix;
private XamlMember PropertyAttribute => currentNode.PropertyAttribute;
private TextBuffer PropertyAttributeText => currentNode.PropertyAttributeText;
private XamlMember PropertyElement => currentNode.PropertyElement;
private void Read()
{
FillQueue();
currentNode = nodes.Dequeue();
}
private void FillQueue()
{
if (nodes.Count != 0)
{
return;
}
ReadXmlFromReader();
}
private void ReadXmlFromReader()
{
while (nodes.Count == 0)
{
if (xmlReader.Read())
{
ProcessCurrentXmlNode();
}
else
{
ReadNone();
}
}
}
private void ReadNone()
{
nodes.Enqueue(new ProtoParserNode {NodeType = NodeType.None});
}
private void ProcessCurrentXmlNode()
{
switch (xmlReader.NodeType)
{
case XmlNodeType.None:
ReadNone();
break;
case XmlNodeType.Element:
ReadElement();
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
ReadText();
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
ReadWhitespace();
break;
case XmlNodeType.EndElement:
ReadEndElement();
break;
}
}
private void EnqueueAnyText()
{
if (HasTextInBuffer)
{
EnqueueTextNode();
}
ClearBufferedText();
}
private void EnqueueTextNode()
{
if (stack.Depth == 0 && TextBuffer.IsWhiteSpaceOnly)
{
return;
}
nodes.Enqueue(new ProtoParserNode {NodeType = NodeType.Text, TextContent = TextBuffer});
}
private void ClearBufferedText()
{
textBuffer = null;
}
private void ReadEndElement()
{
EnqueueAnyText();
if (stack.CurrentProperty != null)
{
stack.CurrentProperty = null;
stack.IsCurrentlyInsideContent = false;
}
else
{
stack.Pop();
}
nodes.Enqueue(new ProtoParserNode {NodeType = NodeType.EndTag});
}
private void ReadWhitespace()
{
TextBuffer.Append(xmlReader.Value, !stack.IsCurrentlyInsideContent);
}
private void ReadText()
{
TextBuffer.Append(xmlReader.Value, !stack.IsCurrentlyInsideContent);
stack.IsCurrentlyInsideContent = true;
}
private void ReadElement()
{
EnqueueAnyText();
var isEmptyElement = xmlReader.IsEmptyElement;
var prefix = xmlReader.Prefix;
var localName = xmlReader.LocalName;
if (!XamlName.ContainsDot(localName))
{
ReadObjectElement(new XamlQualifiedName(prefix, localName), isEmptyElement);
}
else
{
var name = PropertyLocator.Parse(xmlReader.Name, xmlReader.NamespaceURI);
if (stack.CurrentType == null)
{
throw new XamlParseException("Property element with no parent!");
}
ReadPropertyElement(name, stack.CurrentType, isEmptyElement);
}
}
private void ReadObjectElement(XamlName name, bool isEmptyTag)
{
var attributes = EnqueuePrefixDefinitionsAndGetTheRestOfAttributes();
var node = new ProtoParserNode {Prefix = name.Prefix, IsEmptyTag = isEmptyTag};
var namespaceUri = xmlReader.NamespaceURI;
node.TypeNamespace = namespaceUri;
var xamlAttributes = ReadObjectElementObject(namespaceUri, name.PropertyName, node, attributes);
nodes.Enqueue(node);
EnqueueAttributes(xamlAttributes);
}
private List<UnboundAttribute> EnqueuePrefixDefinitionsAndGetTheRestOfAttributes()
{
var allAttributes = ReadAllAttributes()
.ToLookup(attribute => attribute.Type == AttributeType.Namespace);
var withoutPrefixDeclarations = allAttributes[false].ToList();
EnqueuePrefixDefinitions(allAttributes[true]);
return withoutPrefixDeclarations;
}
private void EnqueuePrefixDefinitions(IEnumerable<UnboundAttribute> prefixDefinition)
{
foreach (var xamlBareAttribute in prefixDefinition)
{
EnqueuePrefixDefinition(xamlBareAttribute);
}
}
private void EnqueueAttributes(IEnumerable<XamlAttribute> attributes)
{
foreach (var xamlBareAttribute in attributes)
{
EnqueueAttribute(xamlBareAttribute);
}
}
private void EnqueueAttribute(XamlAttribute attribute)
{
var nodeForAttribute = new ProtoParserNode();
switch (attribute.Type)
{
case AttributeType.CtorDirective:
case AttributeType.Name:
case AttributeType.Directive:
nodeForAttribute.NodeType = NodeType.Directive;
break;
case AttributeType.Property:
nodeForAttribute.NodeType = NodeType.Attribute;
break;
case AttributeType.AttachableProperty:
nodeForAttribute.NodeType = NodeType.Attribute;
break;
default:
throw new ProtoParserException("The type of the attribute is unknown");
}
var property = attribute.Property;
var convertCrlFtoLf = property == null;
nodeForAttribute.PropertyAttribute = property;
var xamlText = new TextBuffer();
xamlText.Append(attribute.Value, false, convertCrlFtoLf);
nodeForAttribute.PropertyAttributeText = xamlText;
nodeForAttribute.Prefix = attribute.Locator.Prefix;
nodes.Enqueue(nodeForAttribute);
}
private List<UnboundAttribute> ReadAllAttributes()
{
var allAttributes = new List<UnboundAttribute>();
if (xmlReader.MoveToFirstAttribute())
{
do
{
var name = xmlReader.Name;
var val = xmlReader.Value;
var propName = PropertyLocator.Parse(name);
if (propName == null)
{
throw new XamlParseException("InvalidXamlMemberName");
}
var attr = new UnboundAttribute(propName, val);
allAttributes.Add(attr);
} while (xmlReader.MoveToNextAttribute());
xmlReader.MoveToElement();
}
return allAttributes;
}
private void EnqueuePrefixDefinition(UnboundAttribute attr)
{
var xmlNsPrefixDefined = attr.XmlNsPrefixDefined;
var xmlNsUriDefined = attr.XmlNsUriDefined;
nodes.Enqueue(
new ProtoParserNode
{
NodeType = NodeType.PrefixDefinition,
Prefix = xmlNsPrefixDefined,
TypeNamespace = xmlNsUriDefined
});
}
private IEnumerable<XamlAttribute> ReadObjectElementObject(string xmlns, string name, ProtoParserNode node, List<UnboundAttribute> xamlBareAttributes)
{
var xamlTypeName = new XamlTypeName(xmlns, name);
node.Type = typingCore.GetWithFullAddress(xamlTypeName);
var attributes = GetAttributes(xamlBareAttributes, node.Type).ToList();
if (stack.Depth > 0)
{
stack.IsCurrentlyInsideContent = true;
}
if (!node.IsEmptyTag)
{
node.NodeType = NodeType.Element;
stack.Push(node.Type, node.TypeNamespace);
}
else
{
node.NodeType = NodeType.EmptyElement;
}
return attributes;
}
private void ReadPropertyElement(PropertyLocator locator, XamlType tagType, bool isEmptyTag)
{
var xamlBareAttributes = EnqueuePrefixDefinitionsAndGetTheRestOfAttributes();
var namespaceUri = xmlReader.NamespaceURI;
var tagIsRoot = stack.Depth == 1;
var dottedProperty = GetDottedProperty(tagType, locator);
var node = new ProtoParserNode
{
Prefix = locator.Prefix,
TypeNamespace = namespaceUri,
IsEmptyTag = isEmptyTag
};
var fullyFledgedAttributes = GetAttributes(xamlBareAttributes, node.Type).ToList();
if (stack.Depth > 0)
{
stack.IsCurrentlyInsideContent = false;
}
node.PropertyElement = dottedProperty;
if (!node.IsEmptyTag)
{
stack.CurrentProperty = node.PropertyElement;
node.NodeType = NodeType.PropertyElement;
}
else
{
node.NodeType = NodeType.EmptyPropertyElement;
}
nodes.Enqueue(node);
EnqueueAttributes(fullyFledgedAttributes);
}
private XamlMember GetDottedProperty(XamlType tagType, PropertyLocator propLocator)
{
if (tagType == null)
{
throw new ArgumentNullException(nameof(tagType));
}
var xamlNamespace = ResolveXamlNameNs(propLocator);
if (xamlNamespace == null)
{
throw new XamlParseException("PrefixNotFound");
}
var xamlTypeName = new XamlTypeName(xamlNamespace, propLocator.Owner.PropertyName);
var xamlType = typingCore.GetWithFullAddress(xamlTypeName);
return xamlType.GetMember(propLocator.PropertyName);
}
private static string ResolveXamlNameNs(XamlName name)
{
return name.Namespace;
}
private IEnumerable<XamlAttribute> GetAttributes(IEnumerable<UnboundAttribute> unboundAttributes, XamlType xamlType)
{
if (xamlType != null)
{
foreach (var xamlAttribute in unboundAttributes)
{
yield return new XamlAttribute(xamlAttribute, xamlType, typingCore);
}
}
}
public IEnumerable<ProtoXamlNode> Parse(string xml)
{
using (xmlReader = XmlReader.Create(new StringReader(xml)))
{
foreach (var node in ExtractStates())
{
yield return node;
}
}
}
private IEnumerable<ProtoXamlNode> ExtractStates()
{
do
{
Read();
yield return ExtractState();
} while (NodeType != NodeType.None);
}
private ProtoXamlNode ExtractState()
{
return new ProtoXamlNode
{
XamlType = Type,
Namespace = Namespace,
NodeType = NodeType,
PropertyAttribute = PropertyAttribute,
Prefix = Prefix,
PropertyElement = PropertyElement,
PropertyAttributeText = PropertyAttributeText?.Text
};
}
}
}

Просмотреть файл

@ -0,0 +1,12 @@
namespace OmniXaml.Parsers.ProtoParser
{
using System;
internal class ProtoParserException : Exception
{
public ProtoParserException(string get) : base(get)
{
}
}
}

Просмотреть файл

@ -0,0 +1,25 @@
namespace OmniXaml.Parsers.ProtoParser
{
using Typing;
internal class ProtoParserNode
{
public string Prefix { get; set; }
public bool IsEmptyTag { get; set; }
public XamlType Type { get; set; }
public NodeType NodeType { get; set; }
public string TypeNamespace { get; set; }
public XamlMember PropertyAttribute { get; set; }
public TextBuffer PropertyAttributeText { get; set; }
public XamlMember PropertyElement { get; set; }
public TextBuffer TextContent { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,23 @@
namespace OmniXaml.Parsers.ProtoParser
{
using Typing;
internal class Scope
{
public Scope(XamlType xamlType, string ns)
{
XamlType = xamlType;
Namespace = ns;
}
public XamlType XamlType { get; private set; }
public XamlMember XamlProperty { get; set; }
public bool IsPreservingSpace { get; set; }
public bool IsInsideContent { get; set; }
public string Namespace { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,117 @@
namespace OmniXaml.Parsers.ProtoParser
{
using System.Linq;
using System.Text;
public class TextBuffer
{
private StringBuilder stringBuilder;
private const char Tab = '\t';
private const char Space = ' ';
private const char NewLine = '\n';
private const char Backspace = '\b';
public TextBuffer()
{
stringBuilder = new StringBuilder();
IsWhiteSpaceOnly = true;
}
public bool IsEmpty => stringBuilder.Length == 0;
public string Text => stringBuilder.ToString();
public bool IsWhiteSpaceOnly { get; private set; }
public void Append(string text, bool trimLeadingWhitespace, bool replaceCrLf = true)
{
var isWhitespace = IsWhitespace(text);
if (isWhitespace)
{
if (IsEmpty && !trimLeadingWhitespace)
{
stringBuilder.Append(Space);
}
}
else
{
var isWhitespaceChar = IsWhitespaceChar(text[0]);
var whitespaceChar = IsWhitespaceChar(text[text.Length - 1]);
var lastIsAlsoWhitespace = false;
var str = CollapseWhitespace(text);
if (stringBuilder.Length > 0)
{
if (IsWhiteSpaceOnly)
{
stringBuilder = new StringBuilder();
}
else if (IsWhitespaceChar(stringBuilder[stringBuilder.Length - 1]))
{
lastIsAlsoWhitespace = true;
}
}
if (isWhitespaceChar && !trimLeadingWhitespace && !lastIsAlsoWhitespace)
{
stringBuilder.Append(Space);
}
stringBuilder.Append(str);
if (whitespaceChar)
{
stringBuilder.Append(Space);
}
}
IsWhiteSpaceOnly = IsWhiteSpaceOnly && isWhitespace;
}
private static bool IsWhitespace(string text)
{
return text.All(IsWhitespaceChar);
}
private static bool IsWhitespaceChar(char ch)
{
if (ch != Space && ch != Tab && ch != Backspace)
{
return ch == NewLine;
}
return true;
}
private static string CollapseWhitespace(string text)
{
var stringBuilder = new StringBuilder(text.Length);
var start = 0;
while (start < text.Length)
{
var ch = text[start];
if (!IsWhitespaceChar(ch))
{
stringBuilder.Append(ch);
start++;
}
else
{
var end = start;
do
{
} while (end++ < text.Length && IsWhitespaceChar(text[end]));
if (start != 0 && end != text.Length)
{
stringBuilder.Append(Space);
}
start = end;
}
}
return stringBuilder.ToString();
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
namespace OmniXaml.Parsers.ProtoParser
{
using System;
using Typing;
internal class UnboundAttribute
{
private readonly string xmlnsDefinitionPrefix;
private readonly string xmlnsDefinitionUri;
public UnboundAttribute(PropertyLocator propLocator, string val)
{
Locator = propLocator;
Value = val;
Type = AttributeType.Property;
if (!TryExtractNamespacePrefixDefinition(out xmlnsDefinitionPrefix, out xmlnsDefinitionUri))
{
return;
}
Type = AttributeType.Namespace;
}
public PropertyLocator Locator { get; }
public string Value { get; }
public AttributeType Type { get; private set; }
public string XmlNsPrefixDefined => xmlnsDefinitionPrefix;
public string XmlNsUriDefined => xmlnsDefinitionUri;
private bool TryExtractNamespacePrefixDefinition(out string prefix, out string ns)
{
ns = string.Empty;
prefix = string.Empty;
if (string.Equals(Locator.Prefix, "xmlns", StringComparison.Ordinal))
{
ns = Value;
prefix = !Locator.IsDotted ? Locator.PropertyName : Locator.OwnerName + "." + Locator.PropertyName;
return true;
}
if (!string.IsNullOrEmpty(Locator.Prefix) || !string.Equals(Locator.PropertyName, "xmlns", StringComparison.Ordinal))
{
return false;
}
ns = Value;
prefix = string.Empty;
return true;
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
namespace OmniXaml.Parsers.ProtoParser
{
using Typing;
internal class XamlAttribute
{
public XamlAttribute(UnboundAttribute unboundAttribute, XamlType type, IXamlTypeRepository typeContext)
{
Type = unboundAttribute.Type;
Value = unboundAttribute.Value;
Locator = unboundAttribute.Locator;
Property = GetProperty(Locator, type, typeContext);
}
public string Value { get; private set; }
public AttributeType Type { get; private set; }
public PropertyLocator Locator { get; }
public XamlMember Property { get; private set; }
private XamlMember GetProperty(PropertyLocator propLocator, XamlType xamType, IXamlTypeRepository typingCore)
{
return propLocator.IsDotted ? GetAttachableMember(propLocator, typingCore) : GetRegularMember(xamType, typingCore);
}
private XamlMember GetRegularMember(XamlType tagType, IXamlTypeRepository typeRepository)
{
return typeRepository.Get(tagType.UnderlyingType).GetMember(Locator.PropertyName);
}
private XamlMember GetAttachableMember(PropertyLocator memberLocator, IXamlTypeRepository typeRepository)
{
var owner = memberLocator.OwnerName;
var ownerType = typeRepository.GetByPrefix(memberLocator.Prefix, owner);
return typeRepository.Get(ownerType.UnderlyingType).GetAttachableMember(Locator.PropertyName);
}
}
}

Просмотреть файл

@ -1,44 +0,0 @@
namespace OmniXaml.Parsers.Xaml
{
using System.Collections.Generic;
using ProtoParser;
public class SuperXamlPullParser
{
public SuperXamlPullParser()
{
}
public IEnumerable<XamlNode> Parse(IEnumerable<ProtoXamlNode> protoNodes)
{
foreach (var protoXamlNode in protoNodes)
{
foreach (var xamlNode in ProcessProtoNode(protoXamlNode))
{
yield return xamlNode;
}
}
}
private IEnumerable<XamlNode> ProcessProtoNode(ProtoXamlNode protoXamlNode)
{
switch (protoXamlNode.NodeType)
{
case ProtoNodeType.PrefixDefinition:
yield return new XamlNode(XamlNodeType.NamespaceDeclaration, new NamespaceDeclaration(protoXamlNode.Namespace, protoXamlNode.Prefix));
break;
case ProtoNodeType.EmptyElement:
var type = protoXamlNode.XamlType;
yield return new XamlNode(XamlNodeType.StartObject, type);
yield return new XamlNode(XamlNodeType.EndObject);
break;
default:
yield break;
}
}
}
}

Просмотреть файл

@ -0,0 +1,253 @@
namespace OmniXaml.Parsers.XamlNodes
{
using System.Collections.Generic;
using MarkupExtensions;
using ProtoParser;
using Sprache;
using Typing;
public class XamlNodesPullParser
{
private readonly WiringContext wiringContext;
private IEnumerator<ProtoXamlNode> nodeStream;
public XamlNodesPullParser(WiringContext wiringContext)
{
this.wiringContext = wiringContext;
}
public IEnumerable<XamlNode> Parse(IEnumerable<ProtoXamlNode> protoNodes)
{
nodeStream = protoNodes.GetEnumerator();
SetNextNode();
foreach (var prefix in ParsePrefixDefinitions()) yield return prefix;
foreach (var element in ParseElements()) yield return element;
}
private IEnumerable<XamlNode> ParseElements(XamlMember hostingProperty = null)
{
SkipTextNodes();
if (hostingProperty != null)
{
yield return Inject.StartOfMember(hostingProperty);
}
while (CurrentNodeIsElement)
{
switch (nodeStream.Current.NodeType)
{
case NodeType.Element:
foreach (var xamlNode in ParseNonEmptyElement()) yield return xamlNode;
break;
case NodeType.EmptyElement:
foreach (var xamlNode in ParseEmptyElement()) yield return xamlNode;
break;
}
// There may be text nodes after each element. Skip all of them.
SkipTextNodes();
}
if (hostingProperty != null)
{
yield return Inject.EndOfMember();
}
}
private bool CurrentNodeIsElement => CurrentNodeType == NodeType.Element || CurrentNodeType == NodeType.EmptyElement;
private void SkipTextNodes()
{
while (CurrentNodeType == NodeType.Text)
{
SetNextNode();
}
}
private NodeType CurrentNodeType => nodeStream.Current?.NodeType ?? NodeType.None;
private IEnumerable<XamlNode> ParseEmptyElement()
{
yield return Inject.StartOfObject(nodeStream.Current.XamlType);
SetNextNode();
foreach (var member in ParseMembersOfObject()) yield return member;
yield return Inject.EndOfObject();
if (CurrentNodeType == NodeType.Text)
{
SetNextNode();
}
}
private IEnumerable<XamlNode> ParseNonEmptyElement()
{
yield return Inject.StartOfObject(nodeStream.Current.XamlType);
var parentType = nodeStream.Current.XamlType;
SetNextNode();
foreach (var xamlNode in ParseMembersOfObject()) { yield return xamlNode; }
foreach (var xamlNode in ParseContentPropertyIfAny(parentType)) { yield return xamlNode; }
SkipTextNodes();
foreach (var xamlNode in ParseNestedProperties(parentType)) { yield return xamlNode; }
yield return Inject.EndOfObject();
ReadEndTag();
}
private void ReadEndTag()
{
SkipTextNodes();
if (CurrentNodeType != NodeType.EndTag)
{
throw new XamlParseException("Expected End Tag");
}
SetNextNode();
}
private XamlMember GetContentProperty(XamlType parentType)
{
var propertyName = wiringContext.ContentPropertyProvider.GetContentPropertyName(parentType.UnderlyingType);
var member = wiringContext.TypeContext.Get(parentType.UnderlyingType).GetMember(propertyName);
return member;
}
private bool IsNestedPropertyImplicit => CurrentNodeType != NodeType.PropertyElement && CurrentNodeType != NodeType.EmptyPropertyElement &&
CurrentNodeType != NodeType.EndTag;
private IEnumerable<XamlNode> ParseNestedProperties(XamlType parentType)
{
while (CurrentNodeType == NodeType.PropertyElement || CurrentNodeType == NodeType.EmptyPropertyElement)
{
var member = nodeStream.Current.PropertyElement;
if (member.Type.IsCollection)
{
SetNextNode();
foreach (var xamlNode in ParseCollectionInsideThisProperty(member))
{
yield return xamlNode;
}
}
else
{
foreach (var xamlNode in ParseNestedProperty(member))
{
yield return xamlNode;
}
}
// If we reach an end tag we find a direct element, we may be reading a content property!
if (CurrentNodeType == NodeType.EndTag)
{
SetNextNode();
foreach (var xamlNode in ParseContentPropertyIfAny(parentType)) yield return xamlNode;
}
}
}
private IEnumerable<XamlNode> ParseContentPropertyIfAny(XamlType parentType)
{
if (IsNestedPropertyImplicit)
{
var contentProperty = GetContentProperty(parentType);
if (contentProperty.Type.IsCollection)
{
foreach (var xamlNode in ParseCollectionInsideThisProperty(contentProperty)) { yield return xamlNode; }
}
else
{
foreach (var xamlNode in ParseElements(contentProperty)) { yield return xamlNode; }
}
}
}
private void SetNextNode()
{
nodeStream.MoveNext();
}
private IEnumerable<XamlNode> ParseCollectionInsideThisProperty(XamlMember member)
{
yield return Inject.StartOfMember(member);
yield return Inject.GetObject();
yield return Inject.Items();
foreach (var xamlNode in ParseElements()) yield return xamlNode;
yield return Inject.EndOfMember();
yield return Inject.EndOfObject();
yield return Inject.EndOfMember();
}
private IEnumerable<XamlNode> ParseNestedProperty(XamlMember member)
{
yield return Inject.StartOfMember(member);
SetNextNode();
foreach (var xamlNode in ParseElements())
{
yield return xamlNode;
}
yield return Inject.EndOfMember();
}
private IEnumerable<XamlNode> ParseMembersOfObject()
{
while (CurrentNodeType == NodeType.Attribute)
{
var protoXamlNode = nodeStream.Current;
var valueOfMember = protoXamlNode.PropertyAttributeText;
yield return Inject.StartOfMember(protoXamlNode.PropertyAttribute);
if (IsMarkupExtension(valueOfMember))
{
foreach (var xamlNode in ParseMarkupExtension(valueOfMember)) yield return xamlNode;
}
else
{
yield return Inject.Value(valueOfMember);
}
yield return Inject.EndOfMember();
SetNextNode();
}
}
private IEnumerable<XamlNode> ParseMarkupExtension(string valueOfMember)
{
var tree = MarkupExtensionParser.MarkupExtension.Parse(valueOfMember);
var markupExtensionConverter = new MarkupExtensionNodeToXamlNodesConverter(wiringContext);
return markupExtensionConverter.Convert(tree);
}
private IEnumerable<XamlNode> ParsePrefixDefinitions()
{
while (CurrentNodeType == NodeType.PrefixDefinition)
{
var protoXamlNode = nodeStream.Current;
yield return Inject.PrefixDefinitionOfNamespace(protoXamlNode);
SetNextNode();
}
}
private static bool IsMarkupExtension(string text)
{
return text.Length > 3 && text.StartsWith("{") && text.EndsWith("}");
}
}
}

Просмотреть файл

@ -0,0 +1,11 @@
namespace OmniXaml.Parsers
{
using System;
public class XamlParseException : Exception
{
public XamlParseException(string message) : base(message)
{
}
}
}

Просмотреть файл

@ -1,7 +1,5 @@
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
@ -10,7 +8,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OmniXaml.Base.Interfaces")]
[assembly: AssemblyProduct("OmniXAML")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@ -28,4 +26,3 @@ using System.Runtime.InteropServices;
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("OmniXaml.Tests")]

Просмотреть файл

@ -7,18 +7,17 @@
{
public XamlType XamlType { get; set; }
public string Namespace { get; set; }
public ProtoNodeType NodeType { get; set; }
public NodeType NodeType { get; set; }
public XamlMember PropertyAttribute { get; set; }
public string Prefix { get; set; }
public XamlMember PropertyElement { get; set; }
public string PropertyAttributeText { get; set; }
protected bool Equals(ProtoXamlNode other)
{
return XamlTypesAreEqual(other) && string.Equals(Namespace, other.Namespace) && NodeType == other.NodeType;
}
private bool XamlTypesAreEqual(ProtoXamlNode other)
{
return XamlType.UnderlyingType == other.XamlType.UnderlyingType;
return Equals(XamlType, other.XamlType) && string.Equals(Namespace, other.Namespace) && NodeType == other.NodeType &&
Equals(PropertyAttribute, other.PropertyAttribute) && string.Equals(Prefix, other.Prefix) && Equals(PropertyElement, other.PropertyElement) &&
string.Equals(PropertyAttributeText, other.PropertyAttributeText);
}
public override bool Equals(object obj)
@ -27,17 +26,14 @@
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((ProtoXamlNode)obj);
}
@ -45,11 +41,49 @@
{
unchecked
{
var hashCode = XamlType?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ (Namespace?.GetHashCode() ?? 0);
var hashCode = (XamlType != null ? XamlType.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Namespace != null ? Namespace.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (int)NodeType;
hashCode = (hashCode * 397) ^ (PropertyAttribute != null ? PropertyAttribute.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Prefix != null ? Prefix.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (PropertyElement != null ? PropertyElement.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (PropertyAttributeText != null ? PropertyAttributeText.GetHashCode() : 0);
return hashCode;
}
}
public override string ToString()
{
object[] nodeType = { NodeType };
var str = string.Format("{0}: ", nodeType);
switch (NodeType)
{
case NodeType.EmptyElement:
case NodeType.Element:
{
str = string.Concat(str, XamlType.Name);
return str;
}
case NodeType.Attribute:
str = string.Concat(str, PropertyAttributeText);
return str;
case NodeType.PropertyElement:
case NodeType.EmptyPropertyElement:
str = string.Concat(str, PropertyElement);
return str;
case NodeType.Directive:
str = string.Concat(str, PropertyAttribute);
return str;
case NodeType.PrefixDefinition:
str = string.Concat($"{Prefix}:{Namespace}");
return str;
default:
{
return str;
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,28 @@
namespace OmniXaml.TypeConversion.BuiltInConverters
{
using System;
using System.Globalization;
public class BooleanConverter : ITypeConverter
{
public object ConvertFrom(CultureInfo culture, object value)
{
return bool.Parse((string) value);
}
public object ConvertTo(CultureInfo culture, object value, Type destinationType)
{
return value.ToString();
}
public bool CanConvertTo(Type destinationType)
{
return true;
}
public bool CanConvertFrom(Type sourceType)
{
return true;
}
}
}

Просмотреть файл

@ -0,0 +1,28 @@
namespace OmniXaml.TypeConversion.BuiltInConverters
{
using System;
using System.Globalization;
internal class EnumTypeConverter : ITypeConverter
{
public object ConvertFrom(CultureInfo culture, object value)
{
throw new NotImplementedException();
}
public object ConvertTo(CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
public bool CanConvertTo(Type destinationType)
{
throw new NotImplementedException();
}
public bool CanConvertFrom(Type sourceType)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -0,0 +1,28 @@
namespace OmniXaml.TypeConversion.BuiltInConverters
{
using System;
using System.Globalization;
public class NumberTypeConverter : ITypeConverter
{
public object ConvertFrom(CultureInfo culture, object value)
{
return int.Parse((string) value);
}
public object ConvertTo(CultureInfo culture, object value, Type destinationType)
{
return value.ToString();
}
public bool CanConvertTo(Type destinationType)
{
return true;
}
public bool CanConvertFrom(Type sourceType)
{
return true;
}
}
}

Просмотреть файл

@ -1,11 +1,11 @@
namespace OmniXaml.TypeConversion
namespace OmniXaml.TypeConversion.BuiltInConverters
{
using System;
using System.Globalization;
public class StringTypeConverter : ITypeConverter
{
public object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
public object ConvertFrom(CultureInfo culture, object value)
{
if (value == null)
{
@ -20,7 +20,7 @@
return value.ToString();
}
public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
public object ConvertTo(CultureInfo culture, object value, Type destinationType)
{
if (value == null)
{
@ -41,10 +41,24 @@
}
}
if (destinationType == typeof(double))
{
var str = value as string;
if (str != null)
{
double n;
if (double.TryParse(str, out n))
{
return n;
}
return null;
}
}
return value.ToString();
}
public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
public bool CanConvertTo(Type destinationType)
{
if (destinationType == typeof(string) || destinationType == typeof(int))
{
@ -54,7 +68,7 @@
return false;
}
public bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
public bool CanConvertFrom(Type sourceType)
{
return true;
}

Просмотреть файл

@ -5,12 +5,12 @@
public interface ITypeConverter
{
object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value);
object ConvertFrom(CultureInfo culture, object value);
object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType);
object ConvertTo(CultureInfo culture, object value, Type destinationType);
bool CanConvertTo(ITypeDescriptorContext context, Type destinationType);
bool CanConvertTo(Type destinationType);
bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType);
bool CanConvertFrom(Type sourceType);
}
}

Просмотреть файл

@ -5,7 +5,7 @@ namespace OmniXaml.TypeConversion
public interface ITypeConverterProvider
{
ITypeConverter GetTypeConverter(Type getType);
ITypeConverter GetTypeConverter(Type type);
void AddCatalog(IDictionary<Type, ITypeConverter> typeConverters);
}

Просмотреть файл

@ -8,7 +8,7 @@
public TypeConverterAttribute(Type typeConverter)
{
this.Converter = typeConverter;
Converter = typeConverter;
}
}
}

Просмотреть файл

@ -2,6 +2,8 @@
{
using System;
using System.Collections.Generic;
using System.Reflection;
using BuiltInConverters;
public class TypeConverterProvider : ITypeConverterProvider
{
@ -20,6 +22,7 @@
Register(typeof(short), new NumberTypeConverter());
Register(typeof(double), new NumberTypeConverter());
Register(typeof(float), new NumberTypeConverter());
Register(typeof(bool), new BooleanConverter());
}
private void Register(Type type, ITypeConverter converter)
@ -35,10 +38,20 @@
}
}
public ITypeConverter GetTypeConverter(Type getType)
public ITypeConverter GetTypeConverter(Type type)
{
ITypeConverter converter;
return converters.TryGetValue(getType, out converter) ? converter : null;
if (IsNullable(type))
{
type = Nullable.GetUnderlyingType(type);
}
return converters.TryGetValue(type, out converter) ? converter : null;
}
static bool IsNullable(Type type)
{
return Nullable.GetUnderlyingType(type) != null;
}
}
}

Просмотреть файл

@ -5,13 +5,9 @@
public static class CoreTypes
{
private static readonly XamlDirective ItemsField = new XamlDirective("_Items", XamlType.Builder.CreateForBuiltInType(typeof(List<object>)));
private static readonly XamlDirective InitializationField = new XamlDirective("_Initialization");
private static readonly XamlDirective MarkupExtensionArgumentsField = new XamlDirective("_MarkupExtensionArguments");
private static readonly XamlDirective UnknownContentField = new XamlDirective("_UnknownContent");
public static XamlDirective Items => ItemsField;
public static XamlDirective Initialization => InitializationField;
public static XamlDirective UnknownContent => UnknownContentField;
public static XamlType String => XamlType.Builder.CreateForBuiltInType(typeof(string));
public static object MarkupExtensionArguments => MarkupExtensionArgumentsField;
}

Просмотреть файл

@ -18,17 +18,7 @@
}
}
public override string ScopedName
{
get
{
if (!IsDotted)
{
return PropertyName;
}
return Owner.ScopedName + "." + PropertyName;
}
}
public string OwnerName
{
@ -54,7 +44,7 @@
string prefix;
string qualifiedName;
if (!XamlQualifiedName.Parse(longName, out prefix, out qualifiedName))
if (!XamlQualifiedName.TryParse(longName, out prefix, out qualifiedName))
{
return null;
}

Просмотреть файл

@ -5,12 +5,12 @@ namespace OmniXaml.Typing
public XamlDirective(string name)
: base(name)
{
this.IsDirective = true;
IsDirective = true;
}
public XamlDirective(string name, XamlType xamlType) : this(name)
{
this.Type = xamlType;
Type = xamlType;
}
}
}

Просмотреть файл

@ -31,13 +31,13 @@ namespace OmniXaml.Typing
public string Name => name;
public bool IsAttachable { get; set; }
public bool IsAttachable { get; }
public bool IsDirective { get; protected set; }
public bool IsDirective { get; set; }
public XamlType DeclaringType { get; private set; }
public XamlType DeclaringType { get; set; }
public bool IsUnreachable { get; private set; }
public bool IsUnreachable { get; set; }
public XamlType Type { get; set; }
@ -84,7 +84,7 @@ namespace OmniXaml.Typing
{
return true;
}
if (obj.GetType() != this.GetType())
if (obj.GetType() != GetType())
{
return false;
}

Просмотреть файл

@ -2,35 +2,22 @@ namespace OmniXaml.Typing
{
public abstract class XamlName
{
public const char PlusSign = '+';
public const char UnderScore = '_';
public const char Dot = '.';
protected XamlName()
: this(string.Empty)
{
}
public XamlName(string propertyName)
protected XamlName(string propertyName)
{
PropertyName = propertyName;
}
public XamlName(string prefix, string propertyName)
protected XamlName(string prefix, string propertyName)
{
PropertyName = propertyName;
this.Prefix = prefix ?? string.Empty;
Prefix = prefix ?? string.Empty;
}
public string PropertyName
{
get; protected set;
get; private set;
}
public abstract string ScopedName { get; }
public string Prefix { get; protected set; }
public string Namespace { get; protected set; }
@ -56,40 +43,23 @@ namespace OmniXaml.Typing
return true;
}
public static bool IsValidNameStartChar(char ch)
protected static bool IsValidNameStartChar(char ch)
{
if (!char.IsLetter(ch))
{
return ch == 95;
return ch == '_';
}
return true;
}
public static bool IsValidNameChar(char ch)
private static bool IsValidNameChar(char ch)
{
if (IsValidNameStartChar(ch) || char.IsDigit(ch))
{
return true;
}
return false;
return IsValidNameStartChar(ch) || char.IsDigit(ch);
}
public static bool IsValidQualifiedNameChar(char ch)
protected static bool IsValidQualifiedNameChar(char ch)
{
if (ch != 46)
{
return IsValidNameChar(ch);
}
return true;
}
public static bool IsValidQualifiedNameCharPlus(char ch)
{
if (!IsValidQualifiedNameChar(ch))
{
return ch == 43;
}
return true;
return ch == '.' || IsValidNameChar(ch);
}
}
}

Просмотреть файл

@ -18,7 +18,7 @@ namespace OmniXaml.Typing
public XamlNamespace(string xamlNamespaceUri, IEnumerable<ClrAssemblyPair> clrAssemblyPair) : this(xamlNamespaceUri)
{
this.mappings = new HashSet<ClrAssemblyPair>(clrAssemblyPair);
mappings = new HashSet<ClrAssemblyPair>(clrAssemblyPair);
}
public string NamespaceUri => xamlNamespaceUri;

Просмотреть файл

@ -1,7 +1,5 @@
namespace OmniXaml.Typing
{
using System;
public class XamlQualifiedName : XamlName
{
public XamlQualifiedName(string prefix, string propertyName)
@ -9,21 +7,39 @@ namespace OmniXaml.Typing
{
}
public override string ScopedName
private static bool IsNameValid(string name)
{
get
if (name.Length == 0 || !IsValidNameStartChar(name[0]))
{
if (!string.IsNullOrEmpty(Prefix))
{
return Prefix + ":" + PropertyName;
}
return PropertyName;
return false;
}
}
for (var index = 1; index < name.Length; ++index)
{
if (!IsValidQualifiedNameChar(name[index]))
{
return false;
}
}
return true;
}
public static bool Parse(string longName, out string prefix, out string name)
public static bool TryParse(string longName, out string prefix, out string name)
{
throw new NotImplementedException();
var startIndex = 0;
var length = longName.IndexOf(':');
prefix = string.Empty;
name = string.Empty;
if (length != -1)
{
prefix = longName.Substring(startIndex, length);
if (string.IsNullOrEmpty(prefix) || !IsNameValid(prefix))
{
return false;
}
startIndex = length + 1;
}
name = startIndex == 0 ? longName : longName.Substring(startIndex);
return !string.IsNullOrEmpty(name);
}
}
}

Просмотреть файл

@ -21,15 +21,15 @@ namespace OmniXaml.Typing
IsUnreachable = true;
}
public bool IsUnreachable { get; private set; }
public bool IsUnreachable { get; }
public Type UnderlyingType { get; private set; }
public Type UnderlyingType { get; }
public string Name { get; set; }
public XamlType BaseType { get; set; }
public bool IsCollection => typeof (IList).GetTypeInfo().IsAssignableFrom(this.UnderlyingType.GetTypeInfo());
public bool IsCollection => typeof (IList).GetTypeInfo().IsAssignableFrom(UnderlyingType.GetTypeInfo());
public bool IsContainer => IsCollection || IsDictionary;
@ -111,5 +111,7 @@ namespace OmniXaml.Typing
var otherUnderlyingType = type.UnderlyingType.GetTypeInfo();
return otherUnderlyingType.IsAssignableFrom(UnderlyingType.GetTypeInfo());
}
}
}

Просмотреть файл

@ -0,0 +1,11 @@
namespace OmniXaml
{
using System;
internal class ValueConversionException : Exception
{
public ValueConversionException(string message) : base(message)
{
}
}
}

Просмотреть файл

@ -8,8 +8,8 @@ namespace OmniXaml
public class WiringContextBuilder
{
private readonly IContentPropertyProvider contentPropertyProvider;
private readonly ITypeConverterProvider converterProvider;
private IContentPropertyProvider contentPropertyProvider;
private ITypeConverterProvider converterProvider;
private readonly TypeContextBuilder typingCoreBuilder = new TypeContextBuilder();
@ -44,6 +44,18 @@ namespace OmniXaml
return this;
}
public WiringContextBuilder WithContentPropertyProvider(IContentPropertyProvider provider)
{
contentPropertyProvider = provider;
return this;
}
public WiringContextBuilder WithConverterProvider(ITypeConverterProvider provider)
{
converterProvider = provider;
return this;
}
public WiringContext Build()
{
var typingCore = typingCoreBuilder.Build();

Просмотреть файл

@ -0,0 +1,17 @@
namespace OmniXaml
{
internal class XamlElement
{
public XamlElement(string name, string @namespace)
{
Name = name;
Namespace = @namespace;
}
public XamlNodeType XamlNodeType { get; set; }
public string Name { get; set; }
public string Namespace { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,51 @@
namespace OmniXaml
{
using System.Collections.Generic;
using Typing;
public class XamlReader : IXamlReader
{
private readonly IEnumerator<XamlNode> nodeStream;
private XamlNode current;
private readonly XamlNode endOfStreamNode = new XamlNode(XamlNode.InternalNodeType.EndOfStream);
public XamlReader(IEnumerable<XamlNode> xamlNodes)
{
nodeStream = xamlNodes.GetEnumerator();
}
public XamlNodeType NodeType => current.NodeType;
public bool IsEof => current.IsEof;
public XamlType Type => current.XamlType;
public XamlMember Member => current.Member;
public NamespaceDeclaration Namespace => current.NamespaceDeclaration;
public object Value => current.Value;
public bool Read()
{
while (nodeStream.MoveNext())
{
current = nodeStream.Current;
if (current.NodeType == XamlNodeType.None)
{
if (current.IsEof)
{
return !IsEof;
}
}
if (current.NodeType != XamlNodeType.None)
{
return !IsEof;
}
}
current = endOfStreamNode;
return !IsEof;
}
}
}

Просмотреть файл

@ -0,0 +1,51 @@
namespace OmniXaml
{
using System;
using System.IO;
using Glass;
using Parsers.ProtoParser;
using Parsers.XamlNodes;
public class XamlXmlLoader : IXamlLoader
{
private readonly IObjectAssembler objectAssembler;
private readonly WiringContext wiringContext;
public XamlXmlLoader(IObjectAssembler objectAssembler, WiringContext wiringContext)
{
Guard.ThrowIfNull(objectAssembler, nameof(objectAssembler));
Guard.ThrowIfNull(wiringContext, nameof(wiringContext));
this.objectAssembler = objectAssembler;
this.wiringContext = wiringContext;
}
public object Load(Stream stream)
{
using (var t = new StreamReader(stream))
return Load(t.ReadToEnd(), null);
}
public object Load(Stream stream, object rootInstance)
{
throw new NotImplementedException();
}
private object Load(string xml, object rootInstance)
{
var pullParser = new XamlNodesPullParser(wiringContext);
var xamlXmlReader = new XamlReader(pullParser.Parse(new ProtoParser(wiringContext.TypeContext).Parse(xml)));
return Load(xamlXmlReader, rootInstance);
}
public object Load(IXamlReader reader, object rootObject = null)
{
while (reader.Read())
{
objectAssembler.WriteNode(reader);
}
return objectAssembler.Result;
}
}
}

Просмотреть файл

@ -1,39 +0,0 @@
namespace OmniXaml
{
using System.Collections.Generic;
using System.Xml;
public class XmlNode
{
private readonly string name;
private readonly string xamlNamespace;
private readonly object value;
private readonly IDictionary<string, string> attributes;
private readonly XmlNodeType nodeType;
public XmlNode(string name, string xamlNamespace, object value, IDictionary<string, string> attributes, XmlNodeType nodeType)
{
this.name = name;
this.xamlNamespace = xamlNamespace;
this.value = value;
this.attributes = attributes;
this.nodeType = nodeType;
}
public string Name => name;
public string XamlNamespace => xamlNamespace;
public object Value => value;
public IDictionary<string, string> Attributes => attributes;
public XmlNodeType NodeType => nodeType;
public bool IsCollapsed { get; set; }
}
}

249
OmniXaml/Settings.StyleCop Normal file
Просмотреть файл

@ -0,0 +1,249 @@
<StyleCopSettings Version="105">
<Analyzers>
<Analyzer AnalyzerId="StyleCop.CSharp.DocumentationRules">
<Rules>
<Rule Name="ElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="EnumerationItemsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationMustContainValidXml">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustHaveSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementDocumentationMustHaveSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustHaveSummaryText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementDocumentationMustHaveSummaryText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustNotHaveDefaultSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParametersMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustMatchElementParameters">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustDeclareParameterName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementReturnValueMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementReturnValueDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="VoidReturnValueMustNotBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParametersMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParametersMustBeDocumentedPartialClass">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustMatchTypeParameters">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustDeclareParameterName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PropertySummaryDocumentationMustMatchAccessors">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PropertySummaryDocumentationMustOmitSetAccessorWithRestrictedAccess">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustNotBeCopiedAndPasted">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="SingleLineCommentsMustNotUseDocumentationStyleSlashes">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustNotBeEmpty">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustContainWhitespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationMustMeetCharacterPercentage">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ConstructorSummaryDocumentationMustBeginWithStandardText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DestructorSummaryDocumentationMustBeginWithStandardText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationHeadersMustNotContainBlankLines">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="IncludedDocumentationXPathDoesNotExist">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="IncludeNodeDoesNotContainValidFileAndPath">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="InheritDocMustBeUsedWithInheritingClass">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustBeSpelledCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileMustHaveHeader">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustShowCopyright">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustHaveCopyrightText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustContainFileName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderFileNameDocumentationMustMatchFileName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustHaveValidCompanyText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderFileNameDocumentationMustMatchTypeName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.OrderingRules">
<Rules>
<Rule Name="UsingDirectivesMustBePlacedWithinNamespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="StyleCop.CSharp.ReadabilityRules">
<Rules>
<Rule Name="PrefixLocalCallsWithThis">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PrefixCallsCorrectly">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="UseBuiltInTypeAlias">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
</Analyzers>
</StyleCopSettings>

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>

Просмотреть файл

@ -0,0 +1,49 @@
<Application x:Class="TestApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<BorderGapMaskConverter x:Key="BorderGapMaskConverter"/>
<Style TargetType="{x:Type GroupBox}">
<Setter Property="BorderBrush" Value="#D5DFE5"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupBox}">
<Grid SnapsToDevicePixels="true">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="6"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="6"/>
</Grid.RowDefinitions>
<Border BorderBrush="Transparent" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="4" Grid.Column="0" CornerRadius="4" Grid.Row="1" Grid.RowSpan="3"/>
<Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" Grid.ColumnSpan="4" CornerRadius="4" Grid.Row="1" Grid.RowSpan="3">
<Border.OpacityMask>
<MultiBinding ConverterParameter="7" Converter="{StaticResource BorderGapMaskConverter}">
<Binding ElementName="Header" Path="ActualWidth"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>
<Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>
</MultiBinding>
</Border.OpacityMask>
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3">
<Border BorderBrush="White" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2"/>
</Border>
</Border>
<Border x:Name="Header" Grid.Column="1" Padding="3,1,3,0" Grid.Row="0" Grid.RowSpan="2">
<ContentPresenter TextElement.FontSize="16" ContentSource="Header" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ContentPresenter Grid.ColumnSpan="2" Grid.Column="1" Margin="{TemplateBinding Padding}" Grid.Row="2" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>

Просмотреть файл

@ -0,0 +1,11 @@
namespace TestApplication
{
using System.Windows;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

Просмотреть файл

@ -0,0 +1,60 @@
namespace TestApplication
{
using System.Windows;
using System.Windows.Controls;
public class GridExpanderSizeBehavior
{
public static readonly DependencyProperty SizeRowsToExpanderStateProperty =
DependencyProperty.RegisterAttached(
"SizeRowsToExpanderState",
typeof(bool),
typeof(GridExpanderSizeBehavior),
new FrameworkPropertyMetadata(false, SizeRowsToExpanderStateChanged));
public static void SetSizeRowsToExpanderState(Grid grid, bool value)
{
grid.SetValue(SizeRowsToExpanderStateProperty, value);
}
private static void SizeRowsToExpanderStateChanged(object target, DependencyPropertyChangedEventArgs e)
{
Grid grid = target as Grid;
if (grid != null)
{
if ((bool)e.NewValue == true)
{
grid.AddHandler(Expander.ExpandedEvent, new RoutedEventHandler(Expander_Expanded));
grid.AddHandler(Expander.CollapsedEvent, new RoutedEventHandler(Expander_Collapsed));
}
else if ((bool)e.OldValue == true)
{
grid.RemoveHandler(Expander.ExpandedEvent, new RoutedEventHandler(Expander_Expanded));
grid.RemoveHandler(Expander.CollapsedEvent, new RoutedEventHandler(Expander_Collapsed));
}
}
}
private static void Expander_Expanded(object sender, RoutedEventArgs e)
{
Grid grid = sender as Grid;
Expander expander = e.OriginalSource as Expander;
int row = Grid.GetRow(expander);
if (row <= grid.RowDefinitions.Count)
{
grid.RowDefinitions[row].Height = new GridLength(1.0, GridUnitType.Star);
}
}
private static void Expander_Collapsed(object sender, RoutedEventArgs e)
{
Grid grid = sender as Grid;
Expander expander = e.OriginalSource as Expander;
int row = Grid.GetRow(expander);
if (row <= grid.RowDefinitions.Count)
{
grid.RowDefinitions[row].Height = new GridLength(1.0, GridUnitType.Auto);
}
}
}
}

Просмотреть файл

@ -0,0 +1,183 @@
namespace TestApplication
{
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using OmniXaml;
using OmniXaml.Assembler;
using OmniXaml.Tests.Classes;
using WpfAdaptation;
using ContentPropertyProvider = WpfAdaptation.ContentPropertyProvider;
using TextBlock = System.Windows.Controls.TextBlock;
using XamlResources = Xaml.Tests.Resources.Dummy;
public class MainViewModel : ViewModel
{
private ObservableCollection<Node> representation;
private Node selectedItem;
private Snippet selectedSnippet;
private string xaml;
public MainViewModel()
{
IXamlSnippetProvider snippetsProvider = new XamlSnippetProvider();
Snippets = snippetsProvider.Snippets;
Xaml = XamlResources.ChildCollection;
LoadCommand = new RelayCommand(o => LoadXaml());
LoadForWpfCommand = new RelayCommand(o => LoadXamlForWpf());
SetSelectedItemCommand = new RelayCommand(o => SetSelectedItem((Node)o));
SetSelectedSnippetCommand = new RelayCommand(o => SetSelectedSnippet());
}
private WiringContext ContextForWpf
{
get
{
var windowType = typeof(Window);
var textBlockType = typeof(TextBlock);
var toggleButtonType = typeof(ToggleButton);
var context = new WiringContextBuilder()
.WithNsPrefix("", "root")
.WithXamlNs("root", windowType.Assembly, windowType.Namespace)
.WithXamlNs("root", textBlockType.Assembly, textBlockType.Namespace)
.WithXamlNs("root", toggleButtonType.Assembly, toggleButtonType.Namespace)
.WithContentPropertyProvider(new ContentPropertyProvider())
.WithConverterProvider(new ConverterProvider())
.Build();
return context;
}
}
private WiringContext ContextForTestClasses
{ get; }
= new WiringContextBuilder().AddNsForThisType("", "root", typeof(DummyClass))
.WithContentPropertiesFromAssemblies(new[] { typeof(DummyClass).Assembly })
.Build();
public IList Snippets { get; set; }
public Node SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
OnPropertyChanged();
}
}
public ObservableCollection<Node> Representation
{
get { return representation; }
set
{
representation = value;
OnPropertyChanged();
}
}
public string Xaml
{
get { return xaml; }
set
{
xaml = value;
OnPropertyChanged();
}
}
public ICommand LoadCommand { get; private set; }
public ICommand LoadForWpfCommand { get; private set; }
public ICommand SetSelectedItemCommand { get; private set; }
public ICommand SetSelectedSnippetCommand { get; private set; }
public Snippet SelectedSnippet
{
get { return selectedSnippet; }
set
{
selectedSnippet = value;
OnPropertyChanged();
}
}
private void LoadXamlForWpf()
{
try
{
var localLoader = new XamlXmlLoader(new ObjectAssembler(ContextForWpf), ContextForWpf);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(Xaml)))
{
var window = (Window)localLoader.Load(stream);
window.Show();
}
}
catch (Exception e)
{
MessageBox.Show(
$"There has been a problem loading the XAML.\n\nException:\n{GetFirstNChars(e.ToString(), 500)}",
"Load problem");
}
}
private void SetSelectedSnippet()
{
Xaml = SelectedSnippet.Xaml;
}
private void SetSelectedItem(Node o)
{
SelectedItem = o;
}
private void LoadXaml()
{
try
{
var loader = new XamlXmlLoader(new ObjectAssembler(ContextForTestClasses), ContextForTestClasses);
var rootObject = LoadFromString(Xaml, loader);
Representation = ConvertToViewNodes(rootObject);
}
catch (Exception e)
{
MessageBox.Show(
$"There has been a problem loading the XAML.\n\nException:\n{GetFirstNChars(e.ToString(), 500)}",
"Load problem");
}
}
private static string GetFirstNChars(string str, int max)
{
if (str.Length <= max)
{
return str;
}
return str.Substring(0, max) + "…";
}
private static object LoadFromString(string xaml, IXamlLoader loader)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml)))
{
return loader.Load(stream);
}
}
private static ObservableCollection<Node> ConvertToViewNodes(object result)
{
return new ObservableCollection<Node>
{
new Node(result)
};
}
}
}

Просмотреть файл

@ -0,0 +1,114 @@
<Window x:Class="TestApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:testApplication="clr-namespace:TestApplication"
mc:Ignorable="d"
WindowStartupLocation="CenterScreen"
Title="OmniXAML Loader" Height="509.456" Width="667.407">
<Window.Resources>
<CollectionViewSource x:Key="SortedSnippets" Source="{Binding Snippets}">
<CollectionViewSource.SortDescriptions>
<componentModel:SortDescription Direction="Ascending" PropertyName="Name" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<Style x:Key="XamlTextBoxStyle" TargetType="TextBox">
<Setter Property="AcceptsReturn" Value="True" />
<Setter Property="AcceptsTab" Value="True" />
<Setter Property="FontSize" Value="16"></Setter>
</Style>
</Window.Resources>
<Window.DataContext>
<testApplication:MainViewModel />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid testApplication:GridExpanderSizeBehavior.SizeRowsToExpanderState="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Expander Grid.Row="0" Header="XAML" IsExpanded="True">
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" >
<StackPanel.Resources>
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Margin" Value="5" />
<Setter Property="Padding" Value="8" />
</Style>
</StackPanel.Resources>
<Button VerticalAlignment="Bottom" IsDefault="True" Content="Load"
Command="{Binding LoadCommand}" Style="{StaticResource ButtonStyle}" />
<Button VerticalAlignment="Bottom" Content="Load for WPF"
Command="{Binding LoadForWpfCommand}" Style="{StaticResource ButtonStyle}" />
</StackPanel>
<TextBox Text="{Binding Xaml}" Style="{StaticResource XamlTextBoxStyle}" />
</DockPanel>
</Expander>
<Expander Grid.Row="1" Header="XAML Snippets" VerticalAlignment="Bottom" DockPanel.Dock="Bottom">
<ListBox ItemsSource="{Binding Source={StaticResource SortedSnippets}}" SelectedItem="{Binding SelectedSnippet}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type testApplication:Snippet}">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding SetSelectedSnippetCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
</Expander>
</Grid>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Center" VerticalAlignment="Stretch" />
<GroupBox Grid.Column="2" Header="Structure">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="3*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="5*" />
</Grid.RowDefinitions>
<TreeView ItemsSource="{Binding Representation}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<i:InvokeCommandAction Command="{Binding SetSelectedItemCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeView}}, Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type testApplication:Node}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding TypeName}" ToolTip="{Binding Tag}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate DataType="{x:Type testApplication:Node}">
<TextBlock Text="{Binding TypeName}" ToolTip="{Binding Tag}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded}" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
<GridSplitter Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Stretch" Height="5" />
<xctk:PropertyGrid ShowTitle="True" Grid.Row="2" SelectedObject="{Binding SelectedItem.Data}" IsReadOnly="True" />
</Grid>
</GroupBox>
</Grid>
</Window>

Просмотреть файл

@ -0,0 +1,15 @@
namespace TestApplication
{
using System.Windows;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

Просмотреть файл

@ -0,0 +1,47 @@
namespace TestApplication
{
using System.Collections;
using System.Collections.ObjectModel;
using System.Reflection;
public class Node : ViewModel
{
private bool isExpanded;
public Node(object data)
{
this.Data = data;
IsExpanded = true;
TypeName = data.GetType().Name;
Tag = data.ToString();
foreach (var runtimeProperty in data.GetType().GetRuntimeProperties())
{
if (typeof (ICollection).IsAssignableFrom(runtimeProperty.PropertyType))
{
var collection = runtimeProperty.GetValue(data) as ICollection;
foreach (var item in collection)
{
Children.Add(new Node(item));
}
}
}
}
public string Tag { get; set; }
public ObservableCollection<Node> Children { get; } = new ObservableCollection<Node>();
public string TypeName { get; set; }
public object Data { get; }
public bool IsExpanded
{
get { return isExpanded; }
set
{
isExpanded = value;
OnPropertyChanged();
}
}
}
}

Просмотреть файл

@ -0,0 +1,880 @@

#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace TestApplication.Properties
{
using System;
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage
/// </summary>
/// <example><code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example><code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Indicates that collection or enumerable value does not contain null elements
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemNotNullAttribute : Attribute { }
/// <summary>
/// Indicates that collection or enumerable value can contain null elements
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemCanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Delegate)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class ValueProviderAttribute : Attribute
{
public ValueProviderAttribute(string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>
/// </summary>
/// <example><code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() =&gt; Property)</c></item>
/// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br/>
/// <c>canbenull</c> annotation is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt &lt;= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly
/// (e.g. via reflection, in external library), so this symbol
/// will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused
/// (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used
/// </summary>
[MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled
/// when the invoked method is on stack. If the parameter is a delegate,
/// indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated
/// while the method is executed
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>
/// </summary>
/// <example><code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~)
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
public string BasePath { get; private set; }
}
/// <summary>
/// Specifies SourceTemplate
/// TODO: documentation
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SourceTemplateAttribute : Attribute { }
/// <summary>
/// TODO: documentation
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class MacroAttribute : Attribute
{
public string Expression { get; set; }
public int Editable { get; set; }
public string Target { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class RazorSectionAttribute : Attribute { }
/// <summary>
/// Indicates how method invocation affects content of the collection
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class CollectionAccessAttribute : Attribute
{
public CollectionAccessAttribute(CollectionAccessType collectionAccessType)
{
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; private set; }
}
[Flags]
public enum CollectionAccessType
{
/// <summary>Method does not use or modify content of the collection</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute"/> attribute
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class AssertionMethodAttribute : Attribute { }
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AssertionConditionAttribute : Attribute
{
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; private set; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted
/// </summary>
public enum AssertionConditionType
{
/// <summary>Marked parameter should be evaluated to true</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value</summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TerminatesProgramAttribute : Attribute { }
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class LinqTunnelAttribute : Attribute { }
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class NoEnumerationAttribute : Attribute { }
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RegexPatternAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be
/// treated as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c>
/// type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class XamlItemsControlAttribute : Attribute { }
/// <summary>
/// XAML attibute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute"/> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspChildControlTypeAttribute : Attribute
{
public AspChildControlTypeAttribute(string tagName, Type controlType)
{
TagName = tagName;
ControlType = controlType;
}
public string TagName { get; private set; }
public Type ControlType { get; private set; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspMethodPropertyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspRequiredAttributeAttribute : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
public string Attribute { get; private set; }
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspTypePropertyAttribute : Attribute
{
public bool CreateConstructorReferences { get; private set; }
public AspTypePropertyAttribute(bool createConstructorReferences)
{
CreateConstructorReferences = createConstructorReferences;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorImportNamespaceAttribute : Attribute
{
public RazorImportNamespaceAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorInjectionAttribute : Attribute
{
public RazorInjectionAttribute(string type, string fieldName)
{
Type = type;
FieldName = fieldName;
}
public string Type { get; private set; }
public string FieldName { get; private set; }
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorHelperCommonAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class RazorLayoutAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteLiteralMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RazorWriteMethodParameterAttribute : Attribute { }
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns
/// </remarks>
[AttributeUsage(AttributeTargets.All)]
public sealed class NoReorder : Attribute { }
}

Просмотреть файл

@ -0,0 +1,55 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("OmniXAML Test Application")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OmniXAML")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

78
OmniXaml/TestApplication/Properties/Resources.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,78 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TestApplication.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TestApplication.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to &lt;DummyClass xmlns=&quot;root&quot;&gt;
/// &lt;DummyClass.Items&gt;
/// &lt;Item/&gt;
/// &lt;Item/&gt;
/// &lt;Item/&gt;
/// &lt;/DummyClass.Items&gt;
///&lt;/DummyClass&gt;.
/// </summary>
internal static string SampleXaml {
get {
return ResourceManager.GetString("SampleXaml", resourceCulture);
}
}
}
}

Просмотреть файл

@ -117,30 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Stage1" xml:space="preserve">
<value>&lt;Window xmlns="root" Title="Hello OmniXaml!"&gt;
&lt;Window.Content&gt;
&lt;Grid&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition /&gt;
&lt;ColumnDefinition /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;Grid.Children&gt;
&lt;TextBlock Text="XAML is the way" Grid.Column="0" /&gt;
&lt;TextBlock Text="To make you invincible :D" Grid.Column="1" /&gt;
&lt;/Grid.Children&gt;
&lt;/Grid&gt;
&lt;/Window.Content&gt;
&lt;/Window&gt;</value>
</data>
<data name="Window" xml:space="preserve">
<value>&lt;Window xmlns="root"&gt;&lt;/Window&gt;</value>
</data>
<data name="WindowWithContent" xml:space="preserve">
<value>&lt;Window xmlns="root"&gt;
&lt;Window.Content&gt;
&lt;TextBlock Text="Saludos cordiales!" /&gt;
&lt;/Window.Content&gt;
&lt;/Window&gt;</value>
<data name="SampleXaml" xml:space="preserve">
<value>&lt;DummyClass xmlns="root"&gt;
&lt;DummyClass.Items&gt;
&lt;Item/&gt;
&lt;Item/&gt;
&lt;Item/&gt;
&lt;/DummyClass.Items&gt;
&lt;/DummyClass&gt;</value>
</data>
</root>

26
OmniXaml/TestApplication/Properties/Settings.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TestApplication.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

Просмотреть файл

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

Просмотреть файл

@ -0,0 +1,54 @@
namespace TestApplication
{
using System;
using System.Diagnostics;
using System.Windows.Input;
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> execute;
readonly Predicate<object> canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return canExecute == null ? true : canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
execute(parameter);
}
#endregion // ICommand Members
}
}

Просмотреть файл

@ -0,0 +1,156 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A49A57C4-6DB5-44A0-869B-39EED7884A0B}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TestApplication</RootNamespace>
<AssemblyName>TestApplication</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Reflection" />
<Reference Include="System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="Xceed.Wpf.AvalonDock, Version=2.4.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>..\packages\Extended.Wpf.Toolkit.2.4.0\lib\net40\Xceed.Wpf.AvalonDock.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Aero, Version=2.4.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>..\packages\Extended.Wpf.Toolkit.2.4.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.Aero.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Metro, Version=2.4.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>..\packages\Extended.Wpf.Toolkit.2.4.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.Metro.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.VS2010, Version=2.4.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>..\packages\Extended.Wpf.Toolkit.2.4.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.VS2010.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Xceed.Wpf.DataGrid, Version=2.4.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>..\packages\Extended.Wpf.Toolkit.2.4.0\lib\net40\Xceed.Wpf.DataGrid.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Xceed.Wpf.Toolkit, Version=2.4.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>..\packages\Extended.Wpf.Toolkit.2.4.0\lib\net40\Xceed.Wpf.Toolkit.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="GridExpanderSizeBehavior.cs" />
<Compile Include="RelayCommand.cs" />
<Compile Include="ViewModel.cs" />
<Compile Include="WpfAdaptation\ConverterAdapter.cs" />
<Compile Include="WpfAdaptation\ContentPropertyProvider.cs" />
<Compile Include="WpfAdaptation\ConverterProvider.cs" />
<Compile Include="XamlSnippetProvider.cs" />
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="MainViewModel.cs" />
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Node.cs" />
<Compile Include="Properties\Annotations.cs" />
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<AppDesigner Include="Properties\" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Xaml.Tests.Resources\Xaml.Tests.Resources.csproj">
<Project>{9b517520-4d99-4bf5-8219-a643f718f6dd}</Project>
<Name>Xaml.Tests.Resources</Name>
</ProjectReference>
<ProjectReference Include="..\OmniXaml\OmniXaml.csproj">
<Project>{0D9CC1DE-84C3-40D7-9CC5-B7751E0B25D1}</Project>
<Name>OmniXaml</Name>
</ProjectReference>
<ProjectReference Include="..\Tests\OmniXaml.Tests.Classes\OmniXaml.Tests.Classes.csproj">
<Project>{E6FDA529-90C2-4DDA-9080-7E7EEF64B2CA}</Project>
<Name>OmniXaml.Tests.Classes</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,17 @@
namespace TestApplication
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Properties;
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
namespace TestApplication.WpfAdaptation
{
using System;
using System.Reflection;
using System.Windows.Markup;
using OmniXaml;
using OmniXaml.Catalogs;
public class ContentPropertyProvider : IContentPropertyProvider
{
public string GetContentPropertyName(Type type)
{
return type.GetTypeInfo().GetCustomAttribute<ContentPropertyAttribute>().Name;
}
public void AddCatalog(ContentPropertyCatalog catalog)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -0,0 +1,61 @@
namespace TestApplication.WpfAdaptation
{
using System;
using System.ComponentModel;
using System.Globalization;
using OmniXaml.TypeConversion;
using ITypeDescriptorContext = System.ComponentModel.ITypeDescriptorContext;
public class ConverterAdapter : ITypeConverter
{
private readonly TypeConverter converter;
public ConverterAdapter(TypeConverter converter)
{
this.converter = converter;
}
public object ConvertFrom(CultureInfo culture, object value)
{
ITypeDescriptorContext typeDescriptor = new FakeDescriptor();
return converter.ConvertFrom(typeDescriptor, culture, value);
}
public object ConvertTo(CultureInfo culture, object value, Type destinationType)
{
return converter.ConvertTo(null, culture, value, destinationType);
}
public bool CanConvertTo(Type destinationType)
{
return converter.CanConvertTo(null, destinationType);
}
public bool CanConvertFrom(Type sourceType)
{
return converter.CanConvertFrom(null, sourceType);
}
}
public class FakeDescriptor : ITypeDescriptorContext
{
public object GetService(Type serviceType)
{
return null;
}
public bool OnComponentChanging()
{
throw new NotImplementedException();
}
public void OnComponentChanged()
{
throw new NotImplementedException();
}
public IContainer Container { get; }
public object Instance { get; }
public PropertyDescriptor PropertyDescriptor { get; }
}
}

Просмотреть файл

@ -0,0 +1,44 @@
namespace TestApplication.WpfAdaptation
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using OmniXaml.TypeConversion;
using TypeConverterAttribute = System.ComponentModel.TypeConverterAttribute;
public class ConverterProvider : ITypeConverterProvider
{
private readonly TypeConverterProvider fallback;
public ConverterProvider()
{
fallback = new TypeConverterProvider();
}
public ITypeConverter GetTypeConverter(Type type)
{
var converter = fallback.GetTypeConverter(type);
if (converter == null)
{
var typeConverterAttribute = type.GetTypeInfo().GetCustomAttribute<TypeConverterAttribute>();
if (typeConverterAttribute == null)
{
return null;
}
var qualifiedName = typeConverterAttribute.ConverterTypeName;
var converterType = Type.GetType(qualifiedName, true);
var converterInstance = (TypeConverter) Activator.CreateInstance(converterType);
converter = new ConverterAdapter(converterInstance);
}
return converter;
}
public void AddCatalog(IDictionary<Type, ITypeConverter> typeConverters)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -0,0 +1,65 @@
namespace TestApplication
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Resources;
using Xaml.Tests.Resources;
public interface IXamlSnippetProvider
{
IList Snippets { get; }
}
public class XamlSnippetProvider : IXamlSnippetProvider
{
private readonly ICollection<Snippet> snippets = new Collection<Snippet>();
public XamlSnippetProvider()
{
var assembly = typeof(Dummy).Assembly;
var resourceIds = new[] {"Xaml.Tests.Resources.Dummy.resources", "Xaml.Tests.Resources.Wpf.resources" };
foreach (var resourceId in resourceIds)
{
try
{
using (var reader = new ResourceReader(assembly.GetManifestResourceStream(resourceId)))
{
var enumerator = reader.GetEnumerator();
while (enumerator.MoveNext())
{
var name = enumerator.Key as string;
var xaml = enumerator.Value as string;
if (name != null && xaml != null)
{
snippets.Add(new Snippet(name, xaml));
}
}
}
}
catch (Exception e)
{
Debug.WriteLine($"Cannot load snippets. Exception: {e}");
}
}
}
public IList Snippets => new ReadOnlyCollection<Snippet>(snippets.ToList());
}
public class Snippet
{
public Snippet(string name, string xaml)
{
Name = name;
Xaml = xaml;
}
public string Name { get; set; }
public string Xaml { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Extended.Wpf.Toolkit" version="2.4.0" targetFramework="net46" userInstalled="true" />
</packages>

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше