using Linq2Rest.Parser;
using Nancy;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
///
/// This is a modified version of Nancy.OData
/// https://github.com/adamhathcock/Nancy.OData
///
/// It adds natural sorting on the results, because Linq2Rest/OData doesn't support custom orderby functions.
///
///
///
namespace BCR
{
public static class ODataExtensions
{
private const string ODATA_URI_KEY = "OData_Uri";
private static NameValueCollection ParseUriOptions(NancyContext context)
{
object item;
if (context.Items.TryGetValue(ODATA_URI_KEY, out item))
{
return item as NameValueCollection;
}
NameValueCollection nv = new NameValueCollection();
context.Items.Add(ODATA_URI_KEY, nv);
var queryString = context.Request.Url.Query;
if (string.IsNullOrWhiteSpace(queryString))
{
return nv;
}
if (!queryString.StartsWith("?"))
{
throw new InvalidOperationException("Invalid OData query string " + queryString);
}
var parameters = queryString.Substring(1).Split('&', '=');
if (parameters.Length % 2 != 0)
{
throw new InvalidOperationException("Invalid OData query string " + queryString);
}
for (int i = 0; i < parameters.Length; i += 2)
{
nv.Add(parameters[i], Uri.UnescapeDataString(parameters[i + 1]));
}
return nv;
}
public static string GetReflectedPropertyValueAsString(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
public static object GetReflectedPropertyValue(this object subject, string field)
{
return subject.GetType().GetProperty(field).GetValue(subject, null);
}
public static bool ReflectedPropertyIsString(this object subject, string field)
{
return subject.GetType().GetProperty(field).GetType() == typeof(bool);
}
///
/// Returns a filtered and ordered result set.
/// Uses natural sort.
///
///
///
/// The objects to filter
/// The total number of items in the resultset before paging.
///
public static IEnumerable