Merge branch 'master' of git://github.com/devtyr/YamlDotNet into devtyr-master

Conflicts:
	YamlDotNet.UnitTests/YamlDotNet.UnitTests.csproj
	YamlDotNet.sln
This commit is contained in:
Antoine Aubry 2013-09-29 22:48:56 +01:00
Родитель c58712d0a2 6c9c5054fe
Коммит 6edca681e9
16 изменённых файлов: 1138 добавлений и 16 удалений

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

@ -59,8 +59,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />

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

@ -58,8 +58,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>

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

@ -59,8 +59,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>

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

@ -0,0 +1,237 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Antoine Aubry
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Credits for this class: https://github.com/imgen
using System;
using System.Collections.Generic;
using Xunit;
namespace YamlDotNet.Dynamic.UnitTests
{
public class DynamicYamlTest
{
[Fact]
public void TestMappingNode()
{
dynamic dynamicYaml = new DynamicYaml(MappingYaml);
var receipt = (string)(dynamicYaml.Receipt);
var firstPartNo = dynamicYaml.Items[0].part_no;
Assert.Equal(receipt, "Oz-Ware Purchase Invoice");
}
[Fact]
public void TestSequenceNode()
{
dynamic dynamicYaml = new DynamicYaml(SequenceYaml);
string firstName = dynamicYaml[0].name;
Assert.Equal(firstName, "Me");
}
[Fact]
public void TestNestedSequenceNode()
{
dynamic dynamicYaml = new DynamicYaml(NestedSequenceYaml);
string firstNumberAsString = dynamicYaml[0, 0];
Assert.Equal(firstNumberAsString, "1");
int firstNumberAsInt = dynamicYaml[0, 0];
Assert.Equal(firstNumberAsInt, 1);
}
[Fact]
public void TestEnumConvert()
{
dynamic dynamicYaml = new DynamicYaml(EnumYaml);
StringComparison stringComparisonMode = dynamicYaml[0].stringComparisonMode;
Assert.Equal(StringComparison.CurrentCultureIgnoreCase, stringComparisonMode);
}
[Fact]
public void TestArrayConvert()
{
dynamic dynamicYaml = new DynamicYaml(NestedSequenceYaml);
dynamic[] dynamicArray = null;
Assert.DoesNotThrow(() =>
{
dynamicArray = dynamicYaml;
Assert.NotNull(dynamicArray);
Assert.NotEmpty(dynamicArray);
});
Assert.DoesNotThrow(() =>
{
int[] intArray = dynamicArray[0];
Assert.NotNull(intArray);
Assert.NotEmpty(intArray);
});
}
[Fact]
public void TestEnumArrayConvert()
{
dynamic dynamicYaml = new DynamicYaml(EnumSequenceYaml);
Assert.DoesNotThrow(() =>
{
StringComparison[] enumArray = dynamicYaml;
Assert.NotNull(enumArray);
Assert.NotEmpty(enumArray);
});
}
[Fact]
public void TestCollectionConvert()
{
dynamic dynamicYaml = new DynamicYaml(NestedSequenceYaml);
List<dynamic> dynamicList = null;
Assert.DoesNotThrow(() =>
{
dynamicList = dynamicYaml;
Assert.NotNull(dynamicList);
Assert.NotEmpty(dynamicList);
});
Assert.DoesNotThrow(() =>
{
List<int> intList = dynamicList[0];
Assert.NotNull(intList);
Assert.NotEmpty(intList);
});
}
[Fact]
public void TestEnumCollectionConvert()
{
dynamic dynamicYaml = new DynamicYaml(EnumSequenceYaml);
Assert.DoesNotThrow(() =>
{
List<StringComparison> enumList = dynamicYaml;
Assert.NotNull(enumList);
Assert.NotEmpty(enumList);
});
}
[Fact]
public void TestDictionaryConvert()
{
dynamic dynamicYaml = new DynamicYaml(MappingYaml);
Dictionary<string, dynamic> dynamicDictionary = null;
Assert.DoesNotThrow(() =>
{
dynamicDictionary = dynamicYaml;
Assert.NotNull(dynamicDictionary);
Assert.NotEmpty(dynamicDictionary);
});
Assert.DoesNotThrow(() =>
{
Dictionary<string, string> stringDictonary = dynamicDictionary["customer"];
Assert.NotNull(stringDictonary);
Assert.NotEmpty(stringDictonary);
});
}
[Fact]
public void TestEnumDictonaryConvert()
{
dynamic dynamicYaml = new DynamicYaml(EnumMappingYaml);
Assert.DoesNotThrow(() =>
{
IDictionary<StringComparison, string> enumDict = dynamicYaml;
Assert.NotNull(enumDict);
Assert.NotEmpty(enumDict);
});
}
[Fact]
public void TestNonexistingMember()
{
dynamic dynamicYaml = new DynamicYaml(SequenceYaml);
var title = (string)(dynamicYaml[0].Title);
Assert.Null(title);
var id = (int?)(dynamicYaml[0].Id);
Assert.Null(id);
}
private const string EnumYaml = @"---
- stringComparisonMode: CurrentCultureIgnoreCase
- stringComparisonMode: Ordinal";
private const string EnumMappingYaml = @"---
CurrentCultureIgnoreCase: on
Ordinal: off";
private const string EnumSequenceYaml = @"---
- CurrentCultureIgnoreCase
- Ordinal";
private const string SequenceYaml = @"---
- name: Me
- name: You";
private const string NestedSequenceYaml = @"---
- [1, 2, 3]
- [4, 5, 6]";
private const string MappingYaml = @"---
receipt: Oz-Ware Purchase Invoice
date: 2007-08-06
customer:
given: Dorothy
family: Gale
items:
- part_no: A4786
descrip: Water Bucket (Filled)
price: 1.47
quantity: 4
- part_no: E1628
descrip: High Heeled ""Ruby"" Slippers
price: 100.27
quantity: 1
bill-to: &id001
street: |
123 Tornado Alley
Suite 16
city: East Westville
state: KS
ship-to: *id001
specialDelivery: >
Follow the Yellow Brick
Road to the Emerald City.
Pay no attention to the
man behind the curtain.
...";
}
}

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

@ -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("YamlDotNet.Dynamic.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet.Dynamic.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("4101852b-818c-4847-9f0b-da45637326b0")]
// 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")]

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

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.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>{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>YamlDotNet.Dynamic.UnitTests</RootNamespace>
<AssemblyName>YamlDotNet.Dynamic.UnitTests</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<TargetFrameworkProfile />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</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="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" />
<Reference Include="xunit">
<HintPath>..\packages\xunit.1.9.1\lib\net20\xunit.dll</HintPath>
</Reference>
<Reference Include="xunit.extensions">
<HintPath>..\packages\xunit.extensions.1.9.1\lib\net20\xunit.extensions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DynamicYamlTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\YamlDotNet.Dynamic\YamlDotNet.Dynamic.csproj">
<Project>{57B52D79-04A0-4091-8EE2-B419C009C2A6}</Project>
<Name>YamlDotNet.Dynamic</Name>
</ProjectReference>
<ProjectReference Include="..\YamlDotNet.RepresentationModel\YamlDotNet.RepresentationModel.csproj">
<Project>{21CA0077-E15C-446D-9C43-F6D3F9D09687}</Project>
<Name>YamlDotNet.RepresentationModel</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.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,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="xunit" version="1.9.1" targetFramework="net40" />
<package id="xunit.extensions" version="1.9.1" targetFramework="net40" />
</packages>

19
YamlDotNet.Dynamic.nuspec Normal file
Просмотреть файл

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<package>
<metadata>
<id>YamlDotNet.Dynamic</id>
<version></version>
<authors>Antoine Aubry</authors>
<description>A .NET library for YAML. yamldotnet provides low level parsing and emitting of YAML as well as a high level object model similar to XmlDocument.</description>
<summary>This package contains the YAML parser to dynamic objects.</summary>
<language>en-US</language>
<licenseUrl>http://www.aaubry.net/yamldotnet/license.aspx</licenseUrl>
<projectUrl>http://www.aaubry.net/yamldotnet.aspx</projectUrl>
<iconUrl>http://www.aaubry.net/IMAGES%2f2012%2f11%2fyamldotnet.png.jpgx</iconUrl>
<tags>yaml parser development library dynamic</tags>
</metadata>
<files>
<file src="..\YamlDotNet.Dynamic\bin\Release\YamlDotNet.Dynamic.dll" target="lib\net40" />
<file src="..\YamlDotNet.Dynamic\bin\Release\YamlDotNet.Dynamic.pdb" target="lib\net40" />
</files>
</package>

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

@ -0,0 +1,499 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Antoine Aubry
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Credits for this class: https://github.com/imgen
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using YamlDotNet.RepresentationModel;
namespace YamlDotNet.Dynamic
{
public class DynamicYaml : DynamicObject
{
private static readonly Type[] ConvertableBasicTypes =
{
typeof(DynamicYaml),
typeof(object),
typeof(string),
typeof(char),
typeof(int),
typeof(long),
typeof(float),
typeof(double),
typeof(decimal)
};
private static readonly Type[] ConvertableGenericCollectionTypes =
{
typeof(IEnumerable<>),
typeof(ICollection<>),
typeof(IList<>),
typeof(List<>)
};
private static readonly Type[] ConvertableGenericDictionaryTypes =
{
typeof(IDictionary<,>),
typeof(Dictionary<,>)
};
private static readonly Type[] ConvertableCollectionTypes = ConvertableGenericCollectionTypes.
SelectMany(type => ConvertableBasicTypes.
Select(basicType => type.MakeGenericType(basicType))
).ToArray();
private static readonly Type[] ConvertableDictionaryTypes = ConvertableGenericDictionaryTypes.
SelectMany(type => ConvertableBasicTypes.
SelectMany(valueType => ConvertableBasicTypes.
Select(keyType => type.MakeGenericType(keyType, valueType)
))).ToArray();
private static readonly Type[] ConvertableArrayTypes = ConvertableBasicTypes.Select(
type => type.MakeArrayType()).ToArray();
private YamlMappingNode mappingNode;
private YamlSequenceNode sequenceNode;
private YamlScalarNode scalarNode;
private YamlNode yamlNode;
public DynamicYaml(YamlNode node)
{
Reload(node);
}
public DynamicYaml(TextReader reader)
: this(YamlDoc.LoadFromTextReader(reader))
{
}
public DynamicYaml(string yaml)
: this(YamlDoc.LoadFromString(yaml))
{
}
public void Reload(YamlNode node)
{
yamlNode = node;
mappingNode = yamlNode as YamlMappingNode;
sequenceNode = yamlNode as YamlSequenceNode;
scalarNode = yamlNode as YamlScalarNode;
children = null;
}
public void Reload(TextReader reader)
{
Reload(YamlDoc.LoadFromTextReader(reader));
}
public void Reload(string yaml)
{
Reload(YamlDoc.LoadFromString(yaml));
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return TryGetValueByKeyAndType(binder.Name, binder.ReturnType, out result);
}
private static bool FailToGetValue(out object result)
{
result = null;
return false;
}
private static bool SuccessfullyGetValue(out object result, object value)
{
result = value;
return true;
}
private bool TryGetValueByKeyAndType(string key,
Type type,
out object result)
{
if (mappingNode == null)
{
return FailToGetValue(out result);
}
var yamlKey = new YamlScalarNode(key.Decapitalize());
var yamlKey2 = new YamlScalarNode(key.Capitalize());
return TryGetValueByYamlKeyAndType(yamlKey, type, out result) ||
TryGetValueByYamlKeyAndType(yamlKey2, type, out result);
}
private bool TryGetValueByYamlKeyAndType(YamlScalarNode yamlKey, Type type, out object result)
{
if (mappingNode.Children.ContainsKey(yamlKey))
{
var value = mappingNode.Children[yamlKey];
if (YamlDoc.TryMapValue(value, out result))
{
return true;
}
}
return IsNullableType(type) ? SuccessfullyGetValue(out result, new DynamicYaml((YamlNode)null)) : FailToGetValue(out result);
}
private static bool IsNullableType(Type type)
{
return type != null && (!type.IsValueType || Nullable.GetUnderlyingType(type) != null);
}
private bool TryGetValueByIndex(int index, out object result)
{
if (sequenceNode == null)
{
return FailToGetValue(out result);
}
if (index >= sequenceNode.Count())
{
throw new IndexOutOfRangeException();
}
return YamlDoc.TryMapValue(sequenceNode.ToArray()[index], out result);
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indices, out object result)
{
var stringKey = indices[0] as string;
if (stringKey != null)
{
if (TryGetValueByKeyAndType(stringKey, binder.ReturnType, out result))
{
return indices.Length <= 1 || TryGetIndex(binder, indices.Skip(1).ToArray(), out result);
}
return FailToGetValue(out result);
}
var intKey = indices[0] as int?;
if (intKey != null)
{
if (TryGetValueByIndex(intKey.Value, out result))
{
if (indices.Length > 1)
{
if (result is DynamicYaml)
{
return ((DynamicYaml)result).TryGetIndex(binder, indices.Skip(1).ToArray(), out result);
}
return FailToGetValue(out result);
}
return true;
}
return FailToGetValue(out result);
}
return base.TryGetIndex(binder, indices, out result);
}
private bool TryConvertToBasicType(Type type, bool isNullable, out object result)
{
if (type == typeof(object) || type == typeof(DynamicYaml))
{
return SuccessfullyGetValue(out result, this);
}
if (scalarNode == null)
{
if (isNullable)
{
return SuccessfullyGetValue(out result, null);
}
return FailToGetValue(out result);
}
if (type == typeof(string))
{
return SuccessfullyGetValue(out result, scalarNode.Value);
}
if (type == typeof(char))
{
char charResult;
bool success = char.TryParse(scalarNode.Value, out charResult);
result = success ? (object)charResult : null;
return success;
}
if (type == typeof(int))
{
int intResult;
bool success = int.TryParse(scalarNode.Value, out intResult);
result = success ? (object)intResult : null;
return success;
}
if (type == typeof(long))
{
long longResult;
bool success = long.TryParse(scalarNode.Value, out longResult);
result = success ? (object)longResult : null;
return success;
}
if (type == typeof(float))
{
float floatResult;
bool success = float.TryParse(scalarNode.Value, out floatResult);
result = success ? (object)floatResult : null;
return success;
}
if (type == typeof(double))
{
double doubleResult;
bool success = double.TryParse(scalarNode.Value, out doubleResult);
result = success ? (object)doubleResult : null;
return success;
}
if (type == typeof(decimal))
{
decimal decimalResult;
bool success = decimal.TryParse(scalarNode.Value, out decimalResult);
result = success ? (object)decimalResult : null;
return success;
}
if (type.IsEnum)
{
long longResult;
if (long.TryParse(scalarNode.Value, out longResult))
{
result = longResult;
return true;
}
try
{
result = Enum.Parse(type, scalarNode.Value);
return true;
}
catch
{
return FailToGetValue(out result);
}
}
return FailToGetValue(out result);
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
var type = binder.ReturnType;
return TryConvertToType(type, out result);
}
private bool IsGenericEnumCollection(Type type)
{
if (!type.IsGenericType)
{
return false;
}
Type[] genericTypeArgs = type.GetGenericArguments();
if (genericTypeArgs.Length != 1)
{
return false;
}
var elementType = genericTypeArgs.First();
return elementType.IsEnum && ConvertableGenericCollectionTypes.Any(
genericType => genericType.MakeGenericType(elementType) == type);
}
private bool IsLegalElementType(Type type)
{
return type.IsEnum || ConvertableBasicTypes.Contains(type);
}
private bool IsGenericEnumDictionary(Type type)
{
if (!type.IsGenericType)
{
return false;
}
Type[] genericTypeArgs = type.GetGenericArguments();
if (genericTypeArgs.Length != 2)
{
return false;
}
Type keyType = genericTypeArgs[0], valueType = genericTypeArgs[1];
return (keyType.IsEnum || valueType.IsEnum) &&
ConvertableGenericDictionaryTypes.
Any(genericType => genericType.MakeGenericType(keyType, valueType) == type) &&
IsLegalElementType(keyType) && IsLegalElementType(valueType);
}
private bool TryConvertToType(Type type, out object result)
{
if (type.IsArray &&
(ConvertableArrayTypes.Contains(type) ||
type.GetElementType().IsSubclassOf(typeof(Enum)))
)
{
return TryConvertToArray(type, out result);
}
if (ConvertableCollectionTypes.Contains(type) ||
IsGenericEnumCollection(type))
{
return TryConvertToCollection(type, out result);
}
if (ConvertableDictionaryTypes.Contains(type) ||
IsGenericEnumDictionary(type))
{
return TryConvertToDictionary(type, out result);
}
var underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
type = underlyingType;
}
return TryConvertToBasicType(type, IsNullableType(type), out result);
}
private bool TryConvertToDictionary(Type type, out object result)
{
if (mappingNode == null)
{
return FailToGetValue(out result);
}
Type[] genericTypeArgs = type.GetGenericArguments();
Type keyType = genericTypeArgs[0],
valueType = genericTypeArgs[1];
Type dictType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
var dict = Activator.CreateInstance(dictType) as IDictionary;
if (dict != null)
{
foreach (KeyValuePair<YamlNode, YamlNode> pair in mappingNode.Children)
{
object key;
if (!new DynamicYaml(pair.Key).TryConvertToType(keyType, out key))
{
return FailToGetValue(out result);
}
object value;
if (!new DynamicYaml(pair.Value).TryConvertToType(valueType, out value))
{
return FailToGetValue(out result);
}
dict.Add(key, value);
}
}
return SuccessfullyGetValue(out result, dict);
}
private bool TryConvertToCollection(Type type, out object result)
{
var elementType = type.GetGenericArguments().First();
Type listType = typeof(List<>).MakeGenericType(elementType);
var list = Activator.CreateInstance(listType) as IList;
if (list != null)
{
foreach (DynamicYaml child in Children)
{
object result2;
if (!child.TryConvertToType(elementType, out result2))
{
return FailToGetValue(out result);
}
list.Add(result2);
}
}
return SuccessfullyGetValue(out result, list);
}
private bool TryConvertToArray(Type type, out object result)
{
if (Children == null)
{
return FailToGetValue(out result);
}
var elementType = type.GetElementType();
Array arrayResult = Array.CreateInstance(elementType, Children.Count);
int index = 0;
foreach (var child in Children)
{
object result2;
if (!child.TryConvertToType(elementType, out result2))
{
return FailToGetValue(out result);
}
arrayResult.SetValue(result2, index);
index++;
}
return SuccessfullyGetValue(out result, arrayResult);
}
private IList<DynamicYaml> GetChilren()
{
if (mappingNode != null)
{
return mappingNode.Children.Values.Select(node => new DynamicYaml(node)).ToList();
}
if (sequenceNode != null)
{
return sequenceNode.Select(node => new DynamicYaml(node)).ToList();
}
return new List<DynamicYaml>();
}
private IList<DynamicYaml> children;
public IList<DynamicYaml> Children
{
get
{
if (children == null)
{
children = GetChilren();
}
return children;
}
}
public int Count
{
get
{
return Children != null ? Children.Count : 0;
}
}
}
}

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

@ -0,0 +1,60 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Antoine Aubry
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Credits for this class: https://github.com/imgen
using System.IO;
namespace YamlDotNet.Dynamic
{
public static class Extensions
{
public static TextReader ToTextReader(this string str)
{
return str.IsNullOrEmpty() ? null : new StringReader(str);
}
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
public static string Capitalize(this string str)
{
if (str.IsNullOrEmpty())
{
return str;
}
return char.ToUpper(str[0]) + str.Substring(1);
}
public static string Decapitalize(this string str)
{
if (str.IsNullOrEmpty())
{
return str;
}
return char.ToLower(str[0]) + str.Substring(1);
}
}
}

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

@ -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("YamlDotNet.Dynamic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet.Dynamic")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("e43baa83-f590-476a-9687-4a8dbbe52c89")]
// 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")]

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

@ -0,0 +1,63 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Antoine Aubry
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Credits for this class: https://github.com/imgen
using System.IO;
using System.Linq;
using YamlDotNet.RepresentationModel;
namespace YamlDotNet.Dynamic
{
public static class YamlDoc
{
public static YamlNode LoadFromFile(string fileName)
{
return LoadFromTextReader(File.OpenText(fileName));
}
public static YamlNode LoadFromString(string yamlText)
{
return LoadFromTextReader(new StringReader(yamlText));
}
public static YamlNode LoadFromTextReader(TextReader reader)
{
var yaml = new YamlStream();
yaml.Load(reader);
return yaml.Documents.First().RootNode;
}
internal static bool TryMapValue(object value, out object result)
{
var node = value as YamlNode;
if (node != null)
{
result = new DynamicYaml(node);
return true;
}
result = null;
return false;
}
}
}

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

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.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>{57B52D79-04A0-4091-8EE2-B419C009C2A6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>YamlDotNet.Dynamic</RootNamespace>
<AssemblyName>YamlDotNet.Dynamic</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<TargetFrameworkProfile />
</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="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="DynamicYaml.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="YamlDoc.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\YamlDotNet.RepresentationModel\YamlDotNet.RepresentationModel.csproj">
<Project>{21CA0077-E15C-446D-9C43-F6D3F9D09687}</Project>
<Name>YamlDotNet.RepresentationModel</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>

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

@ -60,8 +60,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
</Reference>
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>

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

@ -11,6 +11,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.Configuration",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.UnitTests", "YamlDotNet.UnitTests\YamlDotNet.UnitTests.csproj", "{114910D8-5B05-4FDC-BDA0-0DF7A29892DC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.Dynamic", "YamlDotNet.Dynamic\YamlDotNet.Dynamic.csproj", "{57B52D79-04A0-4091-8EE2-B419C009C2A6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.Dynamic.UnitTests", "YamlDotNet.Dynamic.UnitTests\YamlDotNet.Dynamic.UnitTests.csproj", "{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -25,10 +29,18 @@ Global
{21CA0077-E15C-446D-9C43-F6D3F9D09687}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21CA0077-E15C-446D-9C43-F6D3F9D09687}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21CA0077-E15C-446D-9C43-F6D3F9D09687}.Release|Any CPU.Build.0 = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|Any CPU.Build.0 = Release|Any CPU
{6A8DCAF7-6C13-4ADA-AED9-7ABA88FE7717}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A8DCAF7-6C13-4ADA-AED9-7ABA88FE7717}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A8DCAF7-6C13-4ADA-AED9-7ABA88FE7717}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6A8DCAF7-6C13-4ADA-AED9-7ABA88FE7717}.Release|Any CPU.Build.0 = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|Any CPU.Build.0 = Release|Any CPU
{A0178805-DC16-46B6-BEDF-AA201207C17E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A0178805-DC16-46B6-BEDF-AA201207C17E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A0178805-DC16-46B6-BEDF-AA201207C17E}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -61,14 +73,6 @@ Global
$4.AllowEventAddBlockInline = False
$4.AllowEventRemoveBlockInline = False
$4.StatementBraceStyle = NextLine
$4.IfElseBraceForcement = AddBraces
$4.ForBraceForcement = AddBraces
$4.WhileBraceForcement = AddBraces
$4.UsingBraceForcement = AddBraces
$4.FixedBraceForcement = AddBraces
$4.PlaceElseOnNewLine = True
$4.PlaceCatchOnNewLine = True
$4.PlaceFinallyOnNewLine = True
$4.BeforeMethodDeclarationParentheses = False
$4.BeforeMethodCallParentheses = False
$4.BeforeConstructorDeclarationParentheses = False

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

@ -9,6 +9,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
YamlDotNet.build = YamlDotNet.build
YamlDotNet.Converters.nuspec = YamlDotNet.Converters.nuspec
YamlDotNet.Core.nuspec = YamlDotNet.Core.nuspec
YamlDotNet.Dynamic.nuspec = YamlDotNet.Dynamic.nuspec
YamlDotNet.FxCop = YamlDotNet.FxCop
YamlDotNet.RepresentationModel.nuspec = YamlDotNet.RepresentationModel.nuspec
YamlDotNet.snk = YamlDotNet.snk
@ -41,6 +42,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.Core.Test", "Yam
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.RepresentationModel.Test", "YamlDotNet.RepresentationModel.Test\YamlDotNet.RepresentationModel.Test.csproj", "{FF969DAA-C025-4636-89B2-46F16821FA02}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.Dynamic", "YamlDotNet.Dynamic\YamlDotNet.Dynamic.csproj", "{57B52D79-04A0-4091-8EE2-B419C009C2A6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YamlDotNet.Dynamic.UnitTests", "YamlDotNet.Dynamic.UnitTests\YamlDotNet.Dynamic.UnitTests.csproj", "{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -151,6 +156,26 @@ Global
{FF969DAA-C025-4636-89B2-46F16821FA02}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{FF969DAA-C025-4636-89B2-46F16821FA02}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{FF969DAA-C025-4636-89B2-46F16821FA02}.Release|x86.ActiveCfg = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Debug|x86.ActiveCfg = Debug|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|Any CPU.Build.0 = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{57B52D79-04A0-4091-8EE2-B419C009C2A6}.Release|x86.ActiveCfg = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Debug|x86.ActiveCfg = Debug|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|Any CPU.Build.0 = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{6E3BEF5A-2DBA-4941-972D-BD6AF27B4A71}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE