Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge remote-tracking branch 'origin/HEAD'

Conflicts:
	src/ServiceStack.Interfaces/ServiceHost/EndpointAttributes.cs
	src/ServiceStack/ServiceHost/ServiceController.cs
	src/ServiceStack/ServiceStack.csproj
  • Loading branch information...
commit ed25a9edab411acad7841ad6c59f5a3a3621d04d 2 parents 866b756 + 9f0f3fa
Demis Bellot mythz authored
Showing with 12,905 additions and 10,073 deletions.
  1. +34 −0 NuGet/ServiceStack.Razor/content/web.config.transform
  2. BIN  NuGet/ServiceStack.Razor/lib/net40/ServiceStack.Razor.dll
  3. BIN  NuGet/ServiceStack.Razor/lib/net40/ServiceStack.Razor.pdb
  4. BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.Razor.dll
  5. BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.WebPages.Deployment.dll
  6. BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.WebPages.Razor.dll
  7. BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.WebPages.dll
  8. +102 −101 src/ServiceStack.Common/ServiceModel/Serialization/DataContractSerializer.cs
  9. +99 −99 src/ServiceStack.Common/ServiceModel/Serialization/StringMapTypeDeserializer.cs
  10. +431 −423 src/ServiceStack.Common/Utils/ReflectionUtils.cs
  11. +226 −207 src/ServiceStack.Common/Web/ContentType.cs
  12. +14 −13 src/ServiceStack.Common/Web/EndpointType.cs
  13. +72 −73 src/ServiceStack.FluentValidation.Mvc3/Mvc/ExecuteServiceStackFiltersAttribute.cs
  14. +5 −4 src/ServiceStack.Interfaces/ServiceHost/EndpointAttributes.cs
  15. +126 −0 src/ServiceStack.Interfaces/ServiceHost/EndpointAttributes.cs.orig
  16. +28 −24 src/ServiceStack.Interfaces/ServiceHost/Feature.cs
  17. +502 −502 src/ServiceStack.ServiceInterface/Testing/TestBase.cs
  18. +73 −0 src/ServiceStack/MetadataFeature.cs
  19. +81 −0 src/ServiceStack/PredefinedRoutesFeature.cs
  20. +0 −3  src/ServiceStack/README.md
  21. +28 −0 src/ServiceStack/RequestInfoFeature.cs
  22. +100 −96 src/ServiceStack/ServiceHost/ServiceController.cs
  23. +1,039 −0 src/ServiceStack/ServiceHost/ServiceController.cs.orig
  24. +164 −160 src/ServiceStack/ServiceHost/ServiceManager.cs
  25. +71 −69 src/ServiceStack/ServiceHost/ServiceOperations.cs
  26. +3 −1 src/ServiceStack/ServiceStack.csproj
  27. +800 −0 src/ServiceStack/ServiceStack.csproj.orig
  28. +53 −52 src/ServiceStack/WebHost.Endpoints/AppHostExtensions.cs
  29. +413 −398 src/ServiceStack/WebHost.Endpoints/EndpointHost.cs
  30. +146 −137 src/ServiceStack/WebHost.Endpoints/Metadata/BaseMetadataHandler.cs
  31. +34 −33 src/ServiceStack/WebHost.Endpoints/Metadata/JsonMetadataHandler.cs
  32. +382 −477 src/ServiceStack/WebHost.Endpoints/ServiceStackHttpHandlerFactory.cs
  33. +635 −591 tests/RazorRockstars.Console.Files/ReqStarsService.cs
  34. +32 −26 tests/RazorRockstars.Web/AppHost.cs
  35. +189 −184 tests/RazorRockstars.Web/RazorRockstars.Web.csproj
  36. +594 −0 tests/RazorRockstars.Web/ReqStarsService.cs
  37. +348 −348 tests/ServiceStack.WebHost.Endpoints.Tests/CustomerServiceValidationTests.cs
  38. +279 −279 tests/ServiceStack.WebHost.Endpoints.Tests/ExceptionHandlingTests.cs
  39. +256 −256 tests/ServiceStack.WebHost.Endpoints.Tests/FileUploadTests.cs
  40. +51 −51 tests/ServiceStack.WebHost.Endpoints.Tests/HtmlResultTests.cs
  41. +107 −107 tests/ServiceStack.WebHost.Endpoints.Tests/HttpErrorTests.cs
  42. +104 −104 tests/ServiceStack.WebHost.Endpoints.Tests/HttpResultTests.cs
  43. +35 −35 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/CachedMoviesService.cs
  44. +33 −33 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/ConfigureDatabase.cs
  45. +92 −92 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/ErrorRestTests.cs
  46. +24 −24 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/ExampleConfig.cs
  47. +111 −111 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/IntegrationTestBase.cs
  48. +87 −87 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/MovieRestTests.cs
  49. +22 −22 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/ResetMovieDatabase.cs
  50. +43 −43 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/ResetMovies.cs
  51. +101 −101 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/RestMovie.cs
  52. +68 −68 tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/RestMovieService.cs
  53. +124 −124 tests/ServiceStack.WebHost.Endpoints.Tests/IocServiceTests.cs
  54. +189 −189 tests/ServiceStack.WebHost.Endpoints.Tests/MessageSerializationTests.cs
  55. +148 −148 tests/ServiceStack.WebHost.Endpoints.Tests/NewApiTodos.cs
  56. +20 −20 tests/ServiceStack.WebHost.Endpoints.Tests/OperationTests.cs
  57. +46 −46 tests/ServiceStack.WebHost.Endpoints.Tests/Properties/AssemblyInfo.cs
  58. +138 −138 tests/ServiceStack.WebHost.Endpoints.Tests/ProtoBufServiceTests.cs
  59. +85 −85 tests/ServiceStack.WebHost.Endpoints.Tests/RawRequestTests.cs
  60. +131 −131 tests/ServiceStack.WebHost.Endpoints.Tests/RemoteEndDropsConnectionTests.cs
  61. +164 −164 tests/ServiceStack.WebHost.Endpoints.Tests/RequestContextTests.cs
  62. +510 −510 tests/ServiceStack.WebHost.Endpoints.Tests/RequestFiltersTests.cs
  63. +1 −1  tests/ServiceStack.WebHost.Endpoints.Tests/ServiceOperationsTests.cs
  64. +281 −281 tests/ServiceStack.WebHost.Endpoints.Tests/ServiceStack.WebHost.Endpoints.Tests.csproj
  65. +76 −60 tests/ServiceStack.WebHost.Endpoints.Tests/ServiceStackHttpHandlerFactoryTests.cs
  66. +86 −86 tests/ServiceStack.WebHost.Endpoints.Tests/SharedDtoTests.cs
  67. +295 −295 tests/ServiceStack.WebHost.Endpoints.Tests/Support/DirectServiceClient.cs
  68. +76 −76 tests/ServiceStack.WebHost.Endpoints.Tests/Support/EndpointHandlerBaseTests.cs
  69. +534 −534 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Host/ExampleAppHostHttpListener.cs
  70. +95 −95 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Host/IocAppHost.cs
  71. +23 −23 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Host/TestAppHost.cs
  72. +57 −57 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Host/TestConfigAppHostHttpListener.cs
  73. +27 −27 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Operations/CustomFormData.cs
  74. +26 −26 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Operations/CustomRequestBinder.cs
  75. +5 −5 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Operations/RequestOfAllTypes.cs
  76. +5 −5 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Operations/RequestOfComplexTypes.cs
  77. +52 −52 tests/ServiceStack.WebHost.Endpoints.Tests/Support/ServiceClientTestBase.cs
  78. +23 −23 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/CustomFormDataService.cs
  79. +88 −88 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/FileUploadService.cs
  80. +39 −39 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/HeadersService.cs
  81. +32 −32 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/HelloService.cs
  82. +65 −65 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/HttpErrorService.cs
  83. +166 −166 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/IocService.cs
  84. +37 −37 tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/RequestFilter.cs
  85. +22 −22 tests/ServiceStack.WebHost.Endpoints.Tests/Support/TestBase.cs
  86. +266 −266 tests/ServiceStack.WebHost.Endpoints.Tests/SyncRestClientTests.cs
  87. +14 −14 tests/ServiceStack.WebHost.Endpoints.Tests/TestExistingDir/default.html
  88. +13 −13 tests/ServiceStack.WebHost.Endpoints.Tests/TestExistingDir/upload.html
  89. +146 −146 tests/ServiceStack.WebHost.Endpoints.Tests/TodoListTests.cs
  90. +177 −177 tests/ServiceStack.WebHost.Endpoints.Tests/UserServiceValidationTests.cs
  91. +58 −58 tests/ServiceStack.WebHost.Endpoints.Tests/WebServiceExceptionTests.cs
  92. +55 −55 tests/ServiceStack.WebHost.Endpoints.Tests/WsdlMetadataTests.cs
  93. +14 −14 tests/ServiceStack.WebHost.Endpoints.Tests/webpage.html
  94. +29 −29 tests/ServiceStack.WebHost.IntegrationTests/Content/default.css
  95. +217 −217 tests/ServiceStack.WebHost.IntegrationTests/Default.aspx
  96. +13 −0 tests/ServiceStack.WebHost.IntegrationTests/Tests/RequestAndPathResolutionTests.cs
34 NuGet/ServiceStack.Razor/content/web.config.transform
View
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+ <configSections>
+ <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
+ <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
+ <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
+ </sectionGroup>
+ </configSections>
+ <appSettings>
+ <add key="webPages:Enabled" value="false" />
+ </appSettings>
+ <system.web>
+ <compilation debug="true">
+ <assemblies>
+ <add assembly="System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
+ </assemblies>
+ <buildProviders>
+ <add extension=".cshtml" type="ServiceStack.Razor.CSharpRazorBuildProvider, ServiceStack.Razor" />
+ </buildProviders>
+ </compilation>
+ </system.web>
+ <system.web.webPages.razor>
+ <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
+ <pages pageBaseType="ServiceStack.Razor.ViewPage">
+ <namespaces>
+ <add namespace="ServiceStack.Html" />
+ <add namespace="ServiceStack.Razor" />
+ <add namespace="ServiceStack.Text" />
+ <add namespace="ServiceStack.OrmLite" />
+ <add namespace="$rootnamespace$" />
+ </namespaces>
+ </pages>
+ </system.web.webPages.razor>
+</configuration>
BIN  NuGet/ServiceStack.Razor/lib/net40/ServiceStack.Razor.dll
View
Binary file not shown
BIN  NuGet/ServiceStack.Razor/lib/net40/ServiceStack.Razor.pdb
View
Binary file not shown
BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.Razor.dll
View
Binary file not shown
BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.WebPages.Deployment.dll
View
Binary file not shown
BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.WebPages.Razor.dll
View
Binary file not shown
BIN  NuGet/ServiceStack.Razor/lib/net40/System.Web.WebPages.dll
View
Binary file not shown
203 src/ServiceStack.Common/ServiceModel/Serialization/DataContractSerializer.cs
View
@@ -1,101 +1,102 @@
-using System;
-using System.IO;
-using System.Runtime.Serialization;
-using System.Text;
-using System.Xml;
-using ServiceStack.DesignPatterns.Serialization;
-
-#if !SILVERLIGHT && !MONOTOUCH && !XBOX
-using System.IO.Compression;
-#endif
-
-namespace ServiceStack.ServiceModel.Serialization
-{
- public class DataContractSerializer : IStringSerializer
- {
- private static readonly Encoding Encoding = Encoding.UTF8;// new UTF8Encoding(true);
- public static DataContractSerializer Instance = new DataContractSerializer();
-
- public string Parse<XmlDto>(XmlDto from, bool indentXml)
- {
- try
- {
- using (var ms = new MemoryStream())
- {
- var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
-#if !SILVERLIGHT && !MONOTOUCH && !XBOX
- using (var xw = new XmlTextWriter(ms, Encoding))
- {
- if (indentXml)
- {
- xw.Formatting = Formatting.Indented;
- }
-
- serializer.WriteObject(xw, from);
- xw.Flush();
-#else
- serializer.WriteObject(ms, from);
-#endif
-
- ms.Seek(0, SeekOrigin.Begin);
- using (var reader = new StreamReader(ms))
- {
- return reader.ReadToEnd();
- }
-
-#if !SILVERLIGHT && !MONOTOUCH && !XBOX
- }
-#endif
- }
- }
- catch (Exception ex)
- {
- throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
- }
- }
-
- public string Parse<XmlDto>(XmlDto from)
- {
- return Parse(from, false);
- }
-
-
- public void SerializeToStream(object obj, Stream stream)
- {
-#if !SILVERLIGHT && !MONOTOUCH && !XBOX
- using (var xw = new XmlTextWriter(stream, Encoding))
- {
- var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
- serializer.WriteObject(xw, obj);
- }
-#else
- var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
- serializer.WriteObject(stream, obj);
-#endif
- }
-
-#if !SILVERLIGHT && !MONOTOUCH && !XBOX
- public void CompressToStream<XmlDto>(XmlDto from, Stream stream)
- {
- using (var deflateStream = new DeflateStream(stream, CompressionMode.Compress))
- using (var xw = new XmlTextWriter(deflateStream, Encoding))
- {
- var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
- serializer.WriteObject(xw, from);
- xw.Flush();
- }
- }
-
- public byte[] Compress<XmlDto>(XmlDto from)
- {
- using (var ms = new MemoryStream())
- {
- CompressToStream(from, ms);
-
- return ms.ToArray();
- }
- }
-#endif
-
- }
-}
+using System;
+using System.IO;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Xml;
+using ServiceStack.DesignPatterns.Serialization;
+
+#if !SILVERLIGHT && !MONOTOUCH && !XBOX
+using System.IO.Compression;
+#endif
+
+namespace ServiceStack.ServiceModel.Serialization
+{
+ public class DataContractSerializer : IStringSerializer
+ {
+ private static readonly Encoding Encoding = Encoding.UTF8;// new UTF8Encoding(true);
+ public static DataContractSerializer Instance = new DataContractSerializer();
+
+ public string Parse<XmlDto>(XmlDto from, bool indentXml)
+ {
+ try
+ {
+ if (Equals(@from, default(XmlDto))) return null;
+ using (var ms = new MemoryStream())
+ {
+ var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
+#if !SILVERLIGHT && !MONOTOUCH && !XBOX
+ using (var xw = new XmlTextWriter(ms, Encoding))
+ {
+ if (indentXml)
+ {
+ xw.Formatting = Formatting.Indented;
+ }
+
+ serializer.WriteObject(xw, from);
+ xw.Flush();
+#else
+ serializer.WriteObject(ms, from);
+#endif
+
+ ms.Seek(0, SeekOrigin.Begin);
+ using (var reader = new StreamReader(ms))
+ {
+ return reader.ReadToEnd();
+ }
+
+#if !SILVERLIGHT && !MONOTOUCH && !XBOX
+ }
+#endif
+ }
+ }
+ catch (Exception ex)
+ {
+ throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
+ }
+ }
+
+ public string Parse<XmlDto>(XmlDto from)
+ {
+ return Parse(from, false);
+ }
+
+
+ public void SerializeToStream(object obj, Stream stream)
+ {
+#if !SILVERLIGHT && !MONOTOUCH && !XBOX
+ using (var xw = new XmlTextWriter(stream, Encoding))
+ {
+ var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
+ serializer.WriteObject(xw, obj);
+ }
+#else
+ var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
+ serializer.WriteObject(stream, obj);
+#endif
+ }
+
+#if !SILVERLIGHT && !MONOTOUCH && !XBOX
+ public void CompressToStream<XmlDto>(XmlDto from, Stream stream)
+ {
+ using (var deflateStream = new DeflateStream(stream, CompressionMode.Compress))
+ using (var xw = new XmlTextWriter(deflateStream, Encoding))
+ {
+ var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
+ serializer.WriteObject(xw, from);
+ xw.Flush();
+ }
+ }
+
+ public byte[] Compress<XmlDto>(XmlDto from)
+ {
+ using (var ms = new MemoryStream())
+ {
+ CompressToStream(from, ms);
+
+ return ms.ToArray();
+ }
+ }
+#endif
+
+ }
+}
198 src/ServiceStack.Common/ServiceModel/Serialization/StringMapTypeDeserializer.cs
View
@@ -1,97 +1,97 @@
-using System;
-using System.Collections.Generic;
-using System.Runtime.Serialization;
-using ServiceStack.Common;
-using ServiceStack.Common.Utils;
-using ServiceStack.Logging;
-using ServiceStack.Text;
-using ServiceStack.Text.Common;
-using ServiceStack.Text.Jsv;
-
-namespace ServiceStack.ServiceModel.Serialization
-{
- /// <summary>
- /// Serializer cache of delegates required to create a type from a string map (e.g. for REST urls)
- /// </summary>
- public class StringMapTypeDeserializer
- {
- private static readonly ILog Log = LogManager.GetLogger(typeof(StringMapTypeDeserializer));
-
- internal class PropertySerializerEntry
- {
- public PropertySerializerEntry(SetPropertyDelegate propertySetFn, ParseStringDelegate propertyParseStringFn)
- {
- PropertySetFn = propertySetFn;
- PropertyParseStringFn = propertyParseStringFn;
- }
-
- public SetPropertyDelegate PropertySetFn;
- public ParseStringDelegate PropertyParseStringFn;
- public Type PropertyType;
- }
-
- private readonly Type type;
- private readonly Dictionary<string, PropertySerializerEntry> propertySetterMap
- = new Dictionary<string, PropertySerializerEntry>(StringComparer.InvariantCultureIgnoreCase);
-
- public StringMapTypeDeserializer(Type type)
- {
- this.type = type;
-
- foreach (var propertyInfo in type.GetSerializableProperties())
- {
- var propertySetFn = JsvDeserializeType.GetSetPropertyMethod(type, propertyInfo);
+using System;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+using ServiceStack.Common;
+using ServiceStack.Common.Utils;
+using ServiceStack.Logging;
+using ServiceStack.Text;
+using ServiceStack.Text.Common;
+using ServiceStack.Text.Jsv;
+
+namespace ServiceStack.ServiceModel.Serialization
+{
+ /// <summary>
+ /// Serializer cache of delegates required to create a type from a string map (e.g. for REST urls)
+ /// </summary>
+ public class StringMapTypeDeserializer
+ {
+ private static readonly ILog Log = LogManager.GetLogger(typeof(StringMapTypeDeserializer));
+
+ internal class PropertySerializerEntry
+ {
+ public PropertySerializerEntry(SetPropertyDelegate propertySetFn, ParseStringDelegate propertyParseStringFn)
+ {
+ PropertySetFn = propertySetFn;
+ PropertyParseStringFn = propertyParseStringFn;
+ }
+
+ public SetPropertyDelegate PropertySetFn;
+ public ParseStringDelegate PropertyParseStringFn;
+ public Type PropertyType;
+ }
+
+ private readonly Type type;
+ private readonly Dictionary<string, PropertySerializerEntry> propertySetterMap
+ = new Dictionary<string, PropertySerializerEntry>(StringComparer.InvariantCultureIgnoreCase);
+
+ public StringMapTypeDeserializer(Type type)
+ {
+ this.type = type;
+
+ foreach (var propertyInfo in type.GetSerializableProperties())
+ {
+ var propertySetFn = JsvDeserializeType.GetSetPropertyMethod(type, propertyInfo);
var propertyType = propertyInfo.PropertyType;
var propertyParseStringFn = JsvReader.GetParseFn(propertyType);
- var propertySerializer = new PropertySerializerEntry(propertySetFn, propertyParseStringFn) { PropertyType = propertyType };
-
- var attr = propertyInfo.FirstAttribute<DataMemberAttribute>();
- if (attr != null && attr.Name != null)
- {
- propertySetterMap[attr.Name] = propertySerializer;
- }
- propertySetterMap[propertyInfo.Name] = propertySerializer;
- }
- }
-
- public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs)
- {
+ var propertySerializer = new PropertySerializerEntry(propertySetFn, propertyParseStringFn) { PropertyType = propertyType };
+
+ var attr = propertyInfo.FirstAttribute<DataMemberAttribute>();
+ if (attr != null && attr.Name != null)
+ {
+ propertySetterMap[attr.Name] = propertySerializer;
+ }
+ propertySetterMap[propertyInfo.Name] = propertySerializer;
+ }
+ }
+
+ public object PopulateFromMap(object instance, IDictionary<string, string> keyValuePairs)
+ {
string propertyName = null;
string propertyTextValue = null;
- PropertySerializerEntry propertySerializerEntry = null;
-
- try
- {
- if (instance == null) instance = ReflectionUtils.CreateInstance(type);
-
- foreach (var pair in keyValuePairs)
- {
+ PropertySerializerEntry propertySerializerEntry = null;
+
+ try
+ {
+ if (instance == null) instance = type.CreateInstance();
+
+ foreach (var pair in keyValuePairs)
+ {
propertyName = pair.Key;
- propertyTextValue = pair.Value;
-
- if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry))
- {
- if (propertyName != "format" && propertyName != "callback" && propertyName != "debug")
- {
- Log.WarnFormat("Property '{0}' does not exist on type '{1}'", propertyName, type.FullName);
- }
- continue;
- }
-
- var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue);
- if (value == null)
- {
- Log.WarnFormat("Could not create instance on '{0}' for property '{1}' with text value '{2}'",
- instance, propertyName, propertyTextValue);
- continue;
- }
- propertySerializerEntry.PropertySetFn(instance, value);
- }
- return instance;
-
- }
- catch (Exception ex)
- {
+ propertyTextValue = pair.Value;
+
+ if (!propertySetterMap.TryGetValue(propertyName, out propertySerializerEntry))
+ {
+ if (propertyName != "format" && propertyName != "callback" && propertyName != "debug")
+ {
+ Log.WarnFormat("Property '{0}' does not exist on type '{1}'", propertyName, type.FullName);
+ }
+ continue;
+ }
+
+ var value = propertySerializerEntry.PropertyParseStringFn(propertyTextValue);
+ if (value == null)
+ {
+ Log.WarnFormat("Could not create instance on '{0}' for property '{1}' with text value '{2}'",
+ instance, propertyName, propertyTextValue);
+ continue;
+ }
+ propertySerializerEntry.PropertySetFn(instance, value);
+ }
+ return instance;
+
+ }
+ catch (Exception ex)
+ {
var serializationException = new SerializationException("KeyValueDataContractDeserializer: Error converting to type: " + ex.Message, ex);
if (propertyName != null) {
serializationException.Data.Add("propertyName", propertyName);
@@ -101,14 +101,14 @@ public object PopulateFromMap(object instance, IDictionary<string, string> keyVa
}
if (propertySerializerEntry != null && propertySerializerEntry.PropertyType != null) {
serializationException.Data.Add("propertyType", propertySerializerEntry.PropertyType);
- }
- throw serializationException;
- }
- }
-
- public object CreateFromMap(IDictionary<string, string> keyValuePairs)
- {
- return PopulateFromMap(null, keyValuePairs);
- }
- }
+ }
+ throw serializationException;
+ }
+ }
+
+ public object CreateFromMap(IDictionary<string, string> keyValuePairs)
+ {
+ return PopulateFromMap(null, keyValuePairs);
+ }
+ }
}
854 src/ServiceStack.Common/Utils/ReflectionUtils.cs
View
@@ -1,423 +1,431 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Reflection.Emit;
-using ServiceStack.Common.Support;
-using ServiceStack.Logging;
-using ServiceStack.Net30.Collections.Concurrent;
-
-namespace ServiceStack.Common.Utils
-{
- public class ReflectionUtils
- {
- public static readonly ILog Log = LogManager.GetLogger(typeof(ReflectionUtils));
-
- /// <summary>
- /// Populate an object with Example data.
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static object PopulateObject(object obj)
- {
- if (obj == null) return null;
-
- return PopulateObjectInternal(obj, new Dictionary<Type, int>(20));
- }
-
- /// <summary>
- /// Populates the object with example data.
- /// </summary>
- /// <param name="obj"></param>
- /// <param name="recursionInfo">Tracks how deeply nested we are</param>
- /// <returns></returns>
- private static object PopulateObjectInternal(object obj, Dictionary<Type,int> recursionInfo)
- {
- if (obj == null) return null;
- if (obj is string) return obj; // prevents it from dropping into the char[] Chars property. Sheesh
-
- var members = obj.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
- foreach (var info in members)
- {
- var fieldInfo = info as FieldInfo;
- var propertyInfo = info as PropertyInfo;
- if (fieldInfo != null || propertyInfo != null)
- {
- var memberType = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType;
- var value = CreateDefaultValue(memberType, recursionInfo);
- SetValue(fieldInfo, propertyInfo, obj, value);
- }
- }
- return obj;
- }
-
- private static readonly Dictionary<Type, object> DefaultValueTypes
- = new Dictionary<Type, object>();
-
- public static object GetDefaultValue(Type type)
- {
- if (!type.IsValueType) return null;
-
- object defaultValue;
- lock (DefaultValueTypes)
- {
- if (!DefaultValueTypes.TryGetValue(type, out defaultValue))
- {
- defaultValue = Activator.CreateInstance(type);
- DefaultValueTypes[type] = defaultValue;
- }
- }
-
- return defaultValue;
- }
-
- private static readonly ConcurrentDictionary<string, AssignmentDefinition> AssignmentDefinitionCache
- = new ConcurrentDictionary<string, AssignmentDefinition>();
-
- public static AssignmentDefinition GetAssignmentDefinition(Type toType, Type fromType)
- {
- var cacheKey = toType.FullName + "<" + fromType.FullName;
-
- return AssignmentDefinitionCache.GetOrAdd(cacheKey, delegate {
-
- var definition = new AssignmentDefinition {
- ToType = toType,
- FromType = fromType,
- };
-
- var members = fromType.GetMembers(BindingFlags.Public | BindingFlags.Instance);
- foreach (var info in members)
- {
- var fromPropertyInfo = info as PropertyInfo;
- if (fromPropertyInfo != null)
- {
- var toPropertyInfo = GetPropertyInfo(toType, fromPropertyInfo.Name);
- if (toPropertyInfo == null) continue;
-
- if (!fromPropertyInfo.CanRead) continue;
- if (!toPropertyInfo.CanWrite) continue;
-
- definition.AddMatch(fromPropertyInfo, toPropertyInfo);
- }
-
- var fromFieldInfo = info as FieldInfo;
- if (fromFieldInfo != null)
- {
- var toFieldInfo = GetFieldInfo(toType, fromFieldInfo.Name);
- if (toFieldInfo == null) continue;
-
- definition.AddMatch(fromFieldInfo, toFieldInfo);
- }
- }
- return definition;
- });
-
- }
-
- public static To PopulateObject<To, From>(To to, From from)
- {
- if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
-
- var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
-
- assignmentDefinition.Populate(to, from);
-
- return to;
- }
-
- public static To PopulateWithNonDefaultValues<To, From>(To to, From from)
- {
- if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
-
- var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
-
- assignmentDefinition.PopulateWithNonDefaultValues(to, from);
-
- return to;
- }
-
- public static To PopulateFromPropertiesWithAttribute<To, From>(To to, From from,
- Type attributeType)
- {
- if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
-
- var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
-
- assignmentDefinition.PopulateFromPropertiesWithAttribute(to, from, attributeType);
-
- return to;
- }
-
- public static void SetProperty(object obj, PropertyInfo propertyInfo, object value)
- {
- if (!propertyInfo.CanWrite)
- {
- Log.WarnFormat("Attempted to set read only property '{0}'", propertyInfo.Name);
- return;
- }
- var propertySetMetodInfo = propertyInfo.GetSetMethod();
- if (propertySetMetodInfo != null)
- {
- propertySetMetodInfo.Invoke(obj, new[] { value });
- }
- }
-
- public static object GetProperty(object obj, PropertyInfo propertyInfo)
- {
- if (propertyInfo == null || !propertyInfo.CanRead)
- return null;
-
- var getMethod = propertyInfo.GetGetMethod();
- return getMethod != null ? getMethod.Invoke(obj, new object[0]) : null;
- }
-
- public static void SetValue(FieldInfo fieldInfo, PropertyInfo propertyInfo, object obj, object value)
- {
- try
- {
- if (IsUnsettableValue(fieldInfo, propertyInfo)) return;
- if (fieldInfo != null && !fieldInfo.IsLiteral)
- {
- fieldInfo.SetValue(obj, value);
- }
- else
- {
- SetProperty(obj, propertyInfo, value);
- }
- }
- catch (Exception ex)
- {
- var name = (fieldInfo != null) ? fieldInfo.Name : propertyInfo.Name;
- Log.DebugFormat("Could not set member: {0}. Error: {1}", name, ex.Message);
- }
- }
-
- public static bool IsUnsettableValue(FieldInfo fieldInfo, PropertyInfo propertyInfo)
- {
- if (propertyInfo != null && propertyInfo.ReflectedType != null)
- {
- // Properties on non-user defined classes should not be set
- // Currently we define those properties as properties declared on
- // types defined in mscorlib
-
- if (propertyInfo.DeclaringType.Assembly == typeof(object).Assembly)
- {
- return true;
- }
- }
-
- return false;
- }
-
- public static object[] CreateDefaultValues(IEnumerable<Type> types, Dictionary<Type, int> recursionInfo)
- {
- var values = new List<object>();
- foreach (var type in types)
- {
- values.Add(CreateDefaultValue(type, recursionInfo));
- }
- return values.ToArray();
- }
-
- private const int MaxRecursionLevelForDefaultValues = 2; // do not nest a single type more than this deep.
-
- public static object CreateDefaultValue(Type type, Dictionary<Type, int> recursionInfo)
- {
- if (type == typeof(string))
- {
- return type.Name;
- }
-
- if (type.IsEnum)
- {
-#if SILVERLIGHT4
- return Enum.ToObject(type, 0);
-#else
- return Enum.GetValues(type).GetValue(0);
-#endif
- }
-
- // If we have hit our recursion limit for this type, then return null
- int recurseLevel; // will get set to 0 if TryGetValue() fails
- recursionInfo.TryGetValue(type, out recurseLevel);
- if (recurseLevel > MaxRecursionLevelForDefaultValues) return null;
-
- recursionInfo[type] = recurseLevel + 1; // increase recursion level for this type
- try // use a try/finally block to make sure we decrease the recursion level for this type no matter which code path we take,
- {
-
- //when using KeyValuePair<TKey, TValue>, TKey must be non-default to stuff in a Dictionary
- if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
- {
- var genericTypes = type.GetGenericArguments();
- var valueType = Activator.CreateInstance(type, CreateDefaultValue(genericTypes[0], recursionInfo), CreateDefaultValue(genericTypes[1], recursionInfo));
- return PopulateObjectInternal(valueType, recursionInfo);
- }
-
- if (type.IsValueType)
- {
- return Activator.CreateInstance(type);
- }
-
- if (type.IsArray)
- {
- return PopulateArray(type, recursionInfo);
- }
-
- var constructorInfo = type.GetConstructor(Type.EmptyTypes);
- var hasEmptyConstructor = constructorInfo != null;
-
- if (hasEmptyConstructor)
- {
- var value = constructorInfo.Invoke(new object[0]);
-
-#if !SILVERLIGHT && !MONOTOUCH && !XBOX
-
- Type[] interfaces = type.FindInterfaces((t, critera) =>
- t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>)
- , null);
-
- bool isGenericCollection = interfaces.Length > 0;
-
- if (isGenericCollection)
- {
- SetGenericCollection(interfaces[0], value, recursionInfo);
- }
-#endif
-
- //when the object might have nested properties such as enums with non-0 values, etc
- return PopulateObjectInternal(value, recursionInfo);
- }
- return null;
- }
- finally
- {
- recursionInfo[type] = recurseLevel;
- }
- }
-
- public static void SetGenericCollection(Type realisedListType, object genericObj, Dictionary<Type, int> recursionInfo)
- {
- var args = realisedListType.GetGenericArguments();
-
- if (args.Length != 1)
- {
- Log.ErrorFormat("Found a generic list that does not take one generic argument: {0}", realisedListType);
-
- return;
- }
-
- var methodInfo = realisedListType.GetMethod("Add");
-
- if (methodInfo != null)
- {
- var argValues = CreateDefaultValues(args, recursionInfo);
-
- methodInfo.Invoke(genericObj, argValues);
- }
- }
-
- public static Array PopulateArray(Type type, Dictionary<Type, int> recursionInfo)
- {
- var elementType = type.GetElementType();
- var objArray = Array.CreateInstance(elementType, 1);
- var objElementType = CreateDefaultValue(elementType, recursionInfo);
- objArray.SetValue(objElementType, 0);
-
- return objArray;
- }
-
- //TODO: replace with InAssignableFrom
- public static bool CanCast(Type toType, Type fromType)
- {
- if (toType.IsInterface)
- {
- var interfaceList = fromType.GetInterfaces().ToList();
- if (interfaceList.Contains(toType)) return true;
- }
- else
- {
- Type baseType = fromType;
- bool areSameTypes;
- do
- {
- areSameTypes = baseType == toType;
- }
- while (!areSameTypes && (baseType = fromType.BaseType) != null);
-
- if (areSameTypes) return true;
- }
-
- return false;
- }
-
- public static MemberInfo GetMemberInfo(Type fromType, string memberName)
- {
- var baseType = fromType;
- do
- {
- var members = baseType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
- foreach (var memberInfo in members)
- {
- if (memberInfo.Name == memberName) return memberInfo;
- }
- }
- while ((baseType = baseType.BaseType) != null);
- return null;
- }
-
- public static FieldInfo GetFieldInfo(Type fromType, string fieldName)
- {
- var baseType = fromType;
- do
- {
- var fieldInfos = baseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
- foreach (var fieldInfo in fieldInfos)
- {
- if (fieldInfo.Name == fieldName) return fieldInfo;
- }
- }
- while ((baseType = baseType.BaseType) != null);
- return null;
- }
-
- public static PropertyInfo GetPropertyInfo(Type fromType, string propertyName)
- {
- var baseType = fromType;
- do
- {
- var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
- foreach (var propertyInfo in propertyInfos)
- {
- if (propertyInfo.Name == propertyName) return propertyInfo;
- }
- }
- while ((baseType = baseType.BaseType) != null);
- return null;
- }
-
- public static IEnumerable<KeyValuePair<PropertyInfo, T>> GetPropertyAttributes<T>(Type fromType) where T : Attribute
- {
- var attributeType = typeof(T);
- var baseType = fromType;
- do
- {
- var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
- foreach (var propertyInfo in propertyInfos)
- {
- var attributes = propertyInfo.GetCustomAttributes(attributeType, true);
- foreach (T attribute in attributes)
- {
- yield return new KeyValuePair<PropertyInfo, T>(propertyInfo, attribute);
- }
- }
- }
- while ((baseType = baseType.BaseType) != null);
- }
-
- public static object CreateInstance(Type type)
- {
- return Text.ReflectionExtensions.CreateInstance(type);
- }
- }
-}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Reflection.Emit;
+using ServiceStack.Common.Support;
+using ServiceStack.Logging;
+using ServiceStack.Net30.Collections.Concurrent;
+using ServiceStack.Text;
+
+namespace ServiceStack.Common.Utils
+{
+ public class ReflectionUtils
+ {
+ public static readonly ILog Log = LogManager.GetLogger(typeof(ReflectionUtils));
+
+ /// <summary>
+ /// Populate an object with Example data.
+ /// </summary>
+ /// <param name="obj"></param>
+ /// <returns></returns>
+ public static object PopulateObject(object obj)
+ {
+ if (obj == null) return null;
+
+ var type = obj.GetType();
+ if (type.IsArray || type.IsValueType || type.IsGenericType)
+ {
+ var value = CreateDefaultValue(type, new Dictionary<Type, int>(20));
+ return value;
+ }
+
+ return PopulateObjectInternal(obj, new Dictionary<Type, int>(20));
+ }
+
+ /// <summary>
+ /// Populates the object with example data.
+ /// </summary>
+ /// <param name="obj"></param>
+ /// <param name="recursionInfo">Tracks how deeply nested we are</param>
+ /// <returns></returns>
+ private static object PopulateObjectInternal(object obj, Dictionary<Type,int> recursionInfo)
+ {
+ if (obj == null) return null;
+ if (obj is string) return obj; // prevents it from dropping into the char[] Chars property. Sheesh
+ var type = obj.GetType();
+
+ var members = type.GetMembers(BindingFlags.Public | BindingFlags.Instance);
+ foreach (var info in members)
+ {
+ var fieldInfo = info as FieldInfo;
+ var propertyInfo = info as PropertyInfo;
+ if (fieldInfo != null || propertyInfo != null)
+ {
+ var memberType = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType;
+ var value = CreateDefaultValue(memberType, recursionInfo);
+ SetValue(fieldInfo, propertyInfo, obj, value);
+ }
+ }
+ return obj;
+ }
+
+ private static readonly Dictionary<Type, object> DefaultValueTypes
+ = new Dictionary<Type, object>();
+
+ public static object GetDefaultValue(Type type)
+ {
+ if (!type.IsValueType) return null;
+
+ object defaultValue;
+ lock (DefaultValueTypes)
+ {
+ if (!DefaultValueTypes.TryGetValue(type, out defaultValue))
+ {
+ defaultValue = Activator.CreateInstance(type);
+ DefaultValueTypes[type] = defaultValue;
+ }
+ }
+
+ return defaultValue;
+ }
+
+ private static readonly ConcurrentDictionary<string, AssignmentDefinition> AssignmentDefinitionCache
+ = new ConcurrentDictionary<string, AssignmentDefinition>();
+
+ public static AssignmentDefinition GetAssignmentDefinition(Type toType, Type fromType)
+ {
+ var cacheKey = toType.FullName + "<" + fromType.FullName;
+
+ return AssignmentDefinitionCache.GetOrAdd(cacheKey, delegate {
+
+ var definition = new AssignmentDefinition {
+ ToType = toType,
+ FromType = fromType,
+ };
+
+ var members = fromType.GetMembers(BindingFlags.Public | BindingFlags.Instance);
+ foreach (var info in members)
+ {
+ var fromPropertyInfo = info as PropertyInfo;
+ if (fromPropertyInfo != null)
+ {
+ var toPropertyInfo = GetPropertyInfo(toType, fromPropertyInfo.Name);
+ if (toPropertyInfo == null) continue;
+
+ if (!fromPropertyInfo.CanRead) continue;
+ if (!toPropertyInfo.CanWrite) continue;
+
+ definition.AddMatch(fromPropertyInfo, toPropertyInfo);
+ }
+
+ var fromFieldInfo = info as FieldInfo;
+ if (fromFieldInfo != null)
+ {
+ var toFieldInfo = GetFieldInfo(toType, fromFieldInfo.Name);
+ if (toFieldInfo == null) continue;
+
+ definition.AddMatch(fromFieldInfo, toFieldInfo);
+ }
+ }
+ return definition;
+ });
+
+ }
+
+ public static To PopulateObject<To, From>(To to, From from)
+ {
+ if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
+
+ var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
+
+ assignmentDefinition.Populate(to, from);
+
+ return to;
+ }
+
+ public static To PopulateWithNonDefaultValues<To, From>(To to, From from)
+ {
+ if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
+
+ var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
+
+ assignmentDefinition.PopulateWithNonDefaultValues(to, from);
+
+ return to;
+ }
+
+ public static To PopulateFromPropertiesWithAttribute<To, From>(To to, From from,
+ Type attributeType)
+ {
+ if (Equals(to, default(To)) || Equals(from, default(From))) return default(To);
+
+ var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType());
+
+ assignmentDefinition.PopulateFromPropertiesWithAttribute(to, from, attributeType);
+
+ return to;
+ }
+
+ public static void SetProperty(object obj, PropertyInfo propertyInfo, object value)
+ {
+ if (!propertyInfo.CanWrite)
+ {
+ Log.WarnFormat("Attempted to set read only property '{0}'", propertyInfo.Name);
+ return;
+ }
+ var propertySetMetodInfo = propertyInfo.GetSetMethod();
+ if (propertySetMetodInfo != null)
+ {
+ propertySetMetodInfo.Invoke(obj, new[] { value });
+ }
+ }
+
+ public static object GetProperty(object obj, PropertyInfo propertyInfo)
+ {
+ if (propertyInfo == null || !propertyInfo.CanRead)
+ return null;
+
+ var getMethod = propertyInfo.GetGetMethod();
+ return getMethod != null ? getMethod.Invoke(obj, new object[0]) : null;
+ }
+
+ public static void SetValue(FieldInfo fieldInfo, PropertyInfo propertyInfo, object obj, object value)
+ {
+ try
+ {
+ if (IsUnsettableValue(fieldInfo, propertyInfo)) return;
+ if (fieldInfo != null && !fieldInfo.IsLiteral)
+ {
+ fieldInfo.SetValue(obj, value);
+ }
+ else
+ {
+ SetProperty(obj, propertyInfo, value);
+ }
+ }
+ catch (Exception ex)
+ {
+ var name = (fieldInfo != null) ? fieldInfo.Name : propertyInfo.Name;
+ Log.DebugFormat("Could not set member: {0}. Error: {1}", name, ex.Message);
+ }
+ }
+
+ public static bool IsUnsettableValue(FieldInfo fieldInfo, PropertyInfo propertyInfo)
+ {
+ if (propertyInfo != null && propertyInfo.ReflectedType != null)
+ {
+ // Properties on non-user defined classes should not be set
+ // Currently we define those properties as properties declared on
+ // types defined in mscorlib
+
+ if (propertyInfo.DeclaringType.Assembly == typeof(object).Assembly)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static object[] CreateDefaultValues(IEnumerable<Type> types, Dictionary<Type, int> recursionInfo)
+ {
+ var values = new List<object>();
+ foreach (var type in types)
+ {
+ values.Add(CreateDefaultValue(type, recursionInfo));
+ }
+ return values.ToArray();
+ }
+
+ private const int MaxRecursionLevelForDefaultValues = 2; // do not nest a single type more than this deep.
+
+ public static object CreateDefaultValue(Type type, Dictionary<Type, int> recursionInfo)
+ {
+ if (type == typeof(string))
+ {
+ return type.Name;
+ }
+
+ if (type.IsEnum)
+ {
+#if SILVERLIGHT4
+ return Enum.ToObject(type, 0);
+#else
+ return Enum.GetValues(type).GetValue(0);
+#endif
+ }
+
+ // If we have hit our recursion limit for this type, then return null
+ int recurseLevel; // will get set to 0 if TryGetValue() fails
+ recursionInfo.TryGetValue(type, out recurseLevel);
+ if (recurseLevel > MaxRecursionLevelForDefaultValues) return null;
+
+ recursionInfo[type] = recurseLevel + 1; // increase recursion level for this type
+ try // use a try/finally block to make sure we decrease the recursion level for this type no matter which code path we take,
+ {
+
+ //when using KeyValuePair<TKey, TValue>, TKey must be non-default to stuff in a Dictionary
+ if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
+ {
+ var genericTypes = type.GetGenericArguments();
+ var valueType = Activator.CreateInstance(type, CreateDefaultValue(genericTypes[0], recursionInfo), CreateDefaultValue(genericTypes[1], recursionInfo));
+ return PopulateObjectInternal(valueType, recursionInfo);
+ }
+
+ if (type.IsValueType)
+ {
+ return type.CreateInstance();
+ }
+
+ if (type.IsArray)
+ {
+ return PopulateArray(type, recursionInfo);
+ }
+
+ var constructorInfo = type.GetConstructor(Type.EmptyTypes);
+ var hasEmptyConstructor = constructorInfo != null;
+
+ if (hasEmptyConstructor)
+ {
+ var value = constructorInfo.Invoke(new object[0]);
+
+#if !SILVERLIGHT && !MONOTOUCH && !XBOX
+
+ var genericCollectionType = GetGenericCollectionType(type);
+ if (genericCollectionType != null)
+ {
+ SetGenericCollection(genericCollectionType, value, recursionInfo);
+ }
+#endif
+
+ //when the object might have nested properties such as enums with non-0 values, etc
+ return PopulateObjectInternal(value, recursionInfo);
+ }
+ return null;
+ }
+ finally
+ {
+ recursionInfo[type] = recurseLevel;
+ }
+ }
+
+ private static Type GetGenericCollectionType(Type type)
+ {
+ var genericCollectionType = type.FindInterfaces((t, critera) =>
+ t.IsGenericType
+ && t.GetGenericTypeDefinition() == typeof (ICollection<>), null).FirstOrDefault();
+
+ return genericCollectionType;
+ }
+
+ public static void SetGenericCollection(Type realisedListType, object genericObj, Dictionary<Type, int> recursionInfo)
+ {
+ var args = realisedListType.GetGenericArguments();
+
+ if (args.Length != 1)
+ {
+ Log.ErrorFormat("Found a generic list that does not take one generic argument: {0}", realisedListType);
+
+ return;
+ }
+
+ var methodInfo = realisedListType.GetMethod("Add");
+
+ if (methodInfo != null)
+ {
+ var argValues = CreateDefaultValues(args, recursionInfo);
+
+ methodInfo.Invoke(genericObj, argValues);
+ }
+ }
+
+ public static Array PopulateArray(Type type, Dictionary<Type, int> recursionInfo)
+ {
+ var elementType = type.GetElementType();
+ var objArray = Array.CreateInstance(elementType, 1);
+ var objElementType = CreateDefaultValue(elementType, recursionInfo);
+ objArray.SetValue(objElementType, 0);
+
+ return objArray;
+ }
+
+ //TODO: replace with InAssignableFrom
+ public static bool CanCast(Type toType, Type fromType)
+ {
+ if (toType.IsInterface)
+ {
+ var interfaceList = fromType.GetInterfaces().ToList();
+ if (interfaceList.Contains(toType)) return true;
+ }
+ else
+ {
+ Type baseType = fromType;
+ bool areSameTypes;
+ do
+ {
+ areSameTypes = baseType == toType;
+ }
+ while (!areSameTypes && (baseType = fromType.BaseType) != null);
+
+ if (areSameTypes) return true;
+ }
+
+ return false;
+ }
+
+ public static MemberInfo GetMemberInfo(Type fromType, string memberName)
+ {
+ var baseType = fromType;
+ do
+ {
+ var members = baseType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ foreach (var memberInfo in members)
+ {
+ if (memberInfo.Name == memberName) return memberInfo;
+ }
+ }
+ while ((baseType = baseType.BaseType) != null);
+ return null;
+ }
+
+ public static FieldInfo GetFieldInfo(Type fromType, string fieldName)
+ {
+ var baseType = fromType;
+ do
+ {
+ var fieldInfos = baseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ foreach (var fieldInfo in fieldInfos)
+ {
+ if (fieldInfo.Name == fieldName) return fieldInfo;
+ }
+ }
+ while ((baseType = baseType.BaseType) != null);
+ return null;
+ }
+
+ public static PropertyInfo GetPropertyInfo(Type fromType, string propertyName)
+ {
+ var baseType = fromType;
+ do
+ {
+ var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ foreach (var propertyInfo in propertyInfos)
+ {
+ if (propertyInfo.Name == propertyName) return propertyInfo;
+ }
+ }
+ while ((baseType = baseType.BaseType) != null);
+ return null;
+ }
+
+ public static IEnumerable<KeyValuePair<PropertyInfo, T>> GetPropertyAttributes<T>(Type fromType) where T : Attribute
+ {
+ var attributeType = typeof(T);
+ var baseType = fromType;
+ do
+ {
+ var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ foreach (var propertyInfo in propertyInfos)
+ {
+ var attributes = propertyInfo.GetCustomAttributes(attributeType, true);
+ foreach (T attribute in attributes)
+ {
+ yield return new KeyValuePair<PropertyInfo, T>(propertyInfo, attribute);
+ }
+ }
+ }
+ while ((baseType = baseType.BaseType) != null);
+ }
+ }
+}
433 src/ServiceStack.Common/Web/ContentType.cs
View
@@ -1,210 +1,229 @@
-using System;
-using ServiceStack.ServiceHost;
-using ServiceStack.Text;
-
-namespace ServiceStack.Common.Web
-{
- public static class ContentType
- {
- public const string Utf8Suffix = "; charset=utf-8";
-
- public const string HeaderContentType = "Content-Type";
-
- public const string FormUrlEncoded = "application/x-www-form-urlencoded";
-
- public const string MultiPartFormData = "multipart/form-data";
-
- public const string Html = "text/html";
-
- public const string JsonReport = "text/jsonreport";
-
- public const string Xml = "application/xml";
-
- public const string XmlText = "text/xml";
-
- public const string Soap11 = " text/xml; charset=utf-8";
-
- public const string Soap12 = " application/soap+xml";
-
- public const string Json = "application/json";
-
- public const string JsonText = "text/json";
-
- public const string JavaScript = "application/javascript";
-
- public const string Jsv = "application/jsv";
-
- public const string JsvText = "text/jsv";
-
- public const string Csv = "text/csv";
-
- public const string Yaml = "application/yaml";
-
- public const string YamlText = "text/yaml";
-
- public const string PlainText = "text/plain";
-
- public const string MarkdownText = "text/markdown";
-
- public const string ProtoBuf = "application/x-protobuf";
-
- public const string MsgPack = "application/x-msgpack";
-
- public const string Bson = "application/bson";
-
- public const string Binary = "application/octet-stream";
-
- public static EndpointAttributes GetEndpointAttributes(string contentType)
- {
- if (contentType == null)
- return EndpointAttributes.None;
-
- var realContentType = GetRealContentType(contentType);
- switch (realContentType)
- {
- case Json:
- case JsonText:
- return EndpointAttributes.Json;
-
- case Xml:
- case XmlText:
- return EndpointAttributes.Xml;
-
- case Html:
- return EndpointAttributes.Html;
-
- case Jsv:
- case JsvText:
- return EndpointAttributes.Jsv;
-
- case Yaml:
- case YamlText:
- return EndpointAttributes.Yaml;
-
- case Csv:
- return EndpointAttributes.Csv;
-
- case Soap11:
- return EndpointAttributes.Soap11;
-
- case Soap12:
- return EndpointAttributes.Soap12;
- }
-
- return EndpointAttributes.None;
- }
-
- public static string GetRealContentType(string contentType)
- {
+using System;
+using ServiceStack.ServiceHost;
+using ServiceStack.Text;
+
+namespace ServiceStack.Common.Web
+{
+ public static class ContentType
+ {
+ public const string Utf8Suffix = "; charset=utf-8";
+
+ public const string HeaderContentType = "Content-Type";
+
+ public const string FormUrlEncoded = "application/x-www-form-urlencoded";
+
+ public const string MultiPartFormData = "multipart/form-data";
+
+ public const string Html = "text/html";
+
+ public const string JsonReport = "text/jsonreport";
+
+ public const string Xml = "application/xml";
+
+ public const string XmlText = "text/xml";
+
+ public const string Soap11 = " text/xml; charset=utf-8";
+
+ public const string Soap12 = " application/soap+xml";
+
+ public const string Json = "application/json";
+
+ public const string JsonText = "text/json";
+
+ public const string JavaScript = "application/javascript";
+
+ public const string Jsv = "application/jsv";
+
+ public const string JsvText = "text/jsv";
+
+ public const string Csv = "text/csv";
+
+ public const string Yaml = "application/yaml";
+
+ public const string YamlText = "text/yaml";
+
+ public const string PlainText = "text/plain";
+
+ public const string MarkdownText = "text/markdown";
+
+ public const string ProtoBuf = "application/x-protobuf";
+
+ public const string MsgPack = "application/x-msgpack";
+
+ public const string Bson = "application/bson";
+
+ public const string Binary = "application/octet-stream";
+
+ public static EndpointAttributes GetEndpointAttributes(string contentType)
+ {
+ if (contentType == null)
+ return EndpointAttributes.None;
+
+ var realContentType = GetRealContentType(contentType);
+ switch (realContentType)
+ {
+ case Json:
+ case JsonText:
+ return EndpointAttributes.Json;
+
+ case Xml:
+ case XmlText:
+ return EndpointAttributes.Xml;
+
+ case Html:
+ return EndpointAttributes.Html;
+
+ case Jsv:
+ case JsvText:
+ return EndpointAttributes.Jsv;
+
+ case Yaml:
+ case YamlText:
+ return EndpointAttributes.Yaml;
+
+ case Csv:
+ return EndpointAttributes.Csv;
+
+ case Soap11:
+ return EndpointAttributes.Soap11;
+
+ case Soap12:
+ return EndpointAttributes.Soap12;
+
+ case ProtoBuf:
+ return EndpointAttributes.ProtoBuf;
+
+ case MsgPack:
+ return EndpointAttributes.MsgPack;
+
+ }
+
+ return EndpointAttributes.None;
+ }
+
+ public static string GetRealContentType(string contentType)
+ {
return contentType == null
? null
- : contentType.Split(';')[0].Trim();
- }
-
- public static bool MatchesContentType(this string contentType, string matchesContentType)
- {
- return GetRealContentType(contentType) == GetRealContentType(matchesContentType);
- }
-
- public static bool IsBinary(this string contentType)
- {
- var realContentType = GetRealContentType(contentType);
- switch (realContentType)
- {
- case ProtoBuf:
- case MsgPack:
- case Binary:
- case Bson:
- return true;
- }
-
- var primaryType = realContentType.SplitOnFirst('/')[0];
- switch (primaryType)
- {
- case "image":
- case "audio":
- case "video":
- return true;
- }
-
- return false;
- }
-
- public static Feature GetFeature(string contentType)
- {
- if (contentType == null)
- return Feature.None;
-
- var realContentType = GetRealContentType(contentType);
- switch (realContentType)
- {
- case Json:
- case JsonText:
- return Feature.Json;
-
- case Xml:
- case XmlText:
- return Feature.Xml;
-
- case Html:
- return Feature.Html;
-
- case Jsv:
- case JsvText:
- return Feature.Jsv;
-
- case Csv:
- return Feature.Csv;
-
- case Soap11:
- return Feature.Soap11;
-
- case Soap12:
- return Feature.Soap12;
- }
-
- return Feature.None;
- }
-
- public static string GetContentFormat(EndpointType endpointType)
- {
- return endpointType.ToString().ToLower();
- }
-
- public static string GetContentFormat(string contentType)
- {
- if (contentType == null) return contentType;
- var parts = contentType.Split('/');
- return parts[parts.Length - 1];
- }
-
- public static string ToContentFormat(this string contentType)
- {
- return GetContentFormat(contentType);
- }
-
- public static string GetContentType(EndpointType endpointType)
- {
- switch (endpointType)
- {
- case EndpointType.Soap11:
- case EndpointType.Soap12:
- case EndpointType.Xml:
- return Xml;
-
- case EndpointType.Json:
- return Json;
-
- case EndpointType.Jsv:
- return JsvText;
-
- case EndpointType.ProtoBuf:
- return ProtoBuf;
-
- default:
- return null;
- }
- }
- }
-
+ : contentType.Split(';')[0].Trim();
+ }
+
+ public static bool MatchesContentType(this string contentType, string matchesContentType)
+ {
+ return GetRealContentType(contentType) == GetRealContentType(matchesContentType);
+ }
+
+ public static bool IsBinary(this string contentType)
+ {
+ var realContentType = GetRealContentType(contentType);
+ switch (realContentType)
+ {
+ case ProtoBuf:
+ case MsgPack:
+ case Binary:
+ case Bson:
+ return true;
+ }
+
+ var primaryType = realContentType.SplitOnFirst('/')[0];
+ switch (primaryType)
+ {
+ case "image":
+ case "audio":
+ case "video":
+ return true;
+ }
+
+ return false;
+ }
+
+ public static Feature GetFeature(string contentType)
+ {
+ if (contentType == null)
+ return Feature.None;
+
+ var realContentType = GetRealContentType(contentType);
+ switch (realContentType)
+ {
+ case Json:
+ case JsonText:
+ return Feature.Json;
+
+ case Xml:
+ case XmlText:
+ return Feature.Xml;
+
+ case Html:
+ return Feature.Html;
+
+ case Jsv:
+ case JsvText:
+ return Feature.Jsv;
+
+ case Csv:
+ return Feature.Csv;
+
+ case Soap11:
+ return Feature.Soap11;
+
+ case Soap12:
+ return Feature.Soap12;
+
+ case ProtoBuf:
+ return Feature.ProtoBuf;
+
+ case MsgPack:
+ return Feature.MsgPack;
+ }
+
+ return Feature.None;
+ }
+
+ public static string GetContentFormat(EndpointType endpointType)
+ {
+ return endpointType.ToString().ToLower();
+ }
+
+ public static string GetContentFormat(string contentType)
+ {
+ if (contentType == null) return contentType;
+ var parts = contentType.Split('/');
+ return parts[parts.Length - 1];
+ }
+
+ public static string ToContentFormat(this string contentType)
+ {
+ return GetContentFormat(contentType);
+ }
+
+ public static string GetContentType(EndpointType endpointType)
+ {
+ switch (endpointType)
+ {
+ case EndpointType.Soap11:
+ case EndpointType.Soap12:
+ case EndpointType.Xml:
+ return Xml;
+
+ case EndpointType.Json:
+ return Json;
+
+ case EndpointType.Jsv:
+ return JsvText;
+
+ case EndpointType.Csv:
+ return Csv;
+
+ case EndpointType.ProtoBuf:
+ return ProtoBuf;
+
+ case EndpointType.MsgPack:
+ return MsgPack;
+
+ default:
+ return null;
+ }
+ }
+ }
+
}
27 src/ServiceStack.Common/Web/EndpointType.cs
View
@@ -1,14 +1,15 @@
-namespace ServiceStack.Common.Web
-{
- public enum EndpointType
- {
- None,
- Xml,
- Json,
- Jsv,
- Csv,
- ProtoBuf,
- Soap11,
- Soap12,
- }
+namespace ServiceStack.Common.Web
+{
+ public enum EndpointType
+ {
+ None,
+ Xml,
+ Json,
+ Jsv,
+ Csv,
+ ProtoBuf,
+ MsgPack,
+ Soap11,
+ Soap12,
+ }
}
145 src/ServiceStack.FluentValidation.Mvc3/Mvc/ExecuteServiceStackFiltersAttribute.cs
View
@@ -1,74 +1,73 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web;
-using System.Web.Mvc;
-using System.Web.Routing;
-using ServiceStack.ServiceInterface;
-using ServiceStack.ServiceInterface.Auth;
-using ServiceStack.Text;
-
-namespace ServiceStack.Mvc
-{
- public class ExecuteServiceStackFiltersAttribute : ActionFilterAttribute
- {
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- var ssController = filterContext.Controller as ServiceStackController;
- if (ssController == null) return;
-
- var authAttrs = GetActionAndControllerAttributes<AuthenticateAttribute>(filterContext);
- if (authAttrs.Count > 0 && ( ssController.AuthSession==null || !ssController.AuthSession.IsAuthenticated))
- {
- var returnUrl = filterContext.HttpContext.Request.Url.AbsolutePath;
- returnUrl += filterContext.HttpContext.Request.QueryString;
- filterContext.Result = new RedirectResult(ssController.LoginRedirectUrl.Fmt(returnUrl));
- return;
- }
-
- var roleAttrs = GetActionAndControllerAttributes<RequiredRoleAttribute>(filterContext);
- var permAttrs = GetActionAndControllerAttributes<RequiredPermissionAttribute>(filterContext);
-
- if (roleAttrs.Count == 0 && permAttrs.Count == 0) return;
-
- var httpReq = HttpContext.Current.Request.ToRequest();
- var userAuthRepo = httpReq.TryResolve<IUserAuthRepository>();
-
- var hasRoles = roleAttrs.All(x => x.HasAllRoles(httpReq, ssController.AuthSession, userAuthRepo));
- if (!hasRoles)
- {
- filterContext.Result = ssController.AuthorizationErrorResult;
- return;
- }
-
- var hasPermssions = permAttrs.All(x => x.HasAllPermissions(httpReq, ssController.AuthSession, userAuthRepo));
- if (!hasPermssions)
- {
- filterContext.Result = ssController.AuthorizationErrorResult;
- return;
- }
- }
-
- private static List<T> GetActionAndControllerAttributes<T>(ActionExecutingContext filterContext)
- where T : Attribute
- {
- var attrs = new List<T>();
-
- var attr = filterContext.ActionDescriptor
- .GetCustomAttributes(typeof(T), true)
- .FirstOrDefault() as T;
-
- if (attr != null)
- attrs.Add(attr);
-
- attr = filterContext.Controller.GetType()
- .GetCustomAttributes(typeof(T), true)
- .FirstOrDefault() as T;
-
- if (attr != null)
- attrs.Add(attr);
-
- return attrs;
- }
- }
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.Mvc;
+using System.Web.Routing;
+using ServiceStack.ServiceInterface;
+using ServiceStack.ServiceInterface.Auth;
+using ServiceStack.Text;
+
+namespace ServiceStack.Mvc
+{
+ public class ExecuteServiceStackFiltersAttribute : ActionFilterAttribute
+ {
+ public override void OnActionExecuting(ActionExecutingContext filterContext)
+ {
+ var ssController = filterContext.Controller as ServiceStackController;
+ if (ssController == null) return;
+
+ var authAttrs = GetActionAndControllerAttributes<AuthenticateAttribute>(filterContext);
+ if (authAttrs.Count > 0 && ( ssController.AuthSession==null || !ssController.AuthSession.IsAuthenticated))
+ {
+ var returnUrl = filterContext.HttpContext.Request.Url.PathAndQuery;
+ filterContext.Result = new RedirectResult(ssController.LoginRedirectUrl.Fmt(HttpUtility.UrlEncode(returnUrl)));
+ return;
+ }
+
+ var roleAttrs = GetActionAndControllerAttributes<RequiredRoleAttribute>(filterContext);
+ var permAttrs = GetActionAndControllerAttributes<RequiredPermissionAttribute>(filterContext);
+
+ if (roleAttrs.Count == 0 && permAttrs.Count == 0) return;
+
+ var httpReq = HttpContext.Current.Request.ToRequest();
+ var userAuthRepo = httpReq.TryResolve<IUserAuthRepository>();
+
+ var hasRoles = roleAttrs.All(x => x.HasAllRoles(httpReq, ssController.AuthSession, userAuthRepo));
+ if (!hasRoles)
+ {
+ filterContext.Result = ssController.AuthorizationErrorResult;
+ return;
+ }
+
+ var hasPermssions = permAttrs.All(x => x.HasAllPermissions(httpReq, ssController.AuthSession, userAuthRepo));
+ if (!hasPermssions)
+ {
+ filterContext.Result = ssController.AuthorizationErrorResult;
+ return;
+ }
+ }
+
+ private static List<T> GetActionAndControllerAttributes<T>(ActionExecutingContext filterContext)
+ where T : Attribute
+ {
+ var attrs = new List<T>();
+
+ var attr = filterContext.ActionDescriptor
+ .GetCustomAttributes(typeof(T), true)
+ .FirstOrDefault() as T;
+
+ if (attr != null)
+ attrs.Add(attr);
+
+ attr = filterContext.Controller.GetType()
+ .GetCustomAttributes(typeof(T), true)
+ .FirstOrDefault() as T;
+
+ if (attr != null)
+ attrs.Add(attr);
+
+ return attrs;
+ }
+ }
}
9 src/ServiceStack.Interfaces/ServiceHost/EndpointAttributes.cs
View
@@ -31,8 +31,8 @@ public enum EndpointAttributes
HttpPost = 1 << 7,
HttpPut = 1 << 8,
HttpDelete = 1 << 9,
- HttpPatch = 1 << 10,
- HttpOptions = 1 << 11,
+ HttpPatch = 1 << 10,
+ HttpOptions = 1 << 11,
//Future 12
//Call Styles
@@ -56,7 +56,8 @@ public enum EndpointAttributes
Html = 1 << 22,
Yaml = 1 << 23,
- MessageQueue = 1 << 24,
- }
+ MsgPack = 1 << 24,
+ MessageQueue = 1 << 25,
+ }
}
126 src/ServiceStack.Interfaces/ServiceHost/EndpointAttributes.cs.orig
View
@@ -0,0 +1,126 @@
+<<<<<<< HEAD
+using System;
+
+namespace ServiceStack.ServiceHost
+{
+ [Flags]
+ public enum EndpointAttributes
+ {
+ None = 0,
+
+ All = AllNetworkAccessTypes | AllSecurityModes | AllHttpMethods | AllCallStyles | AllEndpointTypes,
+ AllNetworkAccessTypes = External | Localhost | LocalSubnet,
+ AllSecurityModes = Secure | InSecure,
+ AllHttpMethods = HttpHead | HttpGet | HttpPost | HttpPut | HttpDelete,
+ AllCallStyles = AsyncOneWay | SyncReply,
+ AllEndpointTypes = Soap11 | Soap12 | Xml | Json | Jsv | ProtoBuf | Csv,
+
+ InternalNetworkAccess = Localhost | LocalSubnet,
+
+ //Whether it came from an Internal or External address
+ Localhost = 1 << 0,
+ LocalSubnet = 1 << 1,
+ External = 1 << 2,
+
+ //Called over a secure or insecure channel
+ Secure = 1 << 3,
+ InSecure = 1 << 4,
+
+ //HTTP request type
+ HttpHead = 1 << 5,
+ HttpGet = 1 << 6,
+ HttpPost = 1 << 7,
+ HttpPut = 1 << 8,
+ HttpDelete = 1 << 9,
+ HttpPatch = 1 << 10,
+ HttpOptions = 1 << 11,
+ //Future 12
+
+ //Call Styles
+ AsyncOneWay = 1 << 13,
+ SyncReply = 1 << 14,
+
+ //Different endpoints
+ Soap11 = 1 << 15,
+ Soap12 = 1 << 16,
+ //POX
+ Xml = 1 << 17,
+ //Javascript
+ Json = 1 << 18,
+ //Jsv i.e. TypeSerializer
+ Jsv = 1 << 19,
+ //e.g. protobuf-net
+ ProtoBuf = 1 << 20,
+ //e.g. text/csv
+ Csv = 1 << 21,
+
+ Html = 1 << 22,
+ Yaml = 1 << 23,
+
+ MessageQueue = 1 << 24,
+ }
+
+=======
+using System;
+
+namespace ServiceStack.ServiceHost
+{
+ [Flags]
+ public enum EndpointAttributes
+ {
+ None = 0,
+
+ All = AllNetworkAccessTypes | AllSecurityModes | AllHttpMethods | AllCallStyles | AllEndpointTypes,
+ AllNetworkAccessTypes = External | Localhost | LocalSubnet,
+ AllSecurityModes = Secure | InSecure,
+ AllHttpMethods = HttpHead | HttpGet | HttpPost | HttpPut | HttpDelete,
+ AllCallStyles = AsyncOneWay | SyncReply,
+ AllEndpointTypes = Soap11 | Soap12 | Xml | Json | Jsv | ProtoBuf | Csv,
+
+ InternalNetworkAccess = Localhost | LocalSubnet,
+
+ //Whether it came from an Internal or External address
+ Localhost = 1 << 0,
+ LocalSubnet = 1 << 1,
+ External = 1 << 2,
+
+ //Called over a secure or insecure channel
+ Secure = 1 << 3,
+ InSecure = 1 << 4,
+
+ //HTTP request type
+ HttpHead = 1 << 5,
+ HttpGet = 1 << 6,
+ HttpPost = 1 << 7,
+ HttpPut = 1 << 8,
+ HttpDelete = 1 << 9,
+ HttpPatch = 1 << 10,
+ HttpOptions = 1 << 11,
+ //Future 12
+
+ //Call Styles
+ AsyncOneWay = 1 << 13,
+ SyncReply = 1 << 14,
+
+ //Different endpoints
+ Soap11 = 1 << 15,
+ Soap12 = 1 << 16,
+ //POX
+ Xml = 1 << 17,
+ //Javascript
+ Json = 1 << 18,
+ //Jsv i.e. TypeSerializer
+ Jsv = 1 << 19,
+ //e.g. protobuf-net
+ ProtoBuf = 1 << 20,
+ //e.g. text/csv
+ Csv = 1 << 21,
+
+ Html = 1 << 22,
+ Yaml = 1 << 23,
+
+ MsgPack = 1 << 24,
+ }
+
+>>>>>>> origin/HEAD
+}
52 src/ServiceStack.Interfaces/ServiceHost/Feature.cs
View
@@ -1,25 +1,29 @@
-using System;
-
-namespace ServiceStack.ServiceHost
-{
- [Flags]
- public enum Feature : int
- {
- None = 0,
- All = int.MaxValue,
- Soap = Soap11 | Soap12,
-
- Json = 1 << 0,
- Xml = 1 << 1,
- Jsv = 1 << 2,
- Soap11 = 1 << 3,
- Soap12 = 1 << 4,
- Csv = 1 << 5,
- Html = 1 << 6,
- CustomFormat = 1 << 7,
- Metadata = 1 << 8,
- Markdown = 1 << 9,
- Razor = 1 << 10,
- ProtoBuf = 1 << 11,
- }
+using System;
+
+namespace ServiceStack.ServiceHost
+{
+ [Flags]
+ public enum Feature : int
+ {
+ None = 0,
+ All = int.MaxValue,
+ Soap = Soap11 | Soap12,
+
+ Metadata = 1 << 0,
+ PredefinedRoutes = 1 << 1,
+ RequestInfo = 1 << 2,
+
+ Json = 1 << 3,
+ Xml = 1 << 4,
+ Jsv = 1 << 5,
+ Soap11 = 1 << 6,
+ Soap12 = 1 << 7,
+ Csv = 1 << 8,
+ Html = 1 << 9,
+ CustomFormat = 1 << 10,
+ Markdown = 1 << 11,
+ Razor = 1 << 12,
+ ProtoBuf = 1 << 13,
+ MsgPack = 1 << 14,
+ }
}
1,004 src/ServiceStack.ServiceInterface/Testing/TestBase.cs
View
@@ -1,503 +1,503 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Reflection;
-using System.Text;
-using Funq;
-using ServiceStack.Common;
-using ServiceStack.Common.Utils;
-using ServiceStack.Common.Web;
-using ServiceStack.Service;
-using ServiceStack.ServiceClient.Web;
-using ServiceStack.ServiceHost;
-using ServiceStack.ServiceInterface.ServiceModel;
-using ServiceStack.ServiceModel;
-using ServiceStack.Text;
-using ServiceStack.WebHost.Endpoints;
-using ServiceStack.WebHost.Endpoints.Support;
-
-namespace ServiceStack.ServiceInterface.Testing
-{
- public abstract class TestBase
- {
- protected IAppHost AppHost { get; set; }
-
- protected bool HasConfigured { get; set; }
-
- protected TestBase(params Assembly[] serviceAssemblies)
- : this(null, serviceAssemblies) { }
-
- protected TestBase(string serviceClientBaseUri, params Assembly[] serviceAssemblies)
- {
- if (serviceAssemblies.Length == 0)
- serviceAssemblies = new[] { GetType().Assembly };
-
- ServiceClientBaseUri = serviceClientBaseUri;
- ServiceAssemblies = serviceAssemblies;
-
- var serviceManager = new ServiceManager(serviceAssemblies);
-
- this.AppHost = new TestAppHost(serviceManager.Container, serviceAssemblies);
-
- EndpointHost.ConfigureHost(this.AppHost, "TestBase", serviceManager);
-
- EndpointHost.ServiceManager = this.AppHost.Config.ServiceManager;
- }
-
- protected abstract void Configure(Funq.Container container);
-
- protected Funq.Container Container
- {
- get { return EndpointHost.ServiceManager.Container; }
- }
-
- protected IServiceRoutes Routes
- {
- get { return EndpointHost.ServiceManager.ServiceController.Routes; }
- }
-
- //All integration tests call the Webservices hosted at the following location:
- protected string ServiceClientBaseUri { get; set; }
- protected Assembly[] ServiceAssemblies { get; set; }
-
- public virtual void OnBeforeTestFixture()
- {
- OnConfigure();
- }
-
- protected virtual void OnConfigure()
- {
- if (HasConfigured) return;
-
- HasConfigured = true;
- Configure(Container);
- EndpointHost.AfterInit();
- }
-
- public virtual void OnBeforeEachTest()
- {
- OnConfigure();
- }
-
- protected virtual IServiceClient CreateNewServiceClient()
- {
- return new DirectServiceClient(this, EndpointHost.ServiceManager);
- }
-
- protected virtual IRestClient CreateNewRestClient()
- {
- return new DirectServiceClient(this, EndpointHost.ServiceManager);
- }
-
- protected virtual IRestClientAsync CreateNewRestClientAsync()
- {
- return new DirectServiceClient(this, EndpointHost.ServiceManager);
- }
-
- public class DirectServiceClient : IServiceClient, IRestClient
- {
- private readonly TestBase parent;
- ServiceManager ServiceManager { get; set; }
-
- public DirectServiceClient(TestBase parent, ServiceManager serviceManager)
- {
- this.parent = parent;
- this.ServiceManager = serviceManager;
- }
-
- public void SendOneWay(object request)
- {
- ServiceManager.Execute(request);
- }
-
- public void SendOneWay(string relativeOrAbsoluteUrl, object request)
- {
- ServiceManager.Execute(request);
- }
-
- public TResponse Send<TResponse>(object request)
- {
- var response = ServiceManager.Execute(request);
- var httpResult = response as IHttpResult;
- if (httpResult != null)
- {
- if (httpResult.StatusCode >= HttpStatusCode.BadRequest)
- {
- var webEx = new WebServiceException(httpResult.StatusDescription) {
- ResponseDto = httpResult.Response,
- StatusCode = httpResult.Status,
- };
- throw webEx;
- }
- return (TResponse) httpResult.Response;
- }
-
- return (TResponse)response;
- }
-
- public TResponse Send<TResponse>(IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public void Send(IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse Get<TResponse>(IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public void Get(IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse Get<TResponse>(string relativeOrAbsoluteUrl)
- {
- return parent.ExecutePath<TResponse>(HttpMethod.Get, new UrlParts(relativeOrAbsoluteUrl), null);
- }
-
- public TResponse Delete<TResponse>(IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public void Delete(IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl)
- {
- return parent.ExecutePath<TResponse>(HttpMethod.Delete, new UrlParts(relativeOrAbsoluteUrl), null);
- }
-
- public TResponse Post<TResponse>(IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public void Post(IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request)
- {
- return parent.ExecutePath<TResponse>(HttpMethod.Post, new UrlParts(relativeOrAbsoluteUrl), request);
- }
-
- public TResponse Put<TResponse>(IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public void Put(IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request)
- {
- return parent.ExecutePath<TResponse>(HttpMethod.Put, new UrlParts(relativeOrAbsoluteUrl), request);
- }
-
- public TResponse Patch<TResponse>(IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public void Patch(IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request)
- {
- return parent.ExecutePath<TResponse>(HttpMethod.Patch, new UrlParts(relativeOrAbsoluteUrl), request);
- }
-
- public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
- {
- throw new NotImplementedException();
- }
-
- public void CustomMethod(string httpVerb, IReturnVoid request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse CustomMethod<TResponse>(string httpVerb, IReturn<TResponse> request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
- {
- throw new NotImplementedException();
- }
-
-
- public void SendAsync<TResponse>(object request,
- Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
- {
- try
- {
- var response = (TResponse)ServiceManager.Execute(request);
- onSuccess(response);
- }
- catch (Exception ex)
- {
- HandleException(ex, onError);
- }
- }
-
- private static void HandleException<TResponse>(Exception exception, Action<TResponse, Exception> onError)
- {
- var response = (TResponse)ReflectionUtils.CreateInstance(typeof(TResponse));
- var hasResponseStatus = response as IHasResponseStatus;
- if (hasResponseStatus != null)
- {
- hasResponseStatus.ResponseStatus = new ResponseStatus {
- ErrorCode = exception.GetType().Name,
- Message = exception.Message,
- StackTrace = exception.StackTrace,
- };
- }
- var webServiceEx = new WebServiceException(exception.Message, exception);
- if (onError != null) onError(response, webServiceEx);
- }
-
- public void SetCredentials(string userName, string password)
- {
- throw new NotImplementedException();
- }
-
- public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
- {
- try
- {
- var response = parent.ExecutePath<TResponse>(HttpMethod.Get, new UrlParts(relativeOrAbsoluteUrl), default(TResponse));
- onSuccess(response);
- }
- catch (Exception ex)
- {
- HandleException(ex, onError);
- }
- }
-
- public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
- {
- try
- {
- var response = parent.ExecutePath<TResponse>(HttpMethod.Delete, new UrlParts(relativeOrAbsoluteUrl), default(TResponse));
- onSuccess(response);
- }
- catch (Exception ex)
- {
- HandleException(ex, onError);
- }
- }
-
- public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
- {
- try
- {
- var response = parent.ExecutePath<TResponse>(HttpMethod.Post, new UrlParts(relativeOrAbsoluteUrl), request);
- onSuccess(response);
- }
- catch (Exception ex)
- {
- HandleException(ex, onError);
- }
- }
-
- public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
- {
- try
- {
- var response = parent.ExecutePath<TResponse>(HttpMethod.Put, new UrlParts(relativeOrAbsoluteUrl), request);
- onSuccess(response);
- }
- catch (Exception ex)
- {
- HandleException(ex, onError);
- }
- }
-
- public void Dispose() { }
- public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
- {
- throw new NotImplementedException();
- }
-
- public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request)
- {
- throw new NotImplementedException();
- }
- }
-
- public object ExecutePath(string pathInfo)
- {
- return ExecutePath(HttpMethods.Get, pathInfo);
- }
-
- private class UrlParts
- {
- public UrlParts(string pathInfo)
- {
- this.PathInfo = pathInfo.UrlDecode();
- var qsIndex = pathInfo.IndexOf("?");
- if (qsIndex != -1)
- {
- var qs = pathInfo.Substring(qsIndex + 1);
- this.PathInfo = pathInfo.Substring(0, qsIndex);
- var kvps = qs.Split('&');
-
- this.QueryString = new Dictionary<string, string>();
- foreach (var kvp in kvps)
- {
- var parts = kvp.Split('=');
- this.QueryString[parts[0]] = parts.Length > 1 ? parts[1] : null;
- }
- }
- }
-
- public string PathInfo { get; private set; }
- public Dictionary<string, string> QueryString { get; private set; }
- }
-
- public object ExecutePath(string httpMethod, string pathInfo)
- {
- var urlParts = new UrlParts(pathInfo);
- return ExecutePath(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, null);
- }
-
- private TResponse ExecutePath<TResponse>(string httpMethod, UrlParts urlParts, object requestDto)
- {
- return (TResponse)ExecutePath(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, requestDto);
- }
-
- public TResponse ExecutePath<TResponse>(string httpMethod, string pathInfo, object requestDto)
- {
- var urlParts = new UrlParts(pathInfo);
- return (TResponse)ExecutePath(httpMethod, urlParts.PathInfo, urlParts.QueryString, null, requestDto);
- }
-
- public object ExecutePath<T>(
- string httpMethod,
- string pathInfo,
- Dictionary<string, string> queryString,
- Dictionary<string, string> formData,
- T requestBody)
- {
- var isDefault = Equals(requestBody, default(T));
- var json = !isDefault ? JsonSerializer.SerializeToString(requestBody) : null;
- return ExecutePath(httpMethod, pathInfo, queryString, formData, json);
- }
-
- public object ExecutePath(
- string httpMethod,
- string pathInfo,
- Dictionary<string, string> queryString,
- Dictionary<string, string> formData,
- string requestBody)
- {
- var httpHandler = GetHandler(httpMethod, pathInfo);
-
- var contentType = (formData != null && formData.Count > 0)
- ? ContentType.FormUrlEncoded
- : requestBody != null ? ContentType.Json : null;
-
- var httpReq = new MockHttpRequest(
- httpHandler.RequestName, httpMethod, contentType,
- pathInfo,
- queryString.ToNameValueCollection(),
- requestBody == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(requestBody)),
- formData.ToNameValueCollection()
- );
-