1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
|
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Resources;
using System.Web.UI;
using System.Web.UI.WebControls;
internal static class QueryableDataSourceHelper {
// This regular expression verifies that parameter names are set to valid identifiers. This validation
// needs to match the parser's identifier validation as done in the default block of NextToken().
private static readonly string IdentifierPattern =
@"^\s*[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_]" + // first character
@"[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Nd}\p{Pc}\p{Mn}\p{Mc}\p{Cf}_]*"; // remaining characters
private static readonly Regex IdentifierRegex = new Regex(IdentifierPattern + @"\s*$");
private static readonly Regex AutoGenerateOrderByRegex = new Regex(IdentifierPattern +
@"(\s+(asc|ascending|desc|descending))?\s*$", RegexOptions.IgnoreCase); // order operators
internal static IQueryable AsQueryable(object o) {
IQueryable oQueryable = o as IQueryable;
if (oQueryable != null) {
return oQueryable;
}
// Wrap strings in IEnumerable<string> instead of treating as IEnumerable<char>.
string oString = o as string;
if (oString != null) {
return Queryable.AsQueryable(new string[] { oString });
}
IEnumerable oEnumerable = o as IEnumerable;
if (oEnumerable != null) {
// IEnumerable<T> can be directly converted to an IQueryable<T>.
Type genericType = FindGenericEnumerableType(o.GetType());
if (genericType != null) {
// The non-generic Queryable.AsQueryable gets called for array types, executing
// the FindGenericType logic again. Might want to investigate way to avoid this.
return Queryable.AsQueryable(oEnumerable);
}
// Wrap non-generic IEnumerables in IEnumerable<object>.
List<object> genericList = new List<object>();
foreach (object item in oEnumerable) {
genericList.Add(item);
}
return Queryable.AsQueryable(genericList);
}
// Wrap non-IEnumerable types in IEnumerable<T>.
Type listType = typeof(List<>).MakeGenericType(o.GetType());
IList list = (IList)DataSourceHelper.CreateObjectInstance(listType);
list.Add(o);
return Queryable.AsQueryable(list);
}
public static IList ToList(this IQueryable query, Type dataObjectType) {
MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(dataObjectType);
return (IList)toListMethod.Invoke(null, new object[] { query });
}
public static bool EnumerableContentEquals(IEnumerable enumerableA, IEnumerable enumerableB) {
IEnumerator enumeratorA = enumerableA.GetEnumerator();
IEnumerator enumeratorB = enumerableB.GetEnumerator();
while (enumeratorA.MoveNext()) {
if (!enumeratorB.MoveNext())
return false;
object itemA = enumeratorA.Current;
object itemB = enumeratorB.Current;
if (itemA == null) {
if (itemB != null)
return false;
}
else if (!itemA.Equals(itemB))
return false;
}
if (enumeratorB.MoveNext())
return false;
return true;
}
public static Type FindGenericEnumerableType(Type type) {
// Logic taken from Queryable.AsQueryable which accounts for Array types which are not
// generic but implement the generic IEnumerable interface.
while ((type != null) && (type != typeof(object)) && (type != typeof(string))) {
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IEnumerable<>))) {
return type;
}
foreach (Type interfaceType in type.GetInterfaces()) {
Type genericInterface = FindGenericEnumerableType(interfaceType);
if (genericInterface != null) {
return genericInterface;
}
}
type = type.BaseType;
}
return null;
}
internal static IDictionary<string, object> ToEscapedParameterKeys(this ParameterCollection parameters, HttpContext context, Control control) {
if (parameters != null) {
return parameters.GetValues(context, control).ToEscapedParameterKeys(control);
}
return null;
}
internal static IDictionary<string, object> ToEscapedParameterKeys(this IDictionary parameters, Control owner) {
Dictionary<string, object> escapedParameters = new Dictionary<string, object>(parameters.Count,
StringComparer.OrdinalIgnoreCase);
foreach (DictionaryEntry de in parameters) {
string key = (string)de.Key;
if (String.IsNullOrEmpty(key)) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
AtlasWeb.LinqDataSourceView_ParametersMustBeNamed, owner.ID));
}
ValidateParameterName(key, owner);
escapedParameters.Add('@' + key, de.Value);
}
return escapedParameters;
}
internal static IDictionary<string, object> ToEscapedParameterKeys(this IDictionary<string, object> parameters, Control owner) {
Dictionary<string, object> escapedParameters = new Dictionary<string, object>(parameters.Count,
StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, object> parameter in parameters) {
string key = parameter.Key;
if (String.IsNullOrEmpty(key)) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
AtlasWeb.LinqDataSourceView_ParametersMustBeNamed, owner.ID));
}
ValidateParameterName(key, owner);
escapedParameters.Add('@' + key, parameter.Value);
}
return escapedParameters;
}
internal static IQueryable CreateOrderByExpression(IOrderedDictionary parameters, IQueryable source, IDynamicQueryable queryable) {
if (parameters != null && parameters.Count > 0) {
//extract parameter values
//extract the order by expression and apply it to the queryable
string orderByExpression = GetOrderByClause(parameters.ToDictionary());
if (!String.IsNullOrEmpty(orderByExpression)) {
return queryable.OrderBy(source, orderByExpression);
}
}
return source;
}
internal static IQueryable CreateWhereExpression(IDictionary<string, object> parameters, IQueryable source, IDynamicQueryable queryable) {
if (parameters != null && parameters.Count > 0) {
//extract the where clause
WhereClause clause = GetWhereClause(parameters);
if (!String.IsNullOrEmpty(clause.Expression)) {
//transform the current query with the where clause
return queryable.Where(source, clause.Expression, clause.Parameters);
}
}
return source;
}
private static WhereClause GetWhereClause(IDictionary<string, object> whereParameters) {
Debug.Assert((whereParameters != null) && (whereParameters.Count > 0));
WhereClause whereClause = new WhereClause();
whereClause.Parameters = new Dictionary<string, object>(whereParameters.Count);
StringBuilder where = new StringBuilder();
int index = 0;
foreach (KeyValuePair<string, object> parameter in whereParameters) {
string key = parameter.Key;
string value = (parameter.Value == null) ? null : parameter.Value.ToString();
// exclude null and empty values.
if (!(String.IsNullOrEmpty(key) || String.IsNullOrEmpty(value))) {
string newKey = "@p" + index++;
if (where.Length > 0) {
where.Append(" AND ");
}
where.Append(key);
where.Append(" == ");
where.Append(newKey);
whereClause.Parameters.Add(newKey, parameter.Value);
}
}
whereClause.Expression = where.ToString();
return whereClause;
}
private static string GetOrderByClause(IDictionary<string, object> orderByParameters) {
Debug.Assert((orderByParameters != null) && (orderByParameters.Count > 0));
StringBuilder orderBy = new StringBuilder();
foreach (KeyValuePair<string, object> parameter in orderByParameters) {
string value = (string)parameter.Value;
// exclude null and empty values.
if (!String.IsNullOrEmpty(value)) {
string name = parameter.Key;
//validate parameter name
ValidateOrderByParameter(name, value);
if (orderBy.Length > 0) {
orderBy.Append(", ");
}
orderBy.Append(value);
}
}
return orderBy.ToString();
}
internal static void ValidateOrderByParameter(string name, string value) {
if (!AutoGenerateOrderByRegex.IsMatch(value)) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
AtlasWeb.LinqDataSourceView_InvalidOrderByFieldName, value, name));
}
}
internal static void ValidateParameterName(string name, Control owner) {
if (!IdentifierRegex.IsMatch(name)) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
AtlasWeb.LinqDataSourceView_InvalidParameterName, name, owner.ID));
}
}
private class WhereClause {
public string Expression { get; set; }
public IDictionary<string, object> Parameters { get; set; }
}
}
}
|