Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

import repo from mercural/bitbucket (without history) and update name…

…space
  • Loading branch information...
commit ce6e98666d85c019e8a72fa40ed71dae18f407ad 1 parent 5875666
Rui Carvalho authored
Showing with 2,683 additions and 0 deletions.
  1. +2 −0  .gitignore
  2. +7 −0 Build.ps1
  3. +106 −0 Build/Build.proj
  4. +34 −0 Build/Build.tasks
  5. BIN  Build/ILMerge.MSBuild.Tasks.dll
  6. 0  Build/ilmerge.ignore.txt
  7. +21 −0 Common/CommonAssemblyInfo.cs
  8. +21 −0 ConfArt.nuspec
  9. +47 −0 ConfArt.sln
  10. +3 −0  Src/ArtOfNet.FluentConfiguration/ArtOfNet.FluentConfiguration.csproj.vs10x
  11. +81 −0 Src/ArtOfNet.FluentConfiguration/ConfArt.csproj
  12. +99 −0 Src/ArtOfNet.FluentConfiguration/ConfigurationMapper.cs
  13. +12 −0 Src/ArtOfNet.FluentConfiguration/Contracts/IConfigurationMapping.cs
  14. +15 −0 Src/ArtOfNet.FluentConfiguration/Contracts/IConfigurationMappingsBase.cs
  15. +24 −0 Src/ArtOfNet.FluentConfiguration/Contracts/IHideObjectMembers.cs
  16. +55 −0 Src/ArtOfNet.FluentConfiguration/Core/AssemblyHelper.cs
  17. +13 −0 Src/ArtOfNet.FluentConfiguration/Core/AutoConfigurationMapping.cs
  18. +24 −0 Src/ArtOfNet.FluentConfiguration/Core/ConfigurationMappingType.cs
  19. +90 −0 Src/ArtOfNet.FluentConfiguration/Core/ConfigurationMappingsBase.cs
  20. +148 −0 Src/ArtOfNet.FluentConfiguration/Core/ConvertibleBase.cs
  21. +141 −0 Src/ArtOfNet.FluentConfiguration/Core/DynamicConfigurationValues.cs
  22. +264 −0 Src/ArtOfNet.FluentConfiguration/Core/DynamicXml.cs
  23. +65 −0 Src/ArtOfNet.FluentConfiguration/Core/PropertySetterExpression.cs
  24. +175 −0 Src/ArtOfNet.FluentConfiguration/Core/ValueFactory.cs
  25. +39 −0 Src/ArtOfNet.FluentConfiguration/Exceptions/DynamicXmlParseException.cs
  26. +8 −0 Src/ArtOfNet.FluentConfiguration/Exceptions/InternalExceptionEnumeration.cs
  27. +11 −0 Src/ArtOfNet.FluentConfiguration/Exceptions/MapperInvocationException.cs
  28. +26 −0 Src/ArtOfNet.FluentConfiguration/Exceptions/NotAMappedTypeException.cs
  29. +54 −0 Src/ArtOfNet.FluentConfiguration/Extensions/PropertyInfoExtensions.cs
  30. +36 −0 Src/ArtOfNet.FluentConfiguration/Properties/AssemblyInfo.cs
  31. +4 −0 Src/ArtOfNet.FluentConfiguration/packages.config
  32. +6 −0 Tests/ArtOfNet.FluentConfiguration.Tests/App.config
  33. +59 −0 Tests/ArtOfNet.FluentConfiguration.Tests/AssemblyHelperTests.Cs
  34. +100 −0 Tests/ArtOfNet.FluentConfiguration.Tests/DynamicXmlTests.cs
  35. +87 −0 Tests/ArtOfNet.FluentConfiguration.Tests/FluentConfigurationTests.csproj
  36. +3 −0  Tests/ArtOfNet.FluentConfiguration.Tests/FluentConfigurationTests.csproj.vs10x
  37. +36 −0 Tests/ArtOfNet.FluentConfiguration.Tests/Properties/AssemblyInfo.cs
  38. +36 −0 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/Contact.cs
  39. +19 −0 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/User.cs
  40. +30 −0 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/UserHelper.cs
  41. +18 −0 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/UserMap.cs
  42. +162 −0 Tests/ArtOfNet.FluentConfiguration.Tests/ScenarioTest.cs
  43. +36 −0 Tests/ArtOfNet.FluentConfiguration.Tests/TestFixtureBase.cs
  44. +58 −0 Tests/ArtOfNet.FluentConfiguration.Tests/ValueFactoryTests.cs
  45. +4 −0 Tests/ArtOfNet.FluentConfiguration.Tests/packages.config
  46. +242 −0 Tests/TestTaskRunner/Program.cs
  47. +36 −0 Tests/TestTaskRunner/Properties/AssemblyInfo.cs
  48. +120 −0 Tests/TestTaskRunner/TestTaskRunner.csproj
  49. BIN  Tests/TestTaskRunner/TestTaskRunner_TemporaryKey.pfx
  50. BIN  Tools/ILMerge.exe
  51. +6 −0 Tools/ILMerge.exe.config
  52. BIN  Tools/NuGet.exe
2  .gitignore
View
@@ -9,6 +9,8 @@
# Build results
[Dd]ebug/
[Rr]elease/
+Bins/
+packages/
*_i.c
*_p.c
*.ilk
7 Build.ps1
View
@@ -0,0 +1,7 @@
+clear
+
+$configuration = "Release"
+$specialRevision = "0"
+$currentPath = $myinvocation.mycommand.path | split-path -parent
+
+&"$env:windir\Microsoft.NET\Framework\v4.0.30319\msbuild" $currentPath\Build\Build.proj /p:Configuration="$configuration" /p:Revision="$specialRevision"
106 Build/Build.proj
View
@@ -0,0 +1,106 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Start" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildProjectDirectory)\Build.tasks" />
+ <UsingTask TaskName="ILMerge" AssemblyFile="$(MSBuildProjectDirectory)\ILMerge.MSBuild.Tasks.dll" />
+ <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
+ <PropertyGroup>
+ <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
+ <ProjectName>ConfArt</ProjectName>
+ <ProjectRoot>$(MSBuildProjectDirectory)\..</ProjectRoot>
+ <ProjectTest>$(ProjectRoot)\Test</ProjectTest>
+ <ProjectSrc>$(ProjectRoot)\Src</ProjectSrc>
+ <ProjectBinCore>$(ProjectSrc)\ArtOfNet.FluentConfiguration\bin\$(Configuration)</ProjectBinCore>
+ <DropDirectory>$(ProjectRoot)\Bins</DropDirectory>
+ <DropDirectoryAllAssemblies>$(DropDirectory)\AllAssemblies</DropDirectoryAllAssemblies>
+ <DropDirectoryMerged>$(DropDirectory)\Merged</DropDirectoryMerged>
+ <DropDirectoryMergedTemp>$(DropDirectory)\MergedTemp</DropDirectoryMergedTemp>
+ <DropDirectoryLog>$(DropDirectory)\Log</DropDirectoryLog>
+ <ILMergeExe>$(ProjectRoot)\Tools\ILMerge.exe</ILMergeExe>
+ <NugetExe>$(ProjectRoot)\Tools\nuget.exe</NugetExe>
+ <NugetManifest>$(ProjectRoot)\$(ProjectName).nuspec</NugetManifest>
+ <ILMergeFileFinalName>$(DropDirectoryMerged)\$(ProjectName).dll</ILMergeFileFinalName>
+ <ILMergeDirectory>$(DropDirectory)</ILMergeDirectory>
+ <ILMergeIgnoreFile>$(MSBuildProjectDirectory)\ilmerge.ignore.txt</ILMergeIgnoreFile>
+ <DotNet4ReferenceAssemblies>C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0</DotNet4ReferenceAssemblies>
+ <LocalPackagesFolder>E:\Sources\Packages\</LocalPackagesFolder>
+ <LegalFileSource>$(ProjectRoot)\Common\legal.txt</LegalFileSource>
+ </PropertyGroup>
+ <PropertyGroup>
+ <MajorVersion>1</MajorVersion>
+ <MinorVersion>1</MinorVersion>
+ <VersionStartYear>2011</VersionStartYear>
+ <BuildNumber>$([MSBuild]::Add(1, $([MSBuild]::Subtract($([System.DateTime]::Now.Year), $(VersionStartYear)))))$([System.DateTime]::Now.ToString("Md"))</BuildNumber>
+ <Revision Condition="'$(Revision)' == ''">$(BuildNumber)</Revision>
+ <Version>$(MajorVersion).$(MinorVersion).$(BuildNumber).$(Revision)</Version>
+ </PropertyGroup>
+ <ItemGroup>
+ <!-- add build number to common assembly file (used in all projects) -->
+ <RegexTransform Include="$(ProjectRoot)\Common\CommonAssemblyInfo.cs">
+ <Find>\d+\.\d+\.\d+\.\d+</Find>
+ <ReplaceWith>$(Version)</ReplaceWith>
+ </RegexTransform>
+ <!-- add build number to nuget manifest -->
+ <RegexTransform Include="$(NugetManifest)">
+ <Find>&lt;version&gt;\d+\.\d+\.\d+\.\d+&lt;/version&gt;</Find>
+ <ReplaceWith>&lt;version&gt;$(Version)&lt;/version&gt;</ReplaceWith>
+ </RegexTransform>
+ <LegalInsertTransform Include="$(ProjectRoot)\Src">
+ <LegalSource>$(LegalFileSource)</LegalSource>
+ </LegalInsertTransform>
+ </ItemGroup>
+
+ <Target Name="Start" DependsOnTargets="Intro;UpdateVsixVersion;Build;CreateDropDirectories;CopyAllFrameworkAssembliesToDrops;NugetPack">
+ </Target>
+
+ <!-- INFO : BUILD ALL Sources -->
+ <Target Name="Intro">
+ <Message Text="[Building solution with Version Number $(Version)]" />
+ </Target>
+
+ <Target Name="UpdateVsixVersion" Condition="'$(BuildNumber)' != ''">
+ <Message Text="Updating Common Assembly info with current build number ($(Version))" />
+ <RegexTransform Items="@(RegexTransform)" />
+ </Target>
+
+ <Target Name="UpdateLegalInfo" Condition="'$(LegalFileSource)' != ''">
+ <Message Text="Updating all cs files with legal information from file $(LegalFileSource)" />
+ <LegalInsertTransform Items="@(LegalInsertTransform)" />
+ </Target>
+
+ <Target Name="Build">
+ <Message Text="Building the Solution." />
+ <MSBuild Projects="$(ProjectRoot)\$(ProjectName).sln" Targets="Build" />
+ </Target>
+
+ <!-- INFO : Create,Merge,Copy Resulting binaries -->
+ <Target Name="CreateDropDirectories">
+ <Message Text="Making the output directories for the compiled output at '$(DropDirectory)'." />
+ <RemoveDir Directories="$(DropDirectory)" Condition="Exists('$(DropDirectory)')" ContinueOnError="True" />
+ <MakeDir Directories="$(DropDirectory)" Condition="!Exists('$(DropDirectory)')" />
+ <MakeDir Directories="$(DropDirectoryAllAssemblies)" Condition="!Exists('$(DropDirectoryAllAssemblies)')" />
+ <MakeDir Directories="$(DropDirectoryMerged)" Condition="!Exists('$(DropDirectoryMerged)')" />
+ <MakeDir Directories="$(DropDirectoryLog)" Condition="!Exists('$(DropDirectoryLog)')" />
+ <MakeDir Directories="$(DropDirectoryMergedTemp)" Condition="!Exists('$(DropDirectoryLog)')" />
+ </Target>
+
+ <Target Name="CopyAllFrameworkAssembliesToDrops">
+ <ItemGroup>
+ <ProjectBinCoreItems Include="$(ProjectBinCore)\*.dll" />
+ </ItemGroup>
+ <Message Text="Copying the Framework contracts output to $(DropDirectoryAllAssemblies)" />
+ <Copy ContinueOnError="false" SourceFiles="@(ProjectBinCoreItems)" DestinationFiles="@(ProjectBinCoreItems ->'$(DropDirectoryAllAssemblies)\%(RecursiveDir)%(Filename)%(Extension)')" />
+ </Target>
+
+
+
+
+ <Target Name="NugetPack">
+ <ItemGroup>
+ <compiledPackage Include="$(DropDirectory)\$(ProjectName).$(Version).nupkg" />
+ </ItemGroup>
+ <Message Text="Preparing a nuget package" />
+ <Exec Command="&quot;$(NugetExe)&quot; pack &quot;$(NugetManifest)&quot; -o &quot;$(DropDirectory)&quot;" />
+ <Message Text="pushing the nuget package to local repository" />
+ <Copy ContinueOnError="false" SourceFiles="@(compiledPackage)" DestinationFolder="$(LocalPackagesFolder)" />
+ </Target>
+</Project>
34 Build/Build.tasks
View
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Go" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <UsingTask TaskName="RegexTransform" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
+ <ParameterGroup>
+ <Items ParameterType="Microsoft.Build.Framework.ITaskItem[]" />
+ </ParameterGroup>
+ <Task>
+ <Using Namespace="System.IO" />
+ <Using Namespace="System.Text.RegularExpressions" />
+ <Using Namespace="Microsoft.Build.Framework" />
+ <Code Type="Fragment" Language="cs">
+ <![CDATA[
+ foreach(ITaskItem item in Items) {
+ string fileName = item.GetMetadata("FullPath");
+ string find = item.GetMetadata("Find");
+ string replaceWith = item.GetMetadata("ReplaceWith");
+
+ if(!File.Exists(fileName)) {
+ Log.LogError(null, null, null, null, 0, 0, 0, 0, String.Format("Could not find version file: {0}", fileName), new object[0]);
+ }
+ string content = File.ReadAllText(fileName);
+ File.WriteAllText(
+ fileName,
+ Regex.Replace(
+ content,
+ find,
+ replaceWith
+ )
+ );
+ }
+ ]]></Code>
+ </Task>
+ </UsingTask>
+ </Project>
BIN  Build/ILMerge.MSBuild.Tasks.dll
View
Binary file not shown
0  Build/ilmerge.ignore.txt
View
No changes.
21 Common/CommonAssemblyInfo.cs
View
@@ -0,0 +1,21 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 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: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("ArtOfNet")]
+[assembly: AssemblyProduct("ArtOfNet.FluentConfiguration")]
+[assembly: AssemblyCopyright("Copyright © ArtOfNet 2011")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+[assembly: ComVisible(false)]
+
+
+[assembly: Guid("813a0799-d4cc-4f4a-b060-f5e556f27679")]
+
+[assembly: AssemblyVersion("1.1.1613.0")]
+[assembly: AssemblyFileVersion("1.1.1613.0")]
21 ConfArt.nuspec
View
@@ -0,0 +1,21 @@
+<?xml version="1.0"?>
+<package xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <metadata xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
+ <id>ConfArt</id>
+ <version>1.1.1613.0</version>
+ <authors>ArtOfNet</authors>
+ <owners>ArtOfNet</owners>
+ <licenseUrl>http://www.ArtOfNet.com</licenseUrl>
+ <projectUrl>http://www.ArtOfNet.com/</projectUrl>
+ <requireLicenseAcceptance>false</requireLicenseAcceptance>
+ <description>Fluently helps you define configuration and mapping between objects</description>
+ <summary>This framework targets simple mapping using dynamics</summary>
+ <language>en-US</language>
+ <dependencies>
+ <dependency id="NLog" version="2.0.0.0" />
+ </dependencies>
+ </metadata>
+ <files>
+ <file src="Bins\AllAssemblies\ConfArt.dll" target="lib" />
+ </files>
+</package>
47 ConfArt.sln
View
@@ -0,0 +1,47 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConfArt", "Src\ArtOfNet.FluentConfiguration\ConfArt.csproj", "{6945FF16-B35F-487C-B35A-719A148C3163}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{47D220C7-ADD3-44C9-94C6-BF0276D978D3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluentConfigurationTests", "Tests\ArtOfNet.FluentConfiguration.Tests\FluentConfigurationTests.csproj", "{045A124F-1F94-4214-893F-DC8636F86CE4}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|Mixed Platforms = Debug|Mixed Platforms
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|Mixed Platforms = Release|Mixed Platforms
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Release|Any CPU.Build.0 = Release|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {6945FF16-B35F-487C-B35A-719A148C3163}.Release|x86.ActiveCfg = Release|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Release|Any CPU.Build.0 = Release|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {045A124F-1F94-4214-893F-DC8636F86CE4}.Release|x86.ActiveCfg = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {045A124F-1F94-4214-893F-DC8636F86CE4} = {47D220C7-ADD3-44C9-94C6-BF0276D978D3}
+ EndGlobalSection
+EndGlobal
3  Src/ArtOfNet.FluentConfiguration/ArtOfNet.FluentConfiguration.csproj.vs10x
View
@@ -0,0 +1,3 @@
+This file contains Alternate Data Streams, storing configuration information used by CodeSMART 10 and VS10X Extensions.
+
+PLEASE DO NOT DELETE.
81 Src/ArtOfNet.FluentConfiguration/ConfArt.csproj
View
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>8.0.30703</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{6945FF16-B35F-487C-B35A-719A148C3163}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>ConfArt</RootNamespace>
+ <AssemblyName>ConfArt</AssemblyName>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <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' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="NLog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\packages\NLog.2.0.0.0\lib\NET40\NLog.dll</HintPath>
+ </Reference>
+ <Reference Include="NLog.Extended">
+ <HintPath>..\..\packages\NLog.2.0.0.0\lib\NET40\NLog.Extended.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="ConfigurationMapper.cs" />
+ <Compile Include="Contracts\IConfigurationMapping.cs" />
+ <Compile Include="Contracts\IConfigurationMappingsBase.cs" />
+ <Compile Include="Contracts\IHideObjectMembers.cs" />
+ <Compile Include="Core\AssemblyHelper.cs" />
+ <Compile Include="Core\AutoConfigurationMapping.cs" />
+ <Compile Include="Core\ConfigurationMappingsBase.cs" />
+ <Compile Include="Core\ConfigurationMappingType.cs" />
+ <Compile Include="Core\ConvertibleBase.cs" />
+ <Compile Include="Core\DynamicConfigurationValues.cs" />
+ <Compile Include="Core\DynamicXml.cs" />
+ <Compile Include="Core\PropertySetterExpression.cs" />
+ <Compile Include="Core\ValueFactory.cs" />
+ <Compile Include="Exceptions\DynamicXmlParseException.cs" />
+ <Compile Include="Exceptions\InternalExceptionEnumeration.cs" />
+ <Compile Include="Exceptions\MapperInvocationException.cs" />
+ <Compile Include="Exceptions\NotAMappedTypeException.cs" />
+ <Compile Include="Extensions\PropertyInfoExtensions.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="packages.config" />
+ </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>
99 Src/ArtOfNet.FluentConfiguration/ConfigurationMapper.cs
View
@@ -0,0 +1,99 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ConfArt.Core;
+using ConfArt.Contracts;
+using System.Reflection;
+using ArtOfNet.ConfArt.Core;
+
+namespace ConfArt
+{
+ public static class ConfigurationMapper
+ {
+ private static Dictionary<Type, Type> _mappings = new Dictionary<Type, Type>();
+ private static Dictionary<Type, IConfigurationMapping> _mappers = new Dictionary<Type, IConfigurationMapping>();
+ private static Dictionary<Type, IEnumerable<string>> _automappings = new Dictionary<Type, IEnumerable<string>>();
+
+ public static void Define<T,M>() where T:class,new() where M:IConfigurationMappingsBase<T>
+ {
+ if (!_mappings.ContainsKey(typeof(T)))
+ {
+ _mappings.Add(typeof(T), typeof(M));
+ }
+ }
+
+ public static void Define(Type t, Type m)
+ {
+ if (!_mappings.ContainsKey(t))
+ {
+ _mappings.Add(t, m);
+ }
+ }
+
+ public static void Define(Type t, IEnumerable<string> values)
+ {
+ if (!_automappings.ContainsKey(t))
+ {
+ _automappings.Add(t, values);
+ }
+ }
+
+ public static bool HasMappingFor<T>()
+ {
+ bool result = _mappings.ContainsKey(typeof(T));
+ if (!result)
+ {
+ result = _automappings.ContainsKey(typeof(T));
+ }
+ return result;
+ }
+
+ public static IConfigurationMappingsBase<T> GetMapper<T>() where T:class,new()
+ {
+ Type mapperType;
+ _mappings.TryGetValue(typeof(T), out mapperType);
+
+ if (mapperType == null)
+ {
+ return null; //STEX
+ }
+
+ if (_mappers.ContainsKey(mapperType))
+ {
+ return (IConfigurationMappingsBase<T>)_mappers[mapperType];
+ }
+ else
+ {
+ return (IConfigurationMappingsBase<T>)Activator.CreateInstance(mapperType);
+ }
+ }
+
+ public static void AutoConfigure()
+ {
+ if (_mappings.Count > 0)
+ {
+ return;
+ }
+
+ var ti = AssemblyHelper.GetConfigurationMappings();
+
+ if (ti == null)
+ {
+ return;
+ }
+
+ var list = ti.ToList();
+
+ if (list.Count == 0)
+ {
+ return;
+ }
+
+ foreach (var mapping in list)
+ {
+ ConfigurationMapper.Define(mapping.Source, mapping.Target);
+ }
+ }
+ }
+}
12 Src/ArtOfNet.FluentConfiguration/Contracts/IConfigurationMapping.cs
View
@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ConfArt.Contracts
+{
+ public interface IConfigurationMapping
+ {
+ Type ConfiguredType { get; }
+ }
+}
15 Src/ArtOfNet.FluentConfiguration/Contracts/IConfigurationMappingsBase.cs
View
@@ -0,0 +1,15 @@
+using System;
+using ConfArt.Core;
+using System.Collections.Generic;
+
+namespace ConfArt.Contracts
+{
+ public interface IConfigurationMappingsBase<T> : IConfigurationMapping where T : class, new()
+ {
+ void Configure();
+ Dictionary<string, Action<T, object>> Settings { get; }
+ T Get(dynamic values);
+ T Get(System.Collections.Generic.Dictionary<string, object> values);
+ PropertySetterExpression<T> Map(System.Linq.Expressions.Expression<Func<T, object>> memberToSet);
+ }
+}
24 Src/ArtOfNet.FluentConfiguration/Contracts/IHideObjectMembers.cs
View
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.ComponentModel;
+
+namespace ConfArt.Contracts
+{
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public interface IHideObjectMembers
+ {
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ Type GetType();
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ int GetHashCode();
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ string ToString();
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ bool Equals(object obj);
+ }
+}
55 Src/ArtOfNet.FluentConfiguration/Core/AssemblyHelper.cs
View
@@ -0,0 +1,55 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+using ConfArt.Contracts;
+
+namespace ArtOfNet.ConfArt.Core
+{
+ public static class AssemblyHelper
+ {
+ public static IEnumerable<Assembly> GetUserLoadedAssemblies()
+ {
+ var assemblies = from a in AppDomain.CurrentDomain.GetAssemblies()
+ where !a.GlobalAssemblyCache
+ select a;
+
+ return assemblies;
+ }
+
+ public static IEnumerable<Tuple<Type,Type>> GetAllGenericTypesFromUserLoadedAssemblies()
+ {
+ var genericTypes = from assembly in GetUserLoadedAssemblies()
+ from type in assembly.GetTypes().AsQueryable()
+ from genericInterface in type.GetInterfaces().AsQueryable()
+ where genericInterface.IsGenericType
+ select new Tuple<Type,Type>(type,genericInterface);
+ return genericTypes;
+ }
+
+
+ public static IEnumerable<ConfigurationMappingType> GetConfigurationMappings()
+ {
+ var mappings = from typeTupple in GetAllGenericTypesFromUserLoadedAssemblies()
+ where typeTupple.Item2.GetGenericTypeDefinition() == typeof(IConfigurationMappingsBase<>)
+ && !typeTupple.Item1.IsAbstract
+ let target = typeTupple.Item1
+ let source = typeTupple.Item1.BaseType.GetGenericArguments().First()
+ select new ConfigurationMappingType(
+ source, target
+ );
+ return mappings;
+
+ //var ti = from t in calling.GetTypes().AsQueryable()
+ // from i in t.GetInterfaces()
+ // where i.IsGenericType
+ // let ib = i.GetGenericTypeDefinition()
+ // where ib == typeof(IConfigurationMappingsBase<>)
+ // let mapping = t
+ // let mapped = t.BaseType.GetGenericArguments().First()
+ // select new { souce = mapped, target = mapping };
+
+ }
+ }
+}
13 Src/ArtOfNet.FluentConfiguration/Core/AutoConfigurationMapping.cs
View
@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ConfArt.Core;
+
+namespace ArtOfNet.ConfArt.Core
+{
+ public class AutoConfigurationMapping<T> : ConfigurationMappingsBase<T> where T : class,new()
+ {
+
+ }
+}
24 Src/ArtOfNet.FluentConfiguration/Core/ConfigurationMappingType.cs
View
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ArtOfNet.ConfArt.Core
+{
+ public class ConfigurationMappingType
+ {
+ public Type Source { get; set; }
+ public Type Target { get; set; }
+
+ public ConfigurationMappingType(Type source, Type target)
+ {
+ Source = source;
+ Target = target;
+ }
+
+ public ConfigurationMappingType()
+ {
+
+ }
+ }
+}
90 Src/ArtOfNet.FluentConfiguration/Core/ConfigurationMappingsBase.cs
View
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Linq.Expressions;
+using ConfArt.Extensions;
+using ConfArt.Contracts;
+using NLog;
+
+namespace ConfArt.Core
+{
+ public abstract class ConfigurationMappingsBase<T> : IConfigurationMappingsBase<T> where T:class,new()
+ {
+ private Dictionary<string, Action<T, object>> _settings = new Dictionary<string, Action<T, object>>();
+ private static Logger _logger = LogManager.GetCurrentClassLogger();
+
+ public Dictionary<string, Action<T, object>> Settings
+ {
+ get
+ {
+ return _settings;
+ }
+ }
+ public virtual void Configure(){}
+
+ public Type ConfiguredType
+ {
+ get
+ {
+ return typeof(T);
+ }
+ }
+
+ public PropertySetterExpression<T> Map(Expression<Func<T, object>> memberToSet)
+ {
+ PropertySetterExpression<T> mapping = new PropertySetterExpression<T>(this, memberToSet);
+ mapping.UpdateSource = (s, a) =>
+ {
+ if (!_settings.ContainsKey(s))
+ {
+ _settings.Add(s, a);
+ }
+ };
+ return mapping;
+ }
+
+ public T Get(dynamic values)
+ {
+ this.Configure();
+ if (_settings.Count == 0)
+ {
+ return null;
+ }
+
+ T obj = Activator.CreateInstance<T>();
+
+ foreach (string key in _settings.Keys)
+ {
+ _settings[key](obj, values[key]);
+ }
+ return obj;
+ }
+
+ public T Get(Dictionary<string,object> values)
+ {
+
+ this.Configure();
+ if (_settings.Count == 0)
+ {
+ return null;
+ }
+
+ T obj = Activator.CreateInstance<T>();
+
+ foreach (string key in _settings.Keys)
+ {
+ try
+ {
+ _settings[key](obj, values[key]);
+ }
+ catch (Exception ex)
+ {
+ _logger.Warn("there is a problem with the value mapping", ex.Message);
+ }
+
+ }
+ return obj;
+ }
+ }
+}
148 Src/ArtOfNet.FluentConfiguration/Core/ConvertibleBase.cs
View
@@ -0,0 +1,148 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Dynamic;
+
+namespace ArtOfNet.ConfArt.Core
+{
+ public class DynamicConvertibleBase: DynamicObject, IConvertible
+ {
+ public virtual Func<string> GetValue { get; set; }
+
+ private string TryGetValue()
+ {
+ string result;
+ if (GetValue == null)
+ {
+ result = string.Empty; var x = new ExpandoObject();
+ }
+ else
+ {
+ try
+ {
+ result = GetValue();
+ }
+ catch
+ {
+ result = string.Empty;
+ }
+ }
+ return result;
+ }
+ #region IConvertible
+ public TypeCode GetTypeCode()
+ {
+ return TypeCode.String;
+ }
+
+ public bool ToBoolean(IFormatProvider provider)
+ {
+ bool outValue;
+ bool.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public byte ToByte(IFormatProvider provider)
+ {
+ byte outValue;
+ byte.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public char ToChar(IFormatProvider provider)
+ {
+ char outValue;
+ char.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public DateTime ToDateTime(IFormatProvider provider)
+ {
+ DateTime outValue;
+ DateTime.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public decimal ToDecimal(IFormatProvider provider)
+ {
+ decimal outValue;
+ decimal.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public double ToDouble(IFormatProvider provider)
+ {
+ double outValue;
+ double.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public short ToInt16(IFormatProvider provider)
+ {
+ Int16 outValue;
+ Int16.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public int ToInt32(IFormatProvider provider)
+ {
+ Int32 outValue;
+ Int32.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public long ToInt64(IFormatProvider provider)
+ {
+ Int64 outValue;
+ Int64.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public sbyte ToSByte(IFormatProvider provider)
+ {
+ sbyte outValue;
+ sbyte.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public float ToSingle(IFormatProvider provider)
+ {
+ float outValue;
+ float.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public string ToString(IFormatProvider provider)
+ {
+ return TryGetValue();
+ }
+
+ public object ToType(Type conversionType, IFormatProvider provider)
+ {
+ return (object)TryGetValue();
+ }
+
+ public ushort ToUInt16(IFormatProvider provider)
+ {
+ ushort outValue;
+ ushort.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public uint ToUInt32(IFormatProvider provider)
+ {
+ uint outValue;
+ uint.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+
+ public ulong ToUInt64(IFormatProvider provider)
+ {
+ ulong outValue;
+ ulong.TryParse(TryGetValue(), out outValue);
+ return outValue;
+ }
+ #endregion
+ }
+}
141 Src/ArtOfNet.FluentConfiguration/Core/DynamicConfigurationValues.cs
View
@@ -0,0 +1,141 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Dynamic;
+
+namespace ConfArt.Core
+{
+ public class DynamicConfigurationValues : DynamicObject
+ {
+ private Dictionary<string, object> _values = new Dictionary<string, object>();
+ private readonly object _syncRoot = new object();
+
+ private bool _emptyIfNull = false;
+
+ public DynamicConfigurationValues()
+ {
+
+ }
+
+ public DynamicConfigurationValues(bool emptyIfNull)
+ {
+ _emptyIfNull = emptyIfNull;
+ }
+
+
+ public override bool TryGetMember(GetMemberBinder binder, out object result)
+ {
+ bool resultOperation = false;
+ result = null;
+ if (_values.ContainsKey(binder.Name))
+ {
+ result = _values[binder.Name];
+ resultOperation = true;
+ }
+ else
+ {
+ if (_emptyIfNull)
+ {
+ result = string.Empty;
+ resultOperation = true;
+ }
+ }
+ return resultOperation;
+ }
+
+ public override bool TrySetMember(SetMemberBinder binder, object value)
+ {
+ bool resultOperation = false;
+ lock (_syncRoot)
+ {
+ if (!_values.ContainsKey(binder.Name))
+ {
+ _values.Add(binder.Name, value);
+ resultOperation = true;
+ }
+ else
+ {
+ _values[binder.Name] = value;
+ resultOperation = true;
+ }
+ }
+
+ return resultOperation;
+ }
+
+ public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
+ {
+ if (indexes.Length == 0)
+ {
+ result = null;
+ return false;
+ }
+
+ string key = indexes[0] as string;
+ if (string.IsNullOrEmpty(key))
+ {
+ result = null;
+ return false;
+ }
+
+ return _values.TryGetValue(key, out result);
+ }
+
+ public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
+ {
+ if (indexes.Length == 0)
+ {
+ return false;
+ }
+ string key = indexes[0] as string;
+ if (string.IsNullOrEmpty(key))
+ {
+ return false;
+ }
+ lock (_syncRoot)
+ {
+ if (_values.ContainsKey(key))
+ {
+ _values[key] = value;
+ }
+ else
+ {
+ _values.Add(key, value);
+ }
+ }
+ return true;
+ }
+
+ public override IEnumerable<string> GetDynamicMemberNames()
+ {
+ return _values.Keys;
+ }
+
+ public IEnumerable<string> Keys
+ {
+ get
+ {
+ return _values.Keys;
+ }
+ }
+
+ public bool HasProperty(string key)
+ {
+ return _values.Keys.Contains(key);
+ }
+
+ public override string ToString()
+ {
+ string result = string.Empty;
+ string pattern = "{0} : {1}" + Environment.NewLine;
+
+ foreach (var item in _values)
+ {
+ result += string.Format(pattern, item.Key, item.Value);
+ }
+
+ return result;
+ }
+ }
+}
264 Src/ArtOfNet.FluentConfiguration/Core/DynamicXml.cs
View
@@ -0,0 +1,264 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Dynamic;
+using ConfArt.Core;
+using System.Xml.Linq;
+using ArtOfNet.ConfArt.Exceptions;
+using System.Reflection;
+
+namespace ArtOfNet.ConfArt.Core
+{
+ public class DynamicXmlElement : DynamicConvertibleBase
+ {
+ private XElement _InternalNode;
+ private readonly object _syncRoot = new object();
+
+ public DynamicXmlElement(XElement node)
+ {
+ this._InternalNode = node;
+ }
+
+ public DynamicXmlElement()
+ {
+ }
+
+ public DynamicXmlElement(string source)
+ {
+ try
+ {
+ if (source.Contains("<"))
+ {
+ this._InternalNode = XElement.Parse(source);
+ }
+ else
+ {
+ this._InternalNode = new XElement(source);
+ }
+ }
+ catch (Exception inner)
+ {
+ DynamicXmlParseException ex = new DynamicXmlParseException("Error while loading source xml in a DynamicXmlElement constructor", inner);
+ ex.Data.Add("DynamicXmlElement.Contructor.source", source);
+ throw ex;
+ }
+ }
+
+ private bool TrySetXmlMember(string name, object value)
+ {
+ XElement setNode = _InternalNode.Element(name);
+ if (setNode != null)
+ setNode.SetValue(value);
+ else
+ {
+ if (value.GetType() == typeof(DynamicXmlElement))
+ {
+ _InternalNode.Add(new XElement(name));
+ }
+ else
+ {
+ if (value.GetType() == typeof(XElement) || value.GetType() == typeof(XAttribute))
+ {
+ _InternalNode.Add(value);
+ }
+ else
+ {
+ _InternalNode.Add(new XElement(name, value));
+ }
+ }
+
+ }
+ return true;
+ }
+
+ public override bool TrySetMember(
+ SetMemberBinder binder, object value)
+ {
+ return TrySetXmlMember(binder.Name, value);
+ }
+
+ private bool TryGetXmlMember(string name, out object result)
+ {
+ //child name should map to one or many elements, so let's use a list by default
+ IEnumerable<XElement> nodes = _InternalNode.Elements(name);
+
+
+ //if something found it may be a _InternalNode or a list of child nodes
+ if (nodes != null && nodes.Count() > 0)
+ {
+ if (nodes.Count() == 1)
+ {
+ XElement current = nodes.First();
+ if (current.HasElements)
+ {
+ List<string> list = new List<string>(nodes.Elements().Select(x => x.Value));
+ result = list;
+ }
+ else
+ {
+ result = new DynamicXmlElement(nodes.First());
+ }
+
+ }
+ else
+ {
+ List<DynamicXmlElement> list = new List<DynamicXmlElement>(nodes.Select(x => new DynamicXmlElement(x)));
+ result = list;
+ }
+ return true;
+ }
+ //else it should be an attribute name
+ else
+ {
+
+ IEnumerable<XAttribute> getAttrib = _InternalNode.Attributes(name);
+ //finally try to see if the call is made to a member of XElement
+ if (getAttrib != null && getAttrib.Count() > 0)
+ {
+ //if it matches at least one attribute, return directly an XAttribue, as you don't want to
+ //map it as a dynamic node (after all, we can view it as a terminal leaf in a dynamic tree)
+ if (getAttrib.Count() > 1)
+ {
+ result = getAttrib;
+ }
+ else
+ {
+ result = getAttrib.First().Value;
+ }
+ return true;
+ }
+ else
+ {
+ Type xet = typeof(XElement);
+ MemberInfo[] members = xet.GetMember(name);
+ if (members != null && members.Count() > 0)
+ {
+ MemberInfo one = members[0];
+ if (one is PropertyInfo)
+ {
+ var property = (PropertyInfo)one;
+ result = property.GetValue(_InternalNode, null);
+ return true;
+ }
+ else if (one is MethodInfo)
+ {
+ var method = (MethodInfo)one;
+ result = method.Invoke(_InternalNode, null);
+ return true;
+ }
+ result = new DynamicXmlElement(new XElement(name));
+ return true;
+ }
+ else
+ {
+ result = new DynamicXmlElement(new XElement(name));
+ return true;
+ }
+ }
+ }
+ }
+
+ public override bool TryGetMember(
+ GetMemberBinder binder, out object result)
+ {
+ return TryGetXmlMember(binder.Name, out result);
+ }
+
+ public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
+ {
+ if (indexes.Length == 0)
+ {
+ result = null;
+ return false;
+ }
+
+ string key = indexes[0] as string;
+ if (string.IsNullOrEmpty(key))
+ {
+ result = null;
+ return false;
+ }
+
+ return TryGetXmlMember(key, out result);
+ }
+
+ public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
+ {
+ if (indexes.Length == 0)
+ {
+ return false;
+ }
+ string key = indexes[0] as string;
+ if (string.IsNullOrEmpty(key))
+ {
+ return false;
+ }
+ lock (_syncRoot)
+ {
+ XElement child = _InternalNode.Element(key);
+
+ if (child != null)
+ {
+ child = value as XElement;
+ }
+ else
+ {
+ _InternalNode.Add(value);
+ }
+ }
+ return true;
+ }
+
+ public override IEnumerable<string> GetDynamicMemberNames()
+ {
+ return Keys;
+ }
+
+ public IEnumerable<string> Keys
+ {
+ get
+ {
+ foreach (string childNode in _InternalNode.Elements().Select(x => x.Name.LocalName))
+ {
+ yield return childNode;
+ }
+ foreach (string childNode in _InternalNode.Attributes().Select(x => x.Name.LocalName))
+ {
+ yield return childNode;
+ }
+ }
+ }
+
+ public Dictionary<string, object> ToDictionary()
+ {
+ Dictionary<string, object> result = new Dictionary<string, object>();
+
+ foreach (XElement elem in _InternalNode.Elements())
+ {
+ result.Add(
+ elem.Name.ToString(), (object)elem.Value);
+ }
+ foreach (XAttribute elem in _InternalNode.Attributes())
+ {
+ result.Add(
+ elem.Name.ToString(), (elem.Value));
+ }
+ return result;
+ }
+
+ public object ToObject()
+ {
+ return (object)ToDictionary();
+
+ }
+
+ public override string ToString()
+ {
+ return _InternalNode.Value;
+ }
+
+
+
+ }
+}
65 Src/ArtOfNet.FluentConfiguration/Core/PropertySetterExpression.cs
View
@@ -0,0 +1,65 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Linq.Expressions;
+using System.Reflection;
+using ConfArt.Extensions;
+using ConfArt.Contracts;
+
+namespace ConfArt.Core
+{
+ public class PropertySetterExpression<T> where T:class,new()
+ {
+ private Action<T, object> _setter;
+ private Expression<Func<T, object>> _setterExpression;
+ private ConfigurationMappingsBase<T> _source;
+
+ public Action<string, Action<T, object>> UpdateSource { get; set; }
+
+ public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
+ {
+ _source = source;
+ _setterExpression = setterExpression;
+ }
+
+
+ public void With(string field)
+ {
+ Expression expBoxy = _setterExpression.Body;
+
+ if (expBoxy.NodeType == ExpressionType.Convert)
+ {
+ var convertExp = (UnaryExpression)expBoxy;
+ var operand = (MemberExpression)convertExp.Operand;
+
+ if (operand.Member is PropertyInfo)
+ {
+ PropertyInfo pi = typeof(T).GetProperty(operand.Member.Name);
+ _setter = pi.GetValueSetter<T>();
+ }
+
+ }
+ else if (expBoxy.NodeType == ExpressionType.MemberAccess )
+ {
+ var operand = (MemberExpression)expBoxy;
+
+ if (operand.Member is PropertyInfo)
+ {
+ PropertyInfo pi = typeof(T).GetProperty(operand.Member.Name);
+ _setter = pi.GetValueSetter<T>();
+ }
+
+ }
+ else
+ {
+ throw new InvalidOperationException("Expression is not valid to set a property, should be something like x=>x.Name");
+ }
+
+ if (_source != null && _setter != null && UpdateSource != null)
+ {
+ UpdateSource(field,_setter);
+ }
+ }
+ }
+}
175 Src/ArtOfNet.FluentConfiguration/Core/ValueFactory.cs
View
@@ -0,0 +1,175 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ConfArt.Contracts;
+using ConfArt.Exceptions;
+using System.Reflection;
+using ConfArt.Extensions;
+using System.Collections;
+using NLog;
+
+namespace ConfArt.Core
+{
+ /// <summary>
+ /// A factory to help the creation of objects instances based on
+ /// dynamic values and convention mappings
+ /// </summary>
+ public static class ValueFactory
+ {
+ private static bool _initialisized = false;
+ private static bool _automap = true;
+ private static Logger _logger = LogManager.GetCurrentClassLogger();
+
+ public static bool Initialized
+ {
+ get
+ {
+ return _initialisized;
+ }
+ }
+
+ public static bool Automap
+ {
+ get
+ {
+ return _automap;
+ }
+ set
+ {
+ _automap = value;
+ }
+ }
+
+ /// <summary>
+ /// The static constructor auto loads the default configuration
+ /// by discovery
+ /// </summary>
+ static ValueFactory()
+ {
+ ConfigurationMapper.AutoConfigure();
+ _initialisized = true;
+ }
+
+ /// <summary>
+ /// Try to get an instance of type T based on the dynamic object
+ /// values and the IConfigurationMappingBase instance that defines
+ /// the mapping between a T object and a dynamic instance
+ /// </summary>
+ /// <typeparam name="T">the type of the object to construct and fill</typeparam>
+ /// <param name="values">a dynamic object with the values to fill</param>
+ /// <returns></returns>
+ public static T TryGet<T>(dynamic values) where T:class,new()
+ {
+ if (!ConfigurationMapper.HasMappingFor<T>())
+ {
+ if (Automap)
+ {
+ return TryGetWithoutMapping<T>(values);
+ }
+ else
+ {
+ _logger.Warn("Type {0} is not mapped in the configuration", typeof(T));
+ //return new T();
+ throw new NotAMappedTypeException();
+ }
+ }
+
+ T result = default(T);
+
+ try
+ {
+ IConfigurationMappingsBase<T> mapper = ConfigurationMapper.GetMapper<T>();
+ result = mapper.Get(values);
+ }
+ catch (Exception ex)
+ {
+ _logger.Error(ex.Message);
+ throw new MapperInvocationException();
+ }
+ return result;
+ }
+
+ private static T TryGetWithoutMapping<T>(dynamic values) where T : class,new()
+ {
+ Type t = typeof(T);
+
+ T obj = Activator.CreateInstance<T>();
+
+ var properties = from p in t.GetProperties()
+ where p.CanWrite
+ select p;
+
+ foreach (PropertyInfo pi in properties.AsQueryable())
+ {
+ var set = pi.GetValueSetter<T>();
+
+ IEnumerable<string> names = values.Keys;
+
+ string key = (from n in names
+ where n.ToLower() == pi.Name.ToLower()
+ select n).FirstOrDefault();
+
+ if(!string.IsNullOrEmpty(key))
+ {
+ Type methodTargetType = pi.PropertyType;
+ object typedObject = null;
+ if (IsEnumerable(methodTargetType))
+ {
+ typedObject = (IEnumerable)values[key];
+ //Type[] genericArguments = methodTargetType.GetGenericArguments();
+ //Type defaultEnumeratedType = null;
+ //if (genericArguments != null && genericArguments.Length > 0)
+ //{
+ // defaultEnumeratedType = genericArguments[0];
+ // var listOfType = typeof(List<>).MakeGenericType(defaultEnumeratedType);
+
+ //}
+ }
+ else
+ {
+ typedObject = Convert.ChangeType(values[key], methodTargetType);
+ }
+
+ set(obj, typedObject);
+ }
+
+ }
+
+
+ return obj;
+ }
+
+ private static bool IsEnumerable(Type source)
+ {
+ if (!IsValidTypeForEnumeration(source))
+ {
+ return false;
+ }
+
+ IEnumerable<Type> list = source.GetInterfaces().Where(t => t.Name == "IEnumerable");
+ if (list == null)
+ {
+ return false;
+ }
+ if (list.Count() == 1)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ private static bool IsValidTypeForEnumeration(Type source)
+ {
+ if (source == typeof(string))
+ {
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
39 Src/ArtOfNet.FluentConfiguration/Exceptions/DynamicXmlParseException.cs
View
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ArtOfNet.ConfArt.Exceptions
+{
+ public class DynamicXmlParseException: Exception
+ {
+ public DynamicXmlParseException(Exception innerException)
+ : base(ConfArtException.DynamicXmlParse.ToString(),innerException)
+ {
+ }
+ public DynamicXmlParseException(string message,Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ public DynamicXmlParseException(string message)
+ : base(message)
+ {
+ }
+ public ConfArtException TypeException
+ {
+ get
+ {
+ return ConfArtException.DynamicXmlParse;
+ }
+ }
+
+ public int TypeExceptionId
+ {
+ get
+ {
+ return (int)TypeException;
+ }
+ }
+ }
+}
8 Src/ArtOfNet.FluentConfiguration/Exceptions/InternalExceptionEnumeration.cs
View
@@ -0,0 +1,8 @@
+public enum ConfArtException
+{
+ NotAMappedTypeException = 100,
+ ConfiguredMappingIsNotValid = 200,
+ MappedExpressionsAreNotValid = 300,
+ MappedValuesAreNotValid = 400,
+ DynamicXmlParse = 500
+}
11 Src/ArtOfNet.FluentConfiguration/Exceptions/MapperInvocationException.cs
View
@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ConfArt.Exceptions
+{
+ public class MapperInvocationException: Exception
+ {
+ }
+}
26 Src/ArtOfNet.FluentConfiguration/Exceptions/NotAMappedTypeException.cs
View
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ConfArt.Exceptions
+{
+ public class NotAMappedTypeException: Exception
+ {
+ public ConfArtException TypeException
+ {
+ get
+ {
+ return ConfArtException.NotAMappedTypeException;
+ }
+ }
+
+ public int TypeExceptionId
+ {
+ get
+ {
+ return (int)TypeException;
+ }
+ }
+ }
+}
54 Src/ArtOfNet.FluentConfiguration/Extensions/PropertyInfoExtensions.cs
View
@@ -0,0 +1,54 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Reflection;
+using System.Linq.Expressions;
+
+namespace ConfArt.Extensions
+{
+ public static class PropertyInfoExtensions
+ {
+ /// <summary>
+ /// Get an action delegate to get a property of an object T
+ /// </summary>
+ /// <typeparam name="T">Object type</typeparam>
+ /// <param name="propertyInfo">the property to bind getter method</param>
+ /// <returns>the getter delegate</returns>
+ public static Func<T, object> GetValueGetter<T>(this PropertyInfo propertyInfo)
+ {
+ if (typeof(T) != propertyInfo.DeclaringType)
+ {
+ throw new ArgumentException();
+ }
+ ParameterExpression instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
+ MemberExpression property = Expression.Property(instance, propertyInfo);
+ UnaryExpression convert = Expression.TypeAs(property, typeof(object));
+ return (Func<T, object>)Expression.Lambda(convert, instance).Compile();
+
+ }
+
+ /// <summary>
+ /// Get an action delegate to set a property of an object T
+ /// </summary>
+ /// <typeparam name="T">Object type</typeparam>
+ /// <param name="propertyInfo">the property to bind setter method</param>
+ /// <returns>the setter delegate</returns>
+ public static Action<T, object> GetValueSetter<T>(this PropertyInfo propertyInfo)
+ {
+ if (typeof(T) != propertyInfo.DeclaringType)
+ {
+ throw new ArgumentException();
+
+ }
+ var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
+ var argument = Expression.Parameter(typeof(object), "a");
+ var setterCall = Expression.Call(
+ instance,
+ propertyInfo.GetSetMethod(),
+ Expression.Convert(argument, propertyInfo.PropertyType));
+ return (Action<T, object>)Expression.Lambda(setterCall, instance, argument).Compile();
+
+ }
+ }
+}
36 Src/ArtOfNet.FluentConfiguration/Properties/AssemblyInfo.cs
View
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 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("ArtOfNet.ConfArt")]
+[assembly: AssemblyDescription("Fluent configuration library based on conversion between flat files and dynamics")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("ArtOfNet.ConfArt")]
+[assembly: AssemblyCopyright("Copyright © ArtOfNet 2010-2012")]
+[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)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("4d0f77f7-9a24-4eed-bee8-d43088f2abda")]
+
+// 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")]
4 Src/ArtOfNet.FluentConfiguration/packages.config
View
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="NLog" version="2.0.0.0" />
+</packages>
6 Tests/ArtOfNet.FluentConfiguration.Tests/App.config
View
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+ <appSettings>
+ <add key="test" value="hello"/>
+ </appSettings>
+</configuration>
59 Tests/ArtOfNet.FluentConfiguration.Tests/AssemblyHelperTests.Cs
View
@@ -0,0 +1,59 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+using ArtOfNet.ConfArt.Core;
+using ConfArt.Contracts;
+
+namespace ConfArtTests
+{
+ [TestFixture]
+ public class AssemblyHelperTests: TestFixtureBase
+ {
+ [Test]
+ public void VerifyUserLoadedAssemblies()
+ {
+ var assemblies = AssemblyHelper.GetUserLoadedAssemblies();
+ var names = from assembly in assemblies
+ select assembly.GetName().Name;
+
+ Log(names);
+
+ Assert.Greater(assemblies.Count(), 0);
+ //the current test assembly should be loaded
+ Assert.Contains("ConfArtTests", names.ToList());
+ //the assembly to test should also be correctly loaded
+ Assert.Contains("ArtOfNet.ConfArt", names.ToList());
+ }
+
+ [Test]
+ public void VerifyIfCanGetConfigurationFromUserLoadedAssemblies()
+ {
+ IEnumerable<Tuple<Type, Type>> loaded = AssemblyHelper.GetAllGenericTypesFromUserLoadedAssemblies();
+ var interfaces = from t in loaded
+ select t.Item2.Name;
+ Log(loaded);
+ Assert.DoesNotThrow(() => { loaded.Count(); },"Should not throw an error when counting the loaded user assemblies");
+ Assert.Contains(typeof(IConfigurationMappingsBase<>).Name, interfaces.ToList(),"you should have loaded the IConfigurationMappingsBase interface");
+ }
+
+ [Test]
+ public void VerifyIfCanGetConfigurationMappings()
+ {
+ IEnumerable<ConfigurationMappingType> loaded = AssemblyHelper.GetConfigurationMappings();
+ var sources = from t in loaded
+ select t.Source.Name;
+ var targets = from t in loaded
+ select t.Target.Name;
+
+ Log(sources,"Sources:");
+ Log(targets, "Targets:");
+
+ Assert.DoesNotThrow(() => { loaded.Count(); }, "Should not throw an error when counting the loaded user assemblies");
+ Assert.Contains("User", sources.ToList(),"Loaded types should contains the 'User' class");
+ Assert.Contains("UserMap", targets.ToList(), "Loaded types shoudl contains the 'UserMap' class used to define 'User' class mappings");
+ }
+
+ }
+}
100 Tests/ArtOfNet.FluentConfiguration.Tests/DynamicXmlTests.cs
View
@@ -0,0 +1,100 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+using ArtOfNet.ConfArt.Core;
+using System.Diagnostics;
+using System.Web.Routing;
+
+namespace ConfArtTests
+{
+ [TestFixture]
+ public class DynamicXmlTests: TestFixtureBase
+ {
+ public DynamicXmlTests()
+ {
+
+ }
+
+ [Test]
+ public void ShouldLoadDynamicFromXmlString()
+ {
+ string xmlString = @"<Contacts><User name=""user1""/><User name=""user2""/></Contacts>";
+ dynamic xml = new DynamicXmlElement(xmlString);
+
+ dynamic users = xml.User;
+
+ Assert.IsNotNull(users);
+ Assert.IsTrue(users.Count == 2);
+ foreach (dynamic user in users)
+ {
+ Assert.IsNotNull(user.name);
+ }
+ string user1 = users[0].name;
+ Assert.AreEqual(user1, "user1");
+
+ string user2 = users[1].name;
+ Assert.AreEqual(user2, "user2");
+
+ }
+
+ [Test]
+ public void ShouldUseDynamicXmlAsDynamicModel()
+ {
+ string xmlString = @"<Model name=""Rui""><site>ArtOfNet</site><child name=""Thaïs""/><child name=""Léandre"" /></Model>";
+ dynamic model = new DynamicXmlElement(xmlString);
+
+ Assert.AreEqual(model.name,"Rui");
+ Assert.AreEqual(model.child.Count,2);
+ foreach (dynamic item in model.child)
+ {
+ Assert.IsNotNull(item.name);
+ }
+ Assert.AreEqual(model.child[0].name,"Thaïs");
+ Assert.AreEqual(model.child[1].name, "Léandre");
+ }
+
+ [Test]
+ public void ShouldGetValuesFromDynamicXmlRoute()
+ {
+ string xmlstring = @"
+ <add routeName=""default"" path=""{controller}/{action}"">
+ <defaultValues controller=""Home"" action=""Index""/>
+ </add>";
+ dynamic route = new DynamicXmlElement(xmlstring);
+
+ //Assert.AreEqual(route.Name, "add");
+ Assert.AreEqual(route.routeName, "default");
+ Assert.AreEqual(route.path, "{controller}/{action}");
+
+ dynamic defaults = route.defaultValues;
+
+ Assert.AreEqual(defaults.controller,"Home");
+ var anon = new { controller = "Home", action = "Index" };
+ Assert.AreEqual(defaults.controller, anon.controller);
+
+ Dictionary<string, object> dico = new Dictionary<string, object>();
+ dico.Add("controller","Home");
+ dico.Add("action", "About");
+
+ }
+
+ [Test]
+ public void ShouldNotExplodeWithNonExistingKey()
+ {
+ string xmlstring = @"
+ <add routeName=""default"" path=""{controller}/{action}"">
+ <defaultValues controller=""Home"" action=""Index""/>
+ </add>";
+ dynamic route = new DynamicXmlElement(xmlstring);
+
+ Assert.DoesNotThrow(
+ () =>
+ {
+ var notExistingNode = route.constraints;
+ });
+
+ }
+ }
+}
87 Tests/ArtOfNet.FluentConfiguration.Tests/FluentConfigurationTests.csproj
View
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>8.0.30703</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{045A124F-1F94-4214-893F-DC8636F86CE4}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>FluentConfigurationTests</RootNamespace>
+ <AssemblyName>FluentConfigurationTests</AssemblyName>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <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' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="nunit.framework, Version=2.5.7.10213, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\packages\NUnit.2.5.7.10213\lib\nunit.framework.dll</HintPath>
+ </Reference>
+ <Reference Include="nunit.mocks">
+ <HintPath>..\..\packages\NUnit.2.5.7.10213\lib\nunit.mocks.dll</HintPath>
+ </Reference>
+ <Reference Include="pnunit.framework">
+ <HintPath>..\..\packages\NUnit.2.5.7.10213\lib\pnunit.framework.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Web" />
+ <Reference Include="System.Web.Abstractions" />
+ <Reference Include="System.Web.Extensions" />
+ <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
+ <Reference Include="System.Web.Routing" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="AssemblyHelperTests.Cs" />
+ <Compile Include="DynamicXmlTests.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="SampleData\Contact.cs" />
+ <Compile Include="SampleData\User.cs" />
+ <Compile Include="SampleData\UserHelper.cs" />
+ <Compile Include="SampleData\UserMap.cs" />
+ <Compile Include="ScenarioTest.cs" />
+ <Compile Include="TestFixtureBase.cs" />
+ <Compile Include="ValueFactoryTests.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\Src\ArtOfNet.FluentConfiguration\ConfArt.csproj">
+ <Project>{6945FF16-B35F-487C-B35A-719A148C3163}</Project>
+ <Name>ConfArt</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="App.config" />
+ <None Include="packages.config" />
+ </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>
3  Tests/ArtOfNet.FluentConfiguration.Tests/FluentConfigurationTests.csproj.vs10x
View
@@ -0,0 +1,3 @@
+This file contains Alternate Data Streams, storing configuration information used by CodeSMART 10 and VS10X Extensions.
+
+PLEASE DO NOT DELETE.
36 Tests/ArtOfNet.FluentConfiguration.Tests/Properties/AssemblyInfo.cs
View
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 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("ConfArtTests")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("ConfArtTests")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
+[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)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("0a941d5c-7bba-428c-a3de-d7aec9083f0a")]
+
+// 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")]
36 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/Contact.cs
View
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ConfArtTests.SampleData
+{
+ public class Contact
+ {
+ public int Id { get; set; }
+ public string Name { get; set; }
+ public string Company { get; set; }
+ public string Phone { get; set; }
+ public string Mail { get; set; }
+ public List<string> Cities { get; set; }
+
+ public Contact()
+ {
+ Cities = new List<string>();
+ }
+ public override int GetHashCode()
+ {
+ return base.GetHashCode();
+ }
+ public override bool Equals(object obj)
+ {
+ Contact compared = (Contact)obj;
+ if (compared == null)
+ {
+ return false;
+ }
+ return
+ (Id == compared.Id) && (Name == compared.Name) && (Company == compared.Company);
+ }
+ }
+}
19 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/User.cs
View
@@ -0,0 +1,19 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ConfArtTests.SampleData
+{
+ public class User
+ {
+ public int Id { get; set; }
+ public string Name { get; set; }
+ public DateTime Birth { get; set; }
+
+ public override string ToString()
+ {
+ return string.Format("Id: {0},Name: {1},Birth: {2}", Id, Name, Birth);
+ }
+ }
+}
30 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/UserHelper.cs
View
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ConfArtTests.SampleData
+{
+ public static class UserHelper
+ {
+ public static User GetUserOne()
+ {
+ User user = new User();
+ user.Id = 1;
+ user.Name = "TheOne";
+ user.Birth = DateTime.Now.AddMonths(-1000);
+ return user;
+ }
+
+ public static User GetUserRui()
+ {
+ User user = new User();
+ user.Id = 100;
+ user.Name = "Rui";
+ DateTime birth;
+ DateTime.TryParse("1975/04/24", out birth);
+ user.Birth = birth;
+ return user;
+ }
+ }
+}
18 Tests/ArtOfNet.FluentConfiguration.Tests/SampleData/UserMap.cs
View
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ConfArt.Core;
+
+namespace ConfArtTests.SampleData
+{
+ public class UserMap: ConfigurationMappingsBase<User>
+ {
+ public UserMap()
+ {
+ Map(u => u.Name).With("test_name");
+ Map(u => u.Id).With("test_id");
+ Map(u => u.Birth).With("test_birth");
+ }
+ }
+}
162 Tests/ArtOfNet.FluentConfiguration.Tests/ScenarioTest.cs
View
@@ -0,0 +1,162 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+using ConfArtTests.SampleData;
+using ConfArt.Core;
+using System.Threading;
+using ArtOfNet.ConfArt.Core;
+
+namespace ConfArtTests
+{
+ [TestFixture]
+ public class ScenarioTest
+ {
+ [SetUp]
+ public void Setup()
+ {
+
+ }
+ [Test]
+ public void VerifyTestContext()
+ {
+ }
+
+ public void ThisMethodIsNotATest()
+ {
+ Console.WriteLine("ThisMethodIsNotATest");
+ }
+
+ [Test]
+ public void ShouldGetNotNullInstanceOfMappedObject()
+ {
+ Dictionary<string, object> dv = new Dictionary<string, object>();
+
+ User actual = ValueFactory.TryGet<User>(dv);
+ Assert.IsNotNull(actual);
+ }
+
+ [Test]
+ public void ShouldGetCorrectInstanceOfMappedObject()
+ {
+ Dictionary<string, object> dv = new Dictionary<string, object>();
+
+ dv.Add("test_name", "Rui");
+ dv.Add("test_id", 100);
+ dv.Add("test_birth", DateTime.Parse("1975/04/24"));
+
+ User actual = ValueFactory.TryGet<User>(dv);
+
+ User expected = new User();
+ expected.Name = "Rui";
+ expected.Id = 100;
+ expected.Birth = DateTime.Parse("1975/04/24");
+
+ Assert.AreEqual(expected.Birth, actual.Birth);
+ Assert.AreEqual(expected.Id, actual.Id);
+ Assert.AreEqual(expected.Name, actual.Name);
+ }
+ [Test]
+ public void ShouldGetValidInstanceOfMappedObjectFromDynamicValue()
+ {
+ dynamic dv = new DynamicConfigurationValues();
+ dv.test_name = "Rui";
+ dv.test_id = 100;
+ dv.test_birth = DateTime.Parse("1975/04/24");
+
+ User actual = ValueFactory.TryGet<User>(dv);
+ User expected = UserHelper.GetUserRui();
+ Assert.AreEqual(actual.ToString(), expected.ToString());
+ }
+
+ [Test]
+ public void ShouldGetValidInstanceOfMappedObjectFromDictionary()
+ {
+ Dictionary<string, object> dv = new Dictionary<string, object>();
+
+ dv.Add("test_name", "Rui");
+ dv.Add("test_id", 100);
+ dv.Add("test_birth", DateTime.Parse("1975/04/24"));
+
+ User actual = ValueFactory.TryGet<User>(dv);
+ User expected = UserHelper.GetUserRui();
+
+ Assert.AreEqual(actual.ToString(), expected.ToString());
+ }
+
+ [Test]
+ public void ShouldGetValidInstanceEvenIfNotAllMembersMatching()
+ {
+ Dictionary<string, object> dv = new Dictionary<string, object>();
+
+ dv.Add("test_name", "Rui");
+ dv.Add("test_id", 100);
+ dv.Add("test_xxx", DateTime.Parse("1975/04/24"));
+
+ User actual = ValueFactory.TryGet<User>(dv);
+ User expected = UserHelper.GetUserRui();
+ //set birth date of expected to 0 to simulate a non-matching element:
+ expected.Birth = new DateTime();
+
+ Assert.AreEqual(actual.ToString(), expected.ToString());
+ }
+
+ [Test(Description="With auto mapping feature, it should try to fill as best as possible the activated instance")]
+ public void ShouldGetAValueBasedOnMemberNamesWithoutMapping()
+ {
+ dynamic dv = new DynamicConfigurationValues();
+ dv.name = "Rui";
+ dv.id = 111;
+
+ Contact expected = new Contact();
+ expected.Name = "Rui";
+ expected.Id = 111;
+
+ Contact actual = ValueFactory.TryGet<Contact>(dv);
+ Assert.AreEqual(actual, expected);
+ }
+
+ [Test(Description="Mapping a an xml string to a real object")]
+ public void ShouldMapADynamicXmlObjectToARealImplementation()
+ {
+ string xmlstring = @"
+ <Contact Name=""Rui"" Id=""111"" />";
+ dynamic contactDynamic = new DynamicXmlElement(xmlstring);
+
+
+ Contact expected = new Contact();
+ expected.Name = "Rui";
+ expected.Id = 111;
+
+ Contact actual = ValueFactory.TryGet<Contact>(contactDynamic);
+ Assert.AreEqual(actual, expected);
+ }
+
+ [Test(Description = "Mapping a an xml string to a real object with nested elements")]
+ public void ShouldMapADynamicXmlObjectToClassWithNestedElements()
+ {
+ string xmlstring = @"
+ <Contact Name=""Rui"" Id=""111"">
+ <phone>1234567890</phone>
+ <mail>rui@somewhere.com</mail>
+ <cities>
+ <city>Paris</city>
+ <city>Lisbon</city>
+ </cities>
+ </Contact>
+ ";
+ dynamic contactDynamic = new DynamicXmlElement(xmlstring);
+
+ Contact expected = new Contact();
+ expected.Name = "Rui";
+ expected.Id = 111;
+ expected.Mail = "rui@somewhere.com";
+ expected.Phone = "1234567890";
+ expected.Cities.Add("Paris");
+ expected.Cities.Add("Lisbon");
+ Contact actual = ValueFactory.TryGet<Contact>(contactDynamic);
+ Assert.AreEqual(actual, expected);
+ }
+ }
+}
36 Tests/ArtOfNet.FluentConfiguration.Tests/TestFixtureBase.cs
View
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Collections;
+
+namespace ConfArtTests
+{
+ public abstract class TestFixtureBase
+ {
+ public void Log(object obj)
+ {
+ System.Diagnostics.Debug.WriteLine(obj);
+ }
+
+ public void Log(object obj, string message)
+ {
+ System.Diagnostics.Debug.WriteLine(message);
+ Log(obj);
+ }
+
+ public void Log(IEnumerable list)
+ {
+ foreach (var item in list)
+ {
+ System.Diagnostics.Debug.WriteLine(item);
+ }
+ }
+
+ public void Log(IEnumerable list, string message)
+ {
+ System.Diagnostics.Debug.WriteLine(message);
+ Log(list);
+ }
+ }
+}
58 Tests/ArtOfNet.FluentConfiguration.Tests/ValueFactoryTests.cs
View
@@ -0,0 +1,58 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using NUnit.Framework;
+using ConfArt.Core;
+using ConfArt;
+using ConfArtTests.SampleData;
+using ConfArt.Contracts;
+
+namespace ConfArtTests
+{
+ [TestFixture]
+ public class ValueFactoryTests: TestFixtureBase
+ {
+ [Test]
+ public void ValueFactoryShouldBeInitializedByStatic()
+ {
+ Assert.IsTrue(ValueFactory.Initialized,"Value factory should have been initialized by the static constructor");
+ }
+
+ [Test]
+ public void ShouldHaveMappingForUserTypeAfterAutoConfigure()
+ {
+ Assert.IsTrue(ValueFactory.Initialized);
+ Assert.IsTrue(ConfigurationMapper.HasMappingFor<User>(), "Configuration should have mapping for 'User' class defined in test assembly after autoconfigure");
+ }
+
+ [Test]
+ public void ShouldGetAnEmptyValueWithEmptyData()
+ {
+ Dictionary<string, object> dv = new Dictionary<string, object>();
+ dv.Add("test_name", "Rui");
+ User user = ValueFactory.TryGet<User>(dv);
+ IConfigurationMappingsBase<User> mapper = ConfigurationMapper.GetMapper<User>();
+ Assert.IsNotNull(mapper);
+ Log(mapper.ConfiguredType);
+ Log(mapper.Settings.ToList());
+ var result = mapper.Get(dv);
+ Assert.IsNotNull(result);
+ Assert.IsTrue(ConfigurationMapper.HasMappingFor<User>());
+ Log(result.ToString());
+ Log(ConfigurationMapper.HasMappingFor<User>(), "Have mapping for user");
+ Assert.IsNotNull(user);
+ Log(user.ToString());
+
+ }
+
+ [Test]
+ public void ShouldCreateDynamicDictionary()
+ {
+ dynamic values = new DynamicConfigurationValues();
+ values["hello"] = "world";
+
+ Assert.AreEqual(values.hello,"world");
+ }
+ }
+}
4 Tests/ArtOfNet.FluentConfiguration.Tests/packages.config
View
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="NUnit" version="2.5.7.10213" />
+</packages>
242 Tests/TestTaskRunner/Program.cs
View
<
@@ -0,0 +1,242 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Linq.Expressions;
+using System.Reflection;
+using FluentConfigurationTests;
+using NUnit.Framework;
+
+using ArtOfNet.Framework.Core.Test;
+
+namespace TestTaskRunner
+{
+ class Program
+ {
+ static void Main(string[] args)
+ {
+ //TestTaskHelper.RunAllFor<DynamicXmlTests>();
+ Console.Read();
+ }
+
+
+
+
+ }
+
+ //public class NotTestableException: Exception
+ //{
+ // public NotTestableException(){}
+ // public NotTestableException(string message):base(message){}
+ //}
+
+ //public class TestTask<T> where T: class, new()
+ //{
+ // private T _cachedTaskFixture;
+ // private List<MethodInfo> _testMethods;
+
+ // public TestTask()
+ // {
+ // //verify that class is really a test fixture
+ // TestTaskHelper.EnsureTypeIsFixture<T>();
+ // //then create an instance if ok
+ // _cachedTaskFixture = Activator.CreateInstance<T>();
+ // //if instance is null, it must be an error, throw it
+ // if (_cachedTaskFixture == null)
+ // {
+ // throw new ArgumentNullException("T", "can not create an instance of T");
+ // }
+ // //then load in cache a list of available test methods
+ // LoadTestMethods();
+ // }
+
+ // public bool Test(Expression<Action<T>> selectedTest)
+ // {
+ // if (_cachedTaskFixture != null)
+ // {
+ // MethodCallExpression bodyMethod = (selectedTest.Body) as MethodCallExpression;
+ // if (bodyMethod == null)
+ // {
+ // throw new NotTestableException("The method you try to call is not valid");
+ // }
+ // var findMethod = from test in _testMethods
+ // where test == bodyMethod.Method
+ // select test;
+ // if (findMethod == null)
+ // {
+ // throw new NotTestableException("The method you try to call is not a test");
+ // }
+ // if (findMethod.Count() == 1)
+ // {
+ // Action<T> action = selectedTest.Compile();
+ // action.DynamicInvoke(_cachedTaskFixture);
+ // }
+ // else
+ // {
+ // throw new NotTestableException("The method you try to call is not valid"); ;
+ // }
+ // return true;
+ // }
+ // return false;
+ // }
+
+ // public bool RunAll(Action<string> beforeStart, Action<string> successRun, Action<string> failedRun)
+ // {
+ // bool result = true;
+ // foreach (MethodInfo method in _testMethods)
+ // {
+ // beforeStart(method.ToString());
+ // try
+ // {
+ // method.Invoke(_cachedTaskFixture, null);
+ // successRun("Result : ok");
+ // result &= true;
+ // }
+ // catch (Exception e)
+ // {
+ // failedRun(string.Format("Result : {0}", e.Message));
+ // result &= false;
+ // }
+ // }
+ // return result;
+ // }
+ // private void LoadTestMethods()
+ // {
+ // Type type = typeof(T);
+
+ // var methods = type.GetMethods();
+
+ // if (methods == null)
+ // {
+ // return;
+ // }
+
+ // var testMethods = from m in methods
+ // let customAttrib = m.GetCustomAttributes(typeof(TestAttribute), true)
+ // where customAttrib != null && customAttrib.Count() > 0
+ // select m;
+ // _testMethods = testMethods.ToList();
+ // }
+
+
+ //}
+
+ //public static class TestTaskHelper
+ //{
+ // public static bool IsTestFixture(Type t)
+ // {
+ // var attributes = t.GetCustomAttributes(true);
+ // if (attributes == null)
+ // {
+ // return false;
+ // }
+
+ // var isFixtureQuery = from a in attributes
+ // where a.ToString().Contains("TestFixture")
+ // select a;
+ // if (isFixtureQuery.Count() > 0)
+ // {
+ // return true;
+ // }
+ // else
+ // {
+ // return false;
+ // }
+ // }
+ // public static ConsoleTestMessageHelper Message = new ConsoleTestMessageHelper();
+ // public static void EnsureTypeIsFixture<T>()
+ // {
+ // if (!IsTestFixture(typeof(T)))
+ // {
+ // throw new NotTestableException(string.Format("Type [{0}] is not a TestFixture", typeof(T).Name));
+ // }
+ // }
+
+ // public static void Test<T>(Expression<Action<T>> selectedTest) where T : class, new()
+ // {
+ // string typeSource = (selectedTest.Type.GetGenericArguments()[0]).FullName;
+ // string methodName = selectedTest.ToString();