removed dead code

This commit is contained in:
Luke Pulverenti 2017-02-12 21:06:54 -05:00
parent 511a8702c2
commit e1b2b2e77e
11 changed files with 182 additions and 276 deletions

View File

@ -29,7 +29,7 @@ using SocketHttpListener.Primitives;
namespace Emby.Server.Implementations.HttpServer namespace Emby.Server.Implementations.HttpServer
{ {
public class HttpListenerHost : ServiceStackHost, IHttpServer public class HttpListenerHost : IHttpServer, IDisposable
{ {
private string DefaultRedirectPath { get; set; } private string DefaultRedirectPath { get; set; }
@ -62,7 +62,10 @@ namespace Emby.Server.Implementations.HttpServer
private readonly bool _enableDualModeSockets; private readonly bool _enableDualModeSockets;
public List<Action<IRequest, IResponse, object>> RequestFilters { get; set; } public List<Action<IRequest, IResponse, object>> RequestFilters { get; set; }
private Dictionary<Type, Type> ServiceOperationsMap = new Dictionary<Type, Type>(); public List<Action<IRequest, IResponse, object>> ResponseFilters { get; set; }
private readonly Dictionary<Type, Type> ServiceOperationsMap = new Dictionary<Type, Type>();
public static HttpListenerHost Instance { get; protected set; }
public HttpListenerHost(IServerApplicationHost applicationHost, public HttpListenerHost(IServerApplicationHost applicationHost,
ILogger logger, ILogger logger,
@ -71,6 +74,8 @@ namespace Emby.Server.Implementations.HttpServer
string defaultRedirectPath, INetworkManager networkManager, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding, ISocketFactory socketFactory, ICryptoProvider cryptoProvider, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, IEnvironmentInfo environment, ICertificate certificate, IStreamFactory streamFactory, Func<Type, Func<string, object>> funcParseFn, bool enableDualModeSockets) string defaultRedirectPath, INetworkManager networkManager, IMemoryStreamFactory memoryStreamProvider, ITextEncoding textEncoding, ISocketFactory socketFactory, ICryptoProvider cryptoProvider, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, IEnvironmentInfo environment, ICertificate certificate, IStreamFactory streamFactory, Func<Type, Func<string, object>> funcParseFn, bool enableDualModeSockets)
: base() : base()
{ {
Instance = this;
_appHost = applicationHost; _appHost = applicationHost;
DefaultRedirectPath = defaultRedirectPath; DefaultRedirectPath = defaultRedirectPath;
_networkManager = networkManager; _networkManager = networkManager;
@ -90,6 +95,7 @@ namespace Emby.Server.Implementations.HttpServer
_logger = logger; _logger = logger;
RequestFilters = new List<Action<IRequest, IResponse, object>>(); RequestFilters = new List<Action<IRequest, IResponse, object>>();
ResponseFilters = new List<Action<IRequest, IResponse, object>>();
} }
public string GlobalResponse { get; set; } public string GlobalResponse { get; set; }
@ -112,7 +118,7 @@ namespace Emby.Server.Implementations.HttpServer
} }
} }
public override object CreateInstance(Type type) public object CreateInstance(Type type)
{ {
return _appHost.CreateInstance(type); return _appHost.CreateInstance(type);
} }
@ -168,12 +174,12 @@ namespace Emby.Server.Implementations.HttpServer
private IHasRequestFilter[] GetRequestFilterAttributes(Type requestDtoType) private IHasRequestFilter[] GetRequestFilterAttributes(Type requestDtoType)
{ {
var attributes = requestDtoType.AllAttributes().OfType<IHasRequestFilter>().ToList(); var attributes = requestDtoType.GetTypeInfo().GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
var serviceType = GetServiceTypeByRequest(requestDtoType); var serviceType = GetServiceTypeByRequest(requestDtoType);
if (serviceType != null) if (serviceType != null)
{ {
attributes.AddRange(serviceType.AllAttributes().OfType<IHasRequestFilter>()); attributes.AddRange(serviceType.GetTypeInfo().GetCustomAttributes(true).OfType<IHasRequestFilter>());
} }
attributes.Sort((x, y) => x.Priority - y.Priority); attributes.Sort((x, y) => x.Priority - y.Priority);
@ -658,8 +664,6 @@ namespace Emby.Server.Implementations.HttpServer
_logger.Info("Calling ServiceStack AppHost.Init"); _logger.Info("Calling ServiceStack AppHost.Init");
Instance = this;
ServiceController.Init(this); ServiceController.Init(this);
var requestFilters = _appHost.GetExports<IRequestFilter>().ToList(); var requestFilters = _appHost.GetExports<IRequestFilter>().ToList();
@ -668,12 +672,12 @@ namespace Emby.Server.Implementations.HttpServer
RequestFilters.Add(filter.Filter); RequestFilters.Add(filter.Filter);
} }
GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse); ResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
} }
public override RouteAttribute[] GetRouteAttributes(Type requestType) public RouteAttribute[] GetRouteAttributes(Type requestType)
{ {
var routes = requestType.AllAttributes<RouteAttribute>(); var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
var clone = routes.ToList(); var clone = routes.ToList();
foreach (var route in clone) foreach (var route in clone)
@ -703,27 +707,27 @@ namespace Emby.Server.Implementations.HttpServer
return routes.ToArray(); return routes.ToArray();
} }
public override Func<string, object> GetParseFn(Type propertyType) public Func<string, object> GetParseFn(Type propertyType)
{ {
return _funcParseFn(propertyType); return _funcParseFn(propertyType);
} }
public override void SerializeToJson(object o, Stream stream) public void SerializeToJson(object o, Stream stream)
{ {
_jsonSerializer.SerializeToStream(o, stream); _jsonSerializer.SerializeToStream(o, stream);
} }
public override void SerializeToXml(object o, Stream stream) public void SerializeToXml(object o, Stream stream)
{ {
_xmlSerializer.SerializeToStream(o, stream); _xmlSerializer.SerializeToStream(o, stream);
} }
public override object DeserializeXml(Type type, Stream stream) public object DeserializeXml(Type type, Stream stream)
{ {
return _xmlSerializer.DeserializeFromStream(type, stream); return _xmlSerializer.DeserializeFromStream(type, stream);
} }
public override object DeserializeJson(Type type, Stream stream) public object DeserializeJson(Type type, Stream stream)
{ {
return _jsonSerializer.DeserializeFromStream(stream, type); return _jsonSerializer.DeserializeFromStream(stream, type);
} }
@ -764,7 +768,7 @@ namespace Emby.Server.Implementations.HttpServer
{ {
if (_disposed) return; if (_disposed) return;
base.Dispose(); Dispose();
lock (_disposeLock) lock (_disposeLock)
{ {
@ -779,7 +783,7 @@ namespace Emby.Server.Implementations.HttpServer
} }
} }
public override void Dispose() public void Dispose()
{ {
Dispose(true); Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);

View File

@ -204,7 +204,7 @@ namespace Emby.Server.Implementations.HttpServer
using (var ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
var contentType = request.ResponseContentType; var contentType = request.ResponseContentType;
var writerFn = RequestHelper.GetResponseWriter(contentType); var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
writerFn(dto, ms); writerFn(dto, ms);

View File

@ -1,40 +1,40 @@
using System; using System;
using System.IO; using System.IO;
using ServiceStack; using Emby.Server.Implementations.HttpServer;
namespace Emby.Server.Implementations.Services namespace Emby.Server.Implementations.Services
{ {
public class RequestHelper public class RequestHelper
{ {
public static Func<Type, Stream, object> GetRequestReader(string contentType) public static Func<Type, Stream, object> GetRequestReader(HttpListenerHost host, string contentType)
{ {
switch (GetContentTypeWithoutEncoding(contentType)) switch (GetContentTypeWithoutEncoding(contentType))
{ {
case "application/xml": case "application/xml":
case "text/xml": case "text/xml":
case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
return ServiceStackHost.Instance.DeserializeXml; return host.DeserializeXml;
case "application/json": case "application/json":
case "text/json": case "text/json":
return ServiceStackHost.Instance.DeserializeJson; return host.DeserializeJson;
} }
return null; return null;
} }
public static Action<object, Stream> GetResponseWriter(string contentType) public static Action<object, Stream> GetResponseWriter(HttpListenerHost host, string contentType)
{ {
switch (GetContentTypeWithoutEncoding(contentType)) switch (GetContentTypeWithoutEncoding(contentType))
{ {
case "application/xml": case "application/xml":
case "text/xml": case "text/xml":
case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml case "text/xml; charset=utf-8": //"text/xml; charset=utf-8" also matches xml
return (o, s) => ServiceStackHost.Instance.SerializeToXml(o, s); return host.SerializeToXml;
case "application/json": case "application/json":
case "text/json": case "text/json":
return (o, s) => ServiceStackHost.Instance.SerializeToJson(o, s); return host.SerializeToJson;
} }
return null; return null;

View File

@ -5,6 +5,7 @@ using System.Net;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Emby.Server.Implementations.HttpServer;
using MediaBrowser.Model.Services; using MediaBrowser.Model.Services;
namespace Emby.Server.Implementations.Services namespace Emby.Server.Implementations.Services
@ -161,7 +162,7 @@ namespace Emby.Server.Implementations.Services
public static async Task WriteObject(IRequest request, object result, IResponse response) public static async Task WriteObject(IRequest request, object result, IResponse response)
{ {
var contentType = request.ResponseContentType; var contentType = request.ResponseContentType;
var serializer = RequestHelper.GetResponseWriter(contentType); var serializer = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);
using (var ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {

View File

@ -53,28 +53,58 @@ namespace Emby.Server.Implementations.Services
ServiceExecGeneral.CreateServiceRunnersFor(requestType, actions); ServiceExecGeneral.CreateServiceRunnersFor(requestType, actions);
var returnMarker = requestType.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>)); var returnMarker = GetTypeWithGenericTypeDefinitionOf(requestType, typeof(IReturn<>));
var responseType = returnMarker != null ? var responseType = returnMarker != null ?
GetGenericArguments(returnMarker)[0] GetGenericArguments(returnMarker)[0]
: mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ? : mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ?
mi.ReturnType mi.ReturnType
: Type.GetType(requestType.FullName + "Response"); : Type.GetType(requestType.FullName + "Response");
RegisterRestPaths(requestType); RegisterRestPaths(appHost, requestType);
appHost.AddServiceInfo(serviceType, requestType, responseType); appHost.AddServiceInfo(serviceType, requestType, responseType);
} }
} }
private static Type GetTypeWithGenericTypeDefinitionOf(Type type, Type genericTypeDefinition)
{
foreach (var t in type.GetTypeInfo().ImplementedInterfaces)
{
if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == genericTypeDefinition)
{
return t;
}
}
var genericType = FirstGenericType(type);
if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition)
{
return genericType;
}
return null;
}
public static Type FirstGenericType(Type type)
{
while (type != null)
{
if (type.GetTypeInfo().IsGenericType)
return type;
type = type.GetTypeInfo().BaseType;
}
return null;
}
public readonly Dictionary<string, List<RestPath>> RestPathMap = new Dictionary<string, List<RestPath>>(StringComparer.OrdinalIgnoreCase); public readonly Dictionary<string, List<RestPath>> RestPathMap = new Dictionary<string, List<RestPath>>(StringComparer.OrdinalIgnoreCase);
public void RegisterRestPaths(Type requestType) public void RegisterRestPaths(HttpListenerHost appHost, Type requestType)
{ {
var appHost = ServiceStackHost.Instance;
var attrs = appHost.GetRouteAttributes(requestType); var attrs = appHost.GetRouteAttributes(requestType);
foreach (MediaBrowser.Model.Services.RouteAttribute attr in attrs) foreach (RouteAttribute attr in attrs)
{ {
var restPath = new RestPath(requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes); var restPath = new RestPath(appHost.CreateInstance, appHost.GetParseFn, requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes);
if (!restPath.IsValid) if (!restPath.IsValid)
throw new NotSupportedException(string.Format( throw new NotSupportedException(string.Format(

View File

@ -59,17 +59,17 @@ namespace Emby.Server.Implementations.Services
} }
} }
protected static object CreateContentTypeRequest(IRequest httpReq, Type requestType, string contentType) protected static object CreateContentTypeRequest(HttpListenerHost host, IRequest httpReq, Type requestType, string contentType)
{ {
if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0) if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0)
{ {
var deserializer = RequestHelper.GetRequestReader(contentType); var deserializer = RequestHelper.GetRequestReader(host, contentType);
if (deserializer != null) if (deserializer != null)
{ {
return deserializer(requestType, httpReq.InputStream); return deserializer(requestType, httpReq.InputStream);
} }
} }
return ServiceStackHost.Instance.CreateInstance(requestType); //Return an empty DTO, even for empty request bodies return host.CreateInstance(requestType);
} }
public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType) public static RestPath FindMatchingRestPath(string httpMethod, string pathInfo, ILogger logger, out string contentType)
@ -137,7 +137,7 @@ namespace Emby.Server.Implementations.Services
if (ResponseContentType != null) if (ResponseContentType != null)
httpReq.ResponseContentType = ResponseContentType; httpReq.ResponseContentType = ResponseContentType;
var request = httpReq.Dto = CreateRequest(httpReq, restPath, logger); var request = httpReq.Dto = CreateRequest(appHost, httpReq, restPath, logger);
appHost.ApplyRequestFilters(httpReq, httpRes, request); appHost.ApplyRequestFilters(httpReq, httpRes, request);
@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.Services
var response = await HandleResponseAsync(rawResponse).ConfigureAwait(false); var response = await HandleResponseAsync(rawResponse).ConfigureAwait(false);
// Apply response filters // Apply response filters
foreach (var responseFilter in appHost.GlobalResponseFilters) foreach (var responseFilter in appHost.ResponseFilters)
{ {
responseFilter(httpReq, httpRes, response); responseFilter(httpReq, httpRes, response);
} }
@ -154,18 +154,18 @@ namespace Emby.Server.Implementations.Services
await ResponseHelper.WriteToResponse(httpRes, httpReq, response).ConfigureAwait(false); await ResponseHelper.WriteToResponse(httpRes, httpReq, response).ConfigureAwait(false);
} }
public static object CreateRequest(IRequest httpReq, RestPath restPath, ILogger logger) public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, ILogger logger)
{ {
var requestType = restPath.RequestType; var requestType = restPath.RequestType;
if (RequireqRequestStream(requestType)) if (RequireqRequestStream(requestType))
{ {
// Used by IRequiresRequestStream // Used by IRequiresRequestStream
return CreateRequiresRequestStreamRequest(httpReq, requestType); return CreateRequiresRequestStreamRequest(host, httpReq, requestType);
} }
var requestParams = GetFlattenedRequestParams(httpReq); var requestParams = GetFlattenedRequestParams(httpReq);
return CreateRequest(httpReq, restPath, requestParams); return CreateRequest(host, httpReq, restPath, requestParams);
} }
private static bool RequireqRequestStream(Type requestType) private static bool RequireqRequestStream(Type requestType)
@ -175,19 +175,19 @@ namespace Emby.Server.Implementations.Services
return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo()); return requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo());
} }
private static IRequiresRequestStream CreateRequiresRequestStreamRequest(IRequest req, Type requestType) private static IRequiresRequestStream CreateRequiresRequestStreamRequest(HttpListenerHost host, IRequest req, Type requestType)
{ {
var restPath = GetRoute(req); var restPath = GetRoute(req);
var request = ServiceHandler.CreateRequest(req, restPath, GetRequestParams(req), ServiceStackHost.Instance.CreateInstance(requestType)); var request = ServiceHandler.CreateRequest(req, restPath, GetRequestParams(req), host.CreateInstance(requestType));
var rawReq = (IRequiresRequestStream)request; var rawReq = (IRequiresRequestStream)request;
rawReq.RequestStream = req.InputStream; rawReq.RequestStream = req.InputStream;
return rawReq; return rawReq;
} }
public static object CreateRequest(IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams) public static object CreateRequest(HttpListenerHost host, IRequest httpReq, RestPath restPath, Dictionary<string, string> requestParams)
{ {
var requestDto = CreateContentTypeRequest(httpReq, restPath.RequestType, httpReq.ContentType); var requestDto = CreateContentTypeRequest(host, httpReq, restPath.RequestType, httpReq.ContentType);
return CreateRequest(httpReq, restPath, requestParams, requestDto); return CreateRequest(httpReq, restPath, requestParams, requestDto);
} }

View File

@ -1,168 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ServiceStack
{
public static class ReflectionExtensions
{
public static Type FirstGenericType(this Type type)
{
while (type != null)
{
if (type.IsGeneric())
return type;
type = type.BaseType();
}
return null;
}
public static Type GetTypeWithGenericTypeDefinitionOf(this Type type, Type genericTypeDefinition)
{
foreach (var t in type.GetTypeInterfaces())
{
if (t.IsGeneric() && t.GetGenericTypeDefinition() == genericTypeDefinition)
{
return t;
}
}
var genericType = type.FirstGenericType();
if (genericType != null && genericType.GetGenericTypeDefinition() == genericTypeDefinition)
{
return genericType;
}
return null;
}
public static PropertyInfo[] GetPublicProperties(this Type type)
{
if (type.IsInterface())
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetTypeInterfaces())
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetTypesPublicProperties();
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return type.GetTypesPublicProperties()
.Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties
.ToArray();
}
public const string DataMember = "DataMemberAttribute";
internal static string[] IgnoreAttributesNamed = new[] {
"IgnoreDataMemberAttribute",
"JsonIgnoreAttribute"
};
public static PropertyInfo[] GetSerializableProperties(this Type type)
{
var properties = type.GetPublicProperties();
return properties.OnlySerializableProperties(type);
}
private static List<Type> _excludeTypes = new List<Type> { typeof(Stream) };
public static PropertyInfo[] OnlySerializableProperties(this PropertyInfo[] properties, Type type = null)
{
var readableProperties = properties.Where(x => x.PropertyGetMethod(nonPublic: false) != null);
// else return those properties that are not decorated with IgnoreDataMember
return readableProperties
.Where(prop => prop.AllAttributes()
.All(attr =>
{
var name = attr.GetType().Name;
return !IgnoreAttributesNamed.Contains(name);
}))
.Where(prop => !_excludeTypes.Contains(prop.PropertyType))
.ToArray();
}
}
public static class PlatformExtensions //Because WinRT is a POS
{
public static bool IsInterface(this Type type)
{
return type.GetTypeInfo().IsInterface;
}
public static bool IsGeneric(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
public static Type BaseType(this Type type)
{
return type.GetTypeInfo().BaseType;
}
public static Type[] GetTypeInterfaces(this Type type)
{
return type.GetTypeInfo().ImplementedInterfaces.ToArray();
}
internal static PropertyInfo[] GetTypesPublicProperties(this Type subType)
{
var pis = new List<PropertyInfo>();
foreach (var pi in subType.GetRuntimeProperties())
{
var mi = pi.GetMethod ?? pi.SetMethod;
if (mi != null && mi.IsStatic) continue;
pis.Add(pi);
}
return pis.ToArray();
}
public static MethodInfo PropertyGetMethod(this PropertyInfo pi, bool nonPublic = false)
{
return pi.GetMethod;
}
public static object[] AllAttributes(this PropertyInfo propertyInfo)
{
return propertyInfo.GetCustomAttributes(true).ToArray();
}
public static object[] AllAttributes(this Type type)
{
return type.GetTypeInfo().GetCustomAttributes(true).ToArray();
}
public static List<TAttr> AllAttributes<TAttr>(this Type type)
where TAttr : Attribute
{
return type.GetTypeInfo().GetCustomAttributes<TAttr>(true).ToList();
}
}
}

View File

@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using System.Text; using System.Text;
using MediaBrowser.Model.Logging; using MediaBrowser.Model.Logging;
using ServiceStack.Serialization; using ServiceStack.Serialization;
@ -71,7 +73,7 @@ namespace ServiceStack
public static string[] GetPathPartsForMatching(string pathInfo) public static string[] GetPathPartsForMatching(string pathInfo)
{ {
var parts = pathInfo.ToLower().Split(PathSeperatorChar) var parts = pathInfo.ToLower().Split(PathSeperatorChar)
.Where(x => !string.IsNullOrEmpty(x)).ToArray(); .Where(x => !String.IsNullOrEmpty(x)).ToArray();
return parts; return parts;
} }
@ -107,14 +109,14 @@ namespace ServiceStack
return list; return list;
} }
public RestPath(Type requestType, string path, string verbs, string summary = null, string notes = null) public RestPath(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type requestType, string path, string verbs, string summary = null, string notes = null)
{ {
this.RequestType = requestType; this.RequestType = requestType;
this.Summary = summary; this.Summary = summary;
this.Notes = notes; this.Notes = notes;
this.restPath = path; this.restPath = path;
this.allowsAllVerbs = verbs == null || string.Equals(verbs, WildCard, StringComparison.OrdinalIgnoreCase); this.allowsAllVerbs = verbs == null || String.Equals(verbs, WildCard, StringComparison.OrdinalIgnoreCase);
if (!this.allowsAllVerbs) if (!this.allowsAllVerbs)
{ {
this.allowedVerbs = verbs.ToUpper(); this.allowedVerbs = verbs.ToUpper();
@ -126,7 +128,7 @@ namespace ServiceStack
var hasSeparators = new List<bool>(); var hasSeparators = new List<bool>();
foreach (var component in this.restPath.Split(PathSeperatorChar)) foreach (var component in this.restPath.Split(PathSeperatorChar))
{ {
if (string.IsNullOrEmpty(component)) continue; if (String.IsNullOrEmpty(component)) continue;
if (StringContains(component, VariablePrefix) if (StringContains(component, VariablePrefix)
&& component.IndexOf(ComponentSeperator) != -1) && component.IndexOf(ComponentSeperator) != -1)
@ -199,19 +201,95 @@ namespace ServiceStack
this.IsValid = sbHashKey.Length > 0; this.IsValid = sbHashKey.Length > 0;
this.UniqueMatchHashKey = sbHashKey.ToString(); this.UniqueMatchHashKey = sbHashKey.ToString();
this.typeDeserializer = new StringMapTypeDeserializer(this.RequestType); this.typeDeserializer = new StringMapTypeDeserializer(createInstanceFn, getParseFn, this.RequestType);
RegisterCaseInsenstivePropertyNameMappings(); RegisterCaseInsenstivePropertyNameMappings();
} }
private void RegisterCaseInsenstivePropertyNameMappings() private void RegisterCaseInsenstivePropertyNameMappings()
{ {
foreach (var propertyInfo in RequestType.GetSerializableProperties()) foreach (var propertyInfo in GetSerializableProperties(RequestType))
{ {
var propertyName = propertyInfo.Name; var propertyName = propertyInfo.Name;
propertyNamesMap.Add(propertyName.ToLower(), propertyName); propertyNamesMap.Add(propertyName.ToLower(), propertyName);
} }
} }
internal static string[] IgnoreAttributesNamed = new[] {
"IgnoreDataMemberAttribute",
"JsonIgnoreAttribute"
};
private static List<Type> _excludeTypes = new List<Type> { typeof(Stream) };
internal static PropertyInfo[] GetSerializableProperties(Type type)
{
var properties = GetPublicProperties(type);
var readableProperties = properties.Where(x => x.GetMethod != null);
// else return those properties that are not decorated with IgnoreDataMember
return readableProperties
.Where(prop => prop.GetCustomAttributes(true)
.All(attr =>
{
var name = attr.GetType().Name;
return !IgnoreAttributesNamed.Contains(name);
}))
.Where(prop => !_excludeTypes.Contains(prop.PropertyType))
.ToArray();
}
private static PropertyInfo[] GetPublicProperties(Type type)
{
if (type.GetTypeInfo().IsInterface)
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces)
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = GetTypesPublicProperties(subType);
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return GetTypesPublicProperties(type)
.Where(t => t.GetIndexParameters().Length == 0) // ignore indexed properties
.ToArray();
}
private static PropertyInfo[] GetTypesPublicProperties(Type subType)
{
var pis = new List<PropertyInfo>();
foreach (var pi in subType.GetRuntimeProperties())
{
var mi = pi.GetMethod ?? pi.SetMethod;
if (mi != null && mi.IsStatic) continue;
pis.Add(pi);
}
return pis.ToArray();
}
public bool IsValid { get; set; } public bool IsValid { get; set; }
/// <summary> /// <summary>
@ -243,7 +321,7 @@ namespace ServiceStack
score += Math.Max((10 - VariableArgsCount), 1) * 100; score += Math.Max((10 - VariableArgsCount), 1) * 100;
//Exact verb match is better than ANY //Exact verb match is better than ANY
var exactVerb = string.Equals(httpMethod, AllowedVerbs, StringComparison.OrdinalIgnoreCase); var exactVerb = String.Equals(httpMethod, AllowedVerbs, StringComparison.OrdinalIgnoreCase);
score += exactVerb ? 10 : 1; score += exactVerb ? 10 : 1;
return score; return score;
@ -339,7 +417,7 @@ namespace ServiceStack
private bool LiteralsEqual(string str1, string str2) private bool LiteralsEqual(string str1, string str2)
{ {
// Most cases // Most cases
if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)) if (String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
{ {
return true; return true;
} }
@ -349,7 +427,7 @@ namespace ServiceStack
str2 = str2.ToUpperInvariant(); str2 = str2.ToUpperInvariant();
// Invariant IgnoreCase would probably be better but it's not available in PCL // Invariant IgnoreCase would probably be better but it's not available in PCL
return string.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase); return String.Equals(str1, str2, StringComparison.CurrentCultureIgnoreCase);
} }
private bool ExplodeComponents(ref string[] withPathInfoParts) private bool ExplodeComponents(ref string[] withPathInfoParts)
@ -358,7 +436,7 @@ namespace ServiceStack
for (var i = 0; i < withPathInfoParts.Length; i++) for (var i = 0; i < withPathInfoParts.Length; i++)
{ {
var component = withPathInfoParts[i]; var component = withPathInfoParts[i];
if (string.IsNullOrEmpty(component)) continue; if (String.IsNullOrEmpty(component)) continue;
if (this.PathComponentsCount != this.TotalComponentsCount if (this.PathComponentsCount != this.TotalComponentsCount
&& this.componentsWithSeparators[i]) && this.componentsWithSeparators[i])
@ -380,7 +458,7 @@ namespace ServiceStack
public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance) public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
{ {
var requestComponents = pathInfo.Split(PathSeperatorChar) var requestComponents = pathInfo.Split(PathSeperatorChar)
.Where(x => !string.IsNullOrEmpty(x)).ToArray(); .Where(x => !String.IsNullOrEmpty(x)).ToArray();
ExplodeComponents(ref requestComponents); ExplodeComponents(ref requestComponents);
@ -390,7 +468,7 @@ namespace ServiceStack
&& requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount; && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
if (!isValidWildCardPath) if (!isValidWildCardPath)
throw new ArgumentException(string.Format( throw new ArgumentException(String.Format(
"Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'", "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
pathInfo, this.restPath)); pathInfo, this.restPath));
} }
@ -409,7 +487,7 @@ namespace ServiceStack
string propertyNameOnRequest; string propertyNameOnRequest;
if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest)) if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest))
{ {
if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase)) if (String.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
{ {
pathIx++; pathIx++;
continue; continue;
@ -439,12 +517,12 @@ namespace ServiceStack
// hits a match for the next element in the definition (which must be a literal) // hits a match for the next element in the definition (which must be a literal)
// It may consume 0 or more path parts // It may consume 0 or more path parts
var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1]; var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) if (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append(value); sb.Append(value);
pathIx++; pathIx++;
while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) while (!String.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
{ {
sb.Append(PathSeperatorChar + requestComponents[pathIx++]); sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
} }

View File

@ -69,9 +69,7 @@
<Prefer32Bit>false</Prefer32Bit> <Prefer32Bit>false</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ReflectionExtensions.cs" />
<Compile Include="StringMapTypeDeserializer.cs" /> <Compile Include="StringMapTypeDeserializer.cs" />
<Compile Include="ServiceStackHost.cs" />
<Compile Include="UrlExtensions.cs" /> <Compile Include="UrlExtensions.cs" />
<Compile Include="RestPath.cs" /> <Compile Include="RestPath.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />

View File

@ -1,42 +0,0 @@
// Copyright (c) Service Stack LLC. All Rights Reserved.
// License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
namespace ServiceStack
{
public abstract class ServiceStackHost : IDisposable
{
public static ServiceStackHost Instance { get; protected set; }
protected ServiceStackHost()
{
GlobalResponseFilters = new List<Action<IRequest, IResponse, object>>();
}
public abstract object CreateInstance(Type type);
public List<Action<IRequest, IResponse, object>> GlobalResponseFilters { get; set; }
public abstract RouteAttribute[] GetRouteAttributes(Type requestType);
public abstract Func<string, object> GetParseFn(Type propertyType);
public abstract void SerializeToJson(object o, Stream stream);
public abstract void SerializeToXml(object o, Stream stream);
public abstract object DeserializeXml(Type type, Stream stream);
public abstract object DeserializeJson(Type type, Stream stream);
public virtual void Dispose()
{
//JsConfig.Reset(); //Clears Runtime Attributes
Instance = null;
}
}
}

View File

@ -34,14 +34,19 @@ namespace ServiceStack.Serialization
if (propertyType == typeof(string)) if (propertyType == typeof(string))
return s => s; return s => s;
return ServiceStackHost.Instance.GetParseFn(propertyType); return _GetParseFn(propertyType);
} }
public StringMapTypeDeserializer(Type type) private readonly Func<Type, object> _CreateInstanceFn;
private readonly Func<Type, Func<string, object>> _GetParseFn;
public StringMapTypeDeserializer(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type type)
{ {
_CreateInstanceFn = createInstanceFn;
_GetParseFn = getParseFn;
this.type = type; this.type = type;
foreach (var propertyInfo in type.GetSerializableProperties()) foreach (var propertyInfo in RestPath.GetSerializableProperties(type))
{ {
var propertySetFn = TypeAccessor.GetSetPropertyMethod(type, propertyInfo); var propertySetFn = TypeAccessor.GetSetPropertyMethod(type, propertyInfo);
var propertyType = propertyInfo.PropertyType; var propertyType = propertyInfo.PropertyType;
@ -59,7 +64,7 @@ namespace ServiceStack.Serialization
PropertySerializerEntry propertySerializerEntry = null; PropertySerializerEntry propertySerializerEntry = null;
if (instance == null) if (instance == null)
instance = ServiceStackHost.Instance.CreateInstance(type); instance = _CreateInstanceFn(type);
foreach (var pair in keyValuePairs.Where(x => !string.IsNullOrEmpty(x.Value))) foreach (var pair in keyValuePairs.Where(x => !string.IsNullOrEmpty(x.Value)))
{ {