Added unit test for ContentStore, added object extensions and supporting classes from v5,
added RhinoMocks to the test project and httpcontext factory from v5 unit tests to be used in our v4 ones.
This commit is contained in:
66
src/Umbraco.Core/Attempt.cs
Normal file
66
src/Umbraco.Core/Attempt.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
|
||||
namespace Umbraco.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the result of an operation attempt
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <remarks></remarks>
|
||||
[Serializable]
|
||||
public struct Attempt<T>
|
||||
{
|
||||
private readonly bool _success;
|
||||
private readonly T _result;
|
||||
private readonly Exception _error;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this <see cref="Attempt{T}"/> represents a successful operation.
|
||||
/// </summary>
|
||||
/// <remarks></remarks>
|
||||
public bool Success
|
||||
{
|
||||
get { return _success; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the error associated with an unsuccessful attempt.
|
||||
/// </summary>
|
||||
/// <value>The error.</value>
|
||||
public Exception Error { get { return _error; } }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the parse result.
|
||||
/// </summary>
|
||||
/// <remarks></remarks>
|
||||
public T Result
|
||||
{
|
||||
get { return _result; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents an unsuccessful parse operation
|
||||
/// </summary>
|
||||
public static readonly Attempt<T> False;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Attempt{T}"/> struct.
|
||||
/// </summary>
|
||||
/// <param name="success">If set to <c>true</c> this tuple represents a successful parse result.</param>
|
||||
/// <param name="result">The parse result.</param>
|
||||
/// <remarks></remarks>
|
||||
public Attempt(bool success, T result)
|
||||
{
|
||||
_success = success;
|
||||
_result = result;
|
||||
_error = null;
|
||||
}
|
||||
|
||||
public Attempt(Exception error)
|
||||
{
|
||||
_success = false;
|
||||
_result = default(T);
|
||||
_error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
32
src/Umbraco.Core/CustomBooleanTypeConverter.cs
Normal file
32
src/Umbraco.Core/CustomBooleanTypeConverter.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Umbraco.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Allows for converting string representations of 0 and 1 to boolean
|
||||
/// </summary>
|
||||
internal class CustomBooleanTypeConverter : BooleanConverter
|
||||
{
|
||||
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
|
||||
{
|
||||
if (sourceType == typeof(string))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return base.CanConvertFrom(context, sourceType);
|
||||
}
|
||||
|
||||
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
|
||||
{
|
||||
if (value is string)
|
||||
{
|
||||
var str = (string)value;
|
||||
if (str == "1") return true;
|
||||
if (str == "0") return false;
|
||||
}
|
||||
|
||||
return base.ConvertFrom(context, culture, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
376
src/Umbraco.Core/ObjectExtensions.cs
Normal file
376
src/Umbraco.Core/ObjectExtensions.cs
Normal file
@@ -0,0 +1,376 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
|
||||
namespace Umbraco.Core
|
||||
{
|
||||
internal static class ObjectExtensions
|
||||
{
|
||||
//private static readonly ConcurrentDictionary<Type, Func<object>> ObjectFactoryCache = new ConcurrentDictionary<Type, Func<object>>();
|
||||
|
||||
public static IEnumerable<T> AsEnumerableOfOne<T>(this T input)
|
||||
{
|
||||
return Enumerable.Repeat(input, 1);
|
||||
}
|
||||
|
||||
public static void DisposeIfDisposable(this object input)
|
||||
{
|
||||
var disposable = input as IDisposable;
|
||||
if (disposable != null) disposable.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides a shortcut way of safely casting an input when you cannot guarantee the <typeparam name="T"></typeparam> is an instance type (i.e., when the C# AS keyword is not applicable)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="input">The input.</param>
|
||||
/// <returns></returns>
|
||||
public static T SafeCast<T>(this object input)
|
||||
{
|
||||
if (ReferenceEquals(null, input) || ReferenceEquals(default(T), input)) return default(T);
|
||||
if (input is T) return (T)input;
|
||||
return default(T);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to convert the input object to the output type using TypeConverters
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
public static Attempt<T> TryConvertTo<T>(this object input)
|
||||
{
|
||||
var result = TryConvertTo(input, typeof(T));
|
||||
return !result.Success ? Attempt<T>.False : new Attempt<T>(true, (T)result.Result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to convert the input object to the output type using TypeConverters. If the destination type is a superclass of the input type,
|
||||
/// if will use <see cref="Convert.ChangeType(object,System.Type)"/>.
|
||||
/// </summary>
|
||||
/// <param name="input">The input.</param>
|
||||
/// <param name="destinationType">Type of the destination.</param>
|
||||
/// <returns></returns>
|
||||
public static Attempt<object> TryConvertTo(this object input, Type destinationType)
|
||||
{
|
||||
if (input == null) return Attempt<object>.False;
|
||||
|
||||
if (destinationType == typeof(object)) return new Attempt<object>(true, input);
|
||||
|
||||
if (input.GetType() == destinationType) return new Attempt<object>(true, input);
|
||||
|
||||
if (!destinationType.IsGenericType || destinationType.GetGenericTypeDefinition() != typeof(Nullable<>))
|
||||
{
|
||||
if (TypeHelper.IsTypeAssignableFrom(destinationType, input.GetType())
|
||||
&& TypeHelper.IsTypeAssignableFrom<IConvertible>(input))
|
||||
{
|
||||
var casted = Convert.ChangeType(input, destinationType);
|
||||
return new Attempt<object>(true, casted);
|
||||
}
|
||||
}
|
||||
|
||||
var inputConverter = TypeDescriptor.GetConverter(input);
|
||||
if (inputConverter != null)
|
||||
{
|
||||
if (inputConverter.CanConvertTo(destinationType))
|
||||
{
|
||||
return new Attempt<object>(true, inputConverter.ConvertTo(input, destinationType));
|
||||
}
|
||||
}
|
||||
|
||||
if (destinationType == typeof(bool))
|
||||
{
|
||||
var boolConverter = new CustomBooleanTypeConverter();
|
||||
if (boolConverter.CanConvertFrom(input.GetType()))
|
||||
{
|
||||
return new Attempt<object>(true, boolConverter.ConvertFrom(input));
|
||||
}
|
||||
}
|
||||
|
||||
var outputConverter = TypeDescriptor.GetConverter(destinationType);
|
||||
if (outputConverter != null)
|
||||
{
|
||||
if (outputConverter.CanConvertFrom(input.GetType()))
|
||||
{
|
||||
return new Attempt<object>(true, outputConverter.ConvertFrom(input));
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (TypeHelper.IsTypeAssignableFrom<IConvertible>(input))
|
||||
{
|
||||
var casted = Convert.ChangeType(input, destinationType);
|
||||
return new Attempt<object>(true, casted);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
/* Swallow */
|
||||
}
|
||||
|
||||
return Attempt<object>.False;
|
||||
}
|
||||
|
||||
public static void CheckThrowObjectDisposed(this IDisposable disposable, bool isDisposed, string objectname)
|
||||
{
|
||||
//TODO: Localise this exception
|
||||
if (isDisposed)
|
||||
throw new ObjectDisposedException(objectname);
|
||||
}
|
||||
|
||||
//public enum PropertyNamesCaseType
|
||||
//{
|
||||
// CamelCase,
|
||||
// CaseInsensitive
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// Convert an object to a JSON string with camelCase formatting
|
||||
///// </summary>
|
||||
///// <param name="obj"></param>
|
||||
///// <returns></returns>
|
||||
//public static string ToJsonString(this object obj)
|
||||
//{
|
||||
// return obj.ToJsonString(PropertyNamesCaseType.CamelCase);
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// Convert an object to a JSON string with the specified formatting
|
||||
///// </summary>
|
||||
///// <param name="obj">The obj.</param>
|
||||
///// <param name="propertyNamesCaseType">Type of the property names case.</param>
|
||||
///// <returns></returns>
|
||||
//public static string ToJsonString(this object obj, PropertyNamesCaseType propertyNamesCaseType)
|
||||
//{
|
||||
// var type = obj.GetType();
|
||||
// var dateTimeStyle = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
// if (type.IsPrimitive || typeof(string).IsAssignableFrom(type))
|
||||
// {
|
||||
// return obj.ToString();
|
||||
// }
|
||||
|
||||
// if (typeof(DateTime).IsAssignableFrom(type) || typeof(DateTimeOffset).IsAssignableFrom(type))
|
||||
// {
|
||||
// return Convert.ToDateTime(obj).ToString(dateTimeStyle);
|
||||
// }
|
||||
|
||||
// var serializer = new JsonSerializer();
|
||||
|
||||
// switch (propertyNamesCaseType)
|
||||
// {
|
||||
// case PropertyNamesCaseType.CamelCase:
|
||||
// serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
|
||||
// break;
|
||||
// }
|
||||
|
||||
// var dateTimeConverter = new IsoDateTimeConverter
|
||||
// {
|
||||
// DateTimeStyles = System.Globalization.DateTimeStyles.None,
|
||||
// DateTimeFormat = dateTimeStyle
|
||||
// };
|
||||
|
||||
// if (typeof(IDictionary).IsAssignableFrom(type))
|
||||
// {
|
||||
// return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter);
|
||||
// }
|
||||
|
||||
// if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type)))
|
||||
// {
|
||||
// return JArray.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter);
|
||||
// }
|
||||
|
||||
// return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter);
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// Converts an object into a dictionary
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TProperty"></typeparam>
|
||||
/// <typeparam name="TVal"> </typeparam>
|
||||
/// <param name="o"></param>
|
||||
/// <param name="ignoreProperties"></param>
|
||||
/// <returns></returns>
|
||||
public static IDictionary<string, TVal> ToDictionary<T, TProperty, TVal>(this T o,
|
||||
params Expression<Func<T, TProperty>>[] ignoreProperties)
|
||||
{
|
||||
return o.ToDictionary<TVal>(ignoreProperties.Select(e => o.GetPropertyInfo(e)).Select(propInfo => propInfo.Name).ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns object into dictionary
|
||||
/// </summary>
|
||||
/// <param name="o"></param>
|
||||
/// <param name="ignoreProperties">Properties to ignore</param>
|
||||
/// <returns></returns>
|
||||
public static IDictionary<string, TVal> ToDictionary<TVal>(this object o, params string[] ignoreProperties)
|
||||
{
|
||||
if (o != null)
|
||||
{
|
||||
var props = TypeDescriptor.GetProperties(o);
|
||||
var d = new Dictionary<string, TVal>();
|
||||
foreach (var prop in props.Cast<PropertyDescriptor>().Where(x => !ignoreProperties.Contains(x.Name)))
|
||||
{
|
||||
var val = prop.GetValue(o);
|
||||
if (val != null)
|
||||
{
|
||||
d.Add(prop.Name, (TVal)val);
|
||||
}
|
||||
}
|
||||
return d;
|
||||
}
|
||||
return new Dictionary<string, TVal>();
|
||||
}
|
||||
|
||||
public static string ToDebugString(this object obj, int levels = 0)
|
||||
{
|
||||
if (obj == null) return "{null}";
|
||||
try
|
||||
{
|
||||
if (obj is string)
|
||||
{
|
||||
return "\"{0}\"".InvariantFormat(obj);
|
||||
}
|
||||
if (obj is int || obj is Int16 || obj is Int64 || obj is double || obj is bool || obj is int? || obj is Int16? || obj is Int64? || obj is double? || obj is bool?)
|
||||
{
|
||||
return "{0}".InvariantFormat(obj);
|
||||
}
|
||||
if (obj is Enum)
|
||||
{
|
||||
return "[{0}]".InvariantFormat(obj);
|
||||
}
|
||||
if (obj is IEnumerable)
|
||||
{
|
||||
var enumerable = (obj as IEnumerable);
|
||||
|
||||
var items = (from object enumItem in enumerable let value = GetEnumPropertyDebugString(enumItem, levels) where value != null select value).Take(10).ToList();
|
||||
|
||||
return items.Count() > 0
|
||||
? "{{ {0} }}".InvariantFormat(String.Join(", ", items))
|
||||
: null;
|
||||
}
|
||||
|
||||
var props = obj.GetType().GetProperties();
|
||||
if ((props.Count() == 2) && props[0].Name == "Key" && props[1].Name == "Value" && levels > -2)
|
||||
{
|
||||
try
|
||||
{
|
||||
var key = props[0].GetValue(obj, null) as string;
|
||||
var value = props[1].GetValue(obj, null).ToDebugString(levels - 1);
|
||||
return "{0}={1}".InvariantFormat(key, value);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return "[KeyValuePropertyException]";
|
||||
}
|
||||
}
|
||||
if (levels > -1)
|
||||
{
|
||||
var items =
|
||||
from propertyInfo in props
|
||||
let value = GetPropertyDebugString(propertyInfo, obj, levels)
|
||||
where value != null
|
||||
select "{0}={1}".InvariantFormat(propertyInfo.Name, value);
|
||||
|
||||
return items.Count() > 0
|
||||
? "[{0}]:{{ {1} }}".InvariantFormat(obj.GetType().Name, String.Join(", ", items))
|
||||
: null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return "[Exception:{0}]".InvariantFormat(ex.Message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to serialize the value to an XmlString using ToXmlString
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public static Attempt<string> TryConvertToXmlString(this object value, Type type)
|
||||
{
|
||||
try
|
||||
{
|
||||
var output = value.ToXmlString(type);
|
||||
return new Attempt<string>(true, output);
|
||||
}
|
||||
catch (NotSupportedException ex)
|
||||
{
|
||||
return new Attempt<string>(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an XmlSerialized safe string representation for the value
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="type">The Type can only be a primitive type or Guid and byte[] otherwise an exception is thrown</param>
|
||||
/// <returns></returns>
|
||||
public static string ToXmlString(this object value, Type type)
|
||||
{
|
||||
if (type == typeof(string)) return ((string)value).IsNullOrWhiteSpace() ? "" : (string)value;
|
||||
if (type == typeof(bool)) return XmlConvert.ToString((bool)value);
|
||||
if (type == typeof(byte)) return XmlConvert.ToString((byte)value);
|
||||
if (type == typeof(char)) return XmlConvert.ToString((char)value);
|
||||
if (type == typeof(DateTime)) return XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind);
|
||||
if (type == typeof(DateTimeOffset)) return XmlConvert.ToString((DateTimeOffset)value);
|
||||
if (type == typeof(decimal)) return XmlConvert.ToString((decimal)value);
|
||||
if (type == typeof(double)) return XmlConvert.ToString((double)value);
|
||||
if (type == typeof(float)) return XmlConvert.ToString((float)value);
|
||||
if (type == typeof(Guid)) return XmlConvert.ToString((Guid)value);
|
||||
if (type == typeof(int)) return XmlConvert.ToString((int)value);
|
||||
if (type == typeof(long)) return XmlConvert.ToString((long)value);
|
||||
if (type == typeof(sbyte)) return XmlConvert.ToString((sbyte)value);
|
||||
if (type == typeof(short)) return XmlConvert.ToString((short)value);
|
||||
if (type == typeof(TimeSpan)) return XmlConvert.ToString((TimeSpan)value);
|
||||
if (type == typeof(bool)) return XmlConvert.ToString((bool)value);
|
||||
if (type == typeof(uint)) return XmlConvert.ToString((uint)value);
|
||||
if (type == typeof(ulong)) return XmlConvert.ToString((ulong)value);
|
||||
if (type == typeof(ushort)) return XmlConvert.ToString((ushort)value);
|
||||
|
||||
throw new NotSupportedException("Cannot convert type " + type.FullName + " to a string using ToXmlString as it is not supported by XmlConvert");
|
||||
}
|
||||
|
||||
private static string GetEnumPropertyDebugString(object enumItem, int levels)
|
||||
{
|
||||
try
|
||||
{
|
||||
return enumItem.ToDebugString(levels - 1);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return "[GetEnumPartException]";
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetPropertyDebugString(PropertyInfo propertyInfo, object obj, int levels)
|
||||
{
|
||||
try
|
||||
{
|
||||
return propertyInfo.GetValue(obj, null).ToDebugString(levels - 1);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return "[GetPropertyValueException]";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ using System.Web;
|
||||
|
||||
namespace Umbraco.Core
|
||||
{
|
||||
|
||||
///<summary>
|
||||
/// String extension methods
|
||||
///</summary>
|
||||
@@ -29,6 +30,50 @@ namespace Umbraco.Core
|
||||
return value.TrimEnd(forRemoving).TrimStart(forRemoving);
|
||||
}
|
||||
|
||||
public static string EncodeJsString(this string s)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var c in s)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '\"':
|
||||
sb.Append("\\\"");
|
||||
break;
|
||||
case '\\':
|
||||
sb.Append("\\\\");
|
||||
break;
|
||||
case '\b':
|
||||
sb.Append("\\b");
|
||||
break;
|
||||
case '\f':
|
||||
sb.Append("\\f");
|
||||
break;
|
||||
case '\n':
|
||||
sb.Append("\\n");
|
||||
break;
|
||||
case '\r':
|
||||
sb.Append("\\r");
|
||||
break;
|
||||
case '\t':
|
||||
sb.Append("\\t");
|
||||
break;
|
||||
default:
|
||||
int i = (int)c;
|
||||
if (i < 32 || i > 127)
|
||||
{
|
||||
sb.AppendFormat("\\u{0:X04}", i);
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(c);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static string TrimEnd(this string value, string forRemoving)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value)) return value;
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Umbraco.Core
|
||||
/// A utility class for type checking, this provides internal caching so that calls to these methods will be faster
|
||||
/// than doing a manual type check in c#
|
||||
/// </summary>
|
||||
public static class TypeHelper
|
||||
internal static class TypeHelper
|
||||
{
|
||||
private static readonly ConcurrentDictionary<Tuple<Type, Type>, bool> TypeCheckCache = new ConcurrentDictionary<Tuple<Type, Type>, bool>();
|
||||
private static readonly ConcurrentDictionary<Type, bool> ValueTypeCache = new ConcurrentDictionary<Type, bool>();
|
||||
|
||||
@@ -49,8 +49,10 @@
|
||||
<Link>Properties\SolutionInfo.cs</Link>
|
||||
</Compile>
|
||||
<Compile Include="ApplicationContext.cs" />
|
||||
<Compile Include="Attempt.cs" />
|
||||
<Compile Include="Configuration\GlobalSettings.cs" />
|
||||
<Compile Include="Configuration\UmbracoSettings.cs" />
|
||||
<Compile Include="CustomBooleanTypeConverter.cs" />
|
||||
<Compile Include="DisposableObject.cs" />
|
||||
<Compile Include="DisposableTimer.cs" />
|
||||
<Compile Include="ExpressionHelper.cs" />
|
||||
@@ -63,6 +65,7 @@
|
||||
<Compile Include="Logging\AsynchronousRollingFileAppender.cs" />
|
||||
<Compile Include="Logging\LoggingTaskExtension.cs" />
|
||||
<Compile Include="Logging\LogHelper.cs" />
|
||||
<Compile Include="ObjectExtensions.cs" />
|
||||
<Compile Include="RazorDataTypeModelStaticMappingItem.cs" />
|
||||
<Compile Include="Resolving\ManyWeightedResolved.cs" />
|
||||
<Compile Include="Resolving\ManyWeightedResolverBase.cs" />
|
||||
@@ -87,6 +90,7 @@
|
||||
<Compile Include="StringExtensions.cs" />
|
||||
<Compile Include="UriExtensions.cs" />
|
||||
<Compile Include="WriteLock.cs" />
|
||||
<Compile Include="XmlExtensions.cs" />
|
||||
<Compile Include="XmlHelper.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
30
src/Umbraco.Core/XmlExtensions.cs
Normal file
30
src/Umbraco.Core/XmlExtensions.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Xml;
|
||||
|
||||
namespace Umbraco.Core
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for xml objects
|
||||
/// </summary>
|
||||
internal static class XmlExtensions
|
||||
{
|
||||
|
||||
public static T AttributeValue<T>(this XmlNode xml, string attributeName)
|
||||
{
|
||||
if (xml == null) throw new ArgumentNullException("xml");
|
||||
if (xml.Attributes == null) return default(T);
|
||||
|
||||
if (xml.Attributes[attributeName] == null)
|
||||
return default(T);
|
||||
|
||||
var val = xml.Attributes[attributeName].Value;
|
||||
var result = val.TryConvertTo<T>();
|
||||
if (result.Success)
|
||||
return result.Result;
|
||||
|
||||
return default(T);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ namespace Umbraco.Core
|
||||
/// </summary>
|
||||
internal class XmlHelper
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
/// <summary>
|
||||
/// Imports a XML node from text.
|
||||
/// </summary>
|
||||
/// <param name="text">The text.</param>
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Threading;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Core.Logging;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using log4net;
|
||||
using log4net.Config;
|
||||
using log4net.Core;
|
||||
@@ -15,7 +16,7 @@ using log4net.Repository;
|
||||
namespace Umbraco.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class AsynchronousRollingFileAppenderTest
|
||||
public class AsynchronousRollingFileAppenderTests
|
||||
{
|
||||
private const string ErrorMessage = "TEST ERROR MESSAGE";
|
||||
private string _fileFolderPath = @"c:\LogTesting\";
|
||||
75
src/Umbraco.Tests/ContentStoreTests.cs
Normal file
75
src/Umbraco.Tests/ContentStoreTests.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using System.Xml;
|
||||
using NUnit.Framework;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using Umbraco.Web;
|
||||
using Umbraco.Web.Routing;
|
||||
using umbraco.BusinessLogic;
|
||||
|
||||
namespace Umbraco.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public class ContentStoreTests
|
||||
{
|
||||
private FakeHttpContextFactory _httpContextFactory;
|
||||
private UmbracoContext _umbracoContext;
|
||||
private ContentStore _contentStore;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_httpContextFactory = new FakeHttpContextFactory("~/Home");
|
||||
//ensure the StateHelper is using our custom context
|
||||
StateHelper.HttpContext = _httpContextFactory.HttpContext;
|
||||
|
||||
_umbracoContext = new UmbracoContext(_httpContextFactory.HttpContext,
|
||||
new ApplicationContext(),
|
||||
new DefaultRoutesCache(false));
|
||||
|
||||
_umbracoContext.GetXmlDelegate = () =>
|
||||
{
|
||||
var xDoc = new XmlDocument();
|
||||
|
||||
//create a custom xml structure to return
|
||||
|
||||
xDoc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?><!DOCTYPE root[
|
||||
<!ELEMENT Home ANY>
|
||||
<!ATTLIST Home id ID #REQUIRED>
|
||||
|
||||
]>
|
||||
<root id=""-1"">
|
||||
<Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc=""""><content><![CDATA[]]></content>
|
||||
<Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc=""""><content><![CDATA[]]></content>
|
||||
<Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc=""""><content><![CDATA[]]></content>
|
||||
</Home>
|
||||
<Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc=""""><content><![CDATA[]]></content>
|
||||
</Home>
|
||||
</Home>
|
||||
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
|
||||
</Home>
|
||||
</Home>
|
||||
<Home id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""1045"" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" />
|
||||
</root>");
|
||||
//return the custom x doc
|
||||
return xDoc;
|
||||
};
|
||||
|
||||
_contentStore = new ContentStore(_umbracoContext);
|
||||
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Get_Node_By_Route()
|
||||
{
|
||||
var result = _contentStore.GetNodeByRoute("/");
|
||||
Assert.IsNotNull(result);
|
||||
Assert.AreEqual(1046, result.AttributeValue<int>("id"));
|
||||
}
|
||||
}
|
||||
}
|
||||
96
src/Umbraco.Tests/TestHelpers/FakeHttpContextFactory.cs
Normal file
96
src/Umbraco.Tests/TestHelpers/FakeHttpContextFactory.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
using System.Web.Routing;
|
||||
using Rhino.Mocks;
|
||||
|
||||
namespace Umbraco.Tests.TestHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a mock http context with supporting other contexts to test against
|
||||
/// </summary>
|
||||
public class FakeHttpContextFactory
|
||||
{
|
||||
|
||||
[SecuritySafeCritical]
|
||||
public FakeHttpContextFactory(Uri fullUrl)
|
||||
{
|
||||
CreateContext(fullUrl);
|
||||
}
|
||||
|
||||
[SecuritySafeCritical]
|
||||
public FakeHttpContextFactory(string path)
|
||||
{
|
||||
CreateContext(new Uri("http://mysite" + VirtualPathUtility.ToAbsolute(path, "/")));
|
||||
}
|
||||
|
||||
[SecuritySafeCritical]
|
||||
public FakeHttpContextFactory(string path, RouteData routeData)
|
||||
{
|
||||
CreateContext(new Uri("http://mysite" + VirtualPathUtility.ToAbsolute(path, "/")), routeData);
|
||||
}
|
||||
|
||||
public HttpContextBase HttpContext { get; private set; }
|
||||
public RequestContext RequestContext { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Mocks the http context to test against
|
||||
/// </summary>
|
||||
/// <param name="fullUrl"></param>
|
||||
/// <param name="routeData"></param>
|
||||
/// <returns></returns>
|
||||
private void CreateContext(Uri fullUrl, RouteData routeData = null)
|
||||
{
|
||||
//Request context
|
||||
|
||||
RequestContext = MockRepository.GenerateMock<RequestContext>();
|
||||
|
||||
//Request
|
||||
|
||||
var request = MockRepository.GenerateMock<HttpRequestBase>();
|
||||
request.Stub(x => x.AppRelativeCurrentExecutionFilePath).Return("~" + fullUrl.AbsolutePath);
|
||||
request.Stub(x => x.PathInfo).Return(string.Empty);
|
||||
request.Stub(x => x.RawUrl).Return(VirtualPathUtility.ToAbsolute("~" + fullUrl.AbsolutePath, "/"));
|
||||
request.Stub(x => x.RequestContext).Return(RequestContext);
|
||||
request.Stub(x => x.Url).Return(fullUrl);
|
||||
request.Stub(x => x.ApplicationPath).Return("/");
|
||||
request.Stub(x => x.Cookies).Return(new HttpCookieCollection());
|
||||
request.Stub(x => x.ServerVariables).Return(new NameValueCollection());
|
||||
|
||||
//Cache
|
||||
var cache = MockRepository.GenerateMock<HttpCachePolicyBase>();
|
||||
|
||||
//Response
|
||||
//var response = new FakeHttpResponse();
|
||||
var response = MockRepository.GenerateMock<HttpResponseBase>();
|
||||
response.Stub(x => x.ApplyAppPathModifier(null)).IgnoreArguments().Do(new Func<string, string>(appPath => appPath));
|
||||
response.Stub(x => x.Cache).Return(cache);
|
||||
|
||||
//Server
|
||||
|
||||
var server = MockRepository.GenerateStub<HttpServerUtilityBase>();
|
||||
server.Stub(x => x.MapPath(Arg<string>.Is.Anything)).Return(Environment.CurrentDirectory);
|
||||
|
||||
//HTTP Context
|
||||
|
||||
HttpContext = MockRepository.GenerateMock<HttpContextBase>();
|
||||
HttpContext.Stub(x => x.Cache).Return(HttpRuntime.Cache);
|
||||
HttpContext.Stub(x => x.Items).Return(new Dictionary<object, object>());
|
||||
HttpContext.Stub(x => x.Request).Return(request);
|
||||
HttpContext.Stub(x => x.Server).Return(server);
|
||||
HttpContext.Stub(x => x.Response).Return(response);
|
||||
|
||||
RequestContext.Stub(x => x.HttpContext).Return(HttpContext);
|
||||
|
||||
if (routeData != null)
|
||||
{
|
||||
RequestContext.Stub(x => x.RouteData).Return(routeData);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Umbraco.Tests
|
||||
namespace Umbraco.Tests.TestHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Common helper properties and methods useful to testing
|
||||
@@ -8,6 +8,7 @@ using SqlCE4Umbraco;
|
||||
using Umbraco.Core;
|
||||
using Umbraco.Tests;
|
||||
using Umbraco.Tests.PartialTrust;
|
||||
using Umbraco.Tests.TestHelpers;
|
||||
using umbraco;
|
||||
using umbraco.DataLayer;
|
||||
using umbraco.MacroEngines;
|
||||
|
||||
@@ -37,6 +37,9 @@
|
||||
<Reference Include="nunit.framework">
|
||||
<HintPath>..\packages\NUnit.2.6.0.12054\lib\nunit.framework.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Rhino.Mocks">
|
||||
<HintPath>..\packages\RhinoMocks.3.6.1\lib\net\Rhino.Mocks.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.configuration" />
|
||||
<Reference Include="System.Core" />
|
||||
@@ -49,10 +52,11 @@
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="AsynchronousRollingFileAppenderTest.cs" />
|
||||
<Compile Include="AsynchronousRollingFileAppenderTests.cs" />
|
||||
<Compile Include="BusinessLogic\ApplicationTest.cs" />
|
||||
<Compile Include="BusinessLogic\ApplicationTreeTest.cs" />
|
||||
<Compile Include="BusinessLogic\BaseTest.cs" />
|
||||
<Compile Include="ContentStoreTests.cs" />
|
||||
<Compile Include="DataTypeFactoryTests.cs" />
|
||||
<Compile Include="MacroControlFactoryTests.cs" />
|
||||
<Compile Include="MacroEngineFactoryTests.cs" />
|
||||
@@ -60,7 +64,7 @@
|
||||
<Compile Include="PackageActionFactoryTests.cs" />
|
||||
<Compile Include="PluginTypeResolverExtensions.cs" />
|
||||
<Compile Include="PluginTypeResolverTests.cs" />
|
||||
<Compile Include="TestHelper.cs" />
|
||||
<Compile Include="TestHelpers\TestHelper.cs" />
|
||||
<Compile Include="EnumerableExtensionsTests.cs" />
|
||||
<Compile Include="PartialTrust\AbstractPartialTrustFixture.cs" />
|
||||
<Compile Include="PartialTrust\IPartialTrustFixture.cs" />
|
||||
@@ -71,6 +75,7 @@
|
||||
<Compile Include="PartialTrust\TestOnlyInFullTrustAttribute.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="StringExtensionsTests.cs" />
|
||||
<Compile Include="TestHelpers\FakeHttpContextFactory.cs" />
|
||||
<Compile Include="TypeFinderTests.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -2,4 +2,5 @@
|
||||
<packages>
|
||||
<package id="log4net" version="2.0.0" targetFramework="net40" />
|
||||
<package id="NUnit" version="2.6.0.12054" targetFramework="net40" />
|
||||
<package id="RhinoMocks" version="3.6.1" targetFramework="net40" />
|
||||
</packages>
|
||||
@@ -14,3 +14,5 @@ using System.Runtime.CompilerServices;
|
||||
//tg forcing .NET 2.0 security rules, since otherwise it wasn't possible to run in medium trust
|
||||
//(got an inheritance security rules violated by type error)
|
||||
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
|
||||
|
||||
[assembly: InternalsVisibleTo("Umbraco.Tests")]
|
||||
|
||||
@@ -17,23 +17,33 @@ namespace Umbraco.Web.Routing
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DefaultRoutesCache"/> class.
|
||||
/// </summary>
|
||||
public DefaultRoutesCache()
|
||||
public DefaultRoutesCache() : this(true)
|
||||
{
|
||||
Clear();
|
||||
|
||||
//FIXME:
|
||||
//
|
||||
// here we must register handlers to clear the cache when content changes
|
||||
// this was done by presentation.library, which cleared everything when content changed
|
||||
// but really, we should do some partial refreshes
|
||||
|
||||
// these are the two events that were used by presentation.library
|
||||
// are they enough?
|
||||
|
||||
global::umbraco.content.AfterRefreshContent += (sender, e) => Clear();
|
||||
global::umbraco.content.AfterUpdateDocumentCache += (sender, e) => Clear();
|
||||
|
||||
}
|
||||
|
||||
internal DefaultRoutesCache(bool bindToEvents)
|
||||
{
|
||||
Clear();
|
||||
|
||||
if (bindToEvents)
|
||||
{
|
||||
//FIXME:
|
||||
//
|
||||
// here we must register handlers to clear the cache when content changes
|
||||
// this was done by presentation.library, which cleared everything when content changed
|
||||
// but really, we should do some partial refreshes
|
||||
|
||||
// these are the two events that were used by presentation.library
|
||||
// are they enough?
|
||||
|
||||
global::umbraco.content.AfterRefreshContent += (sender, e) => Clear();
|
||||
global::umbraco.content.AfterUpdateDocumentCache += (sender, e) => Clear();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores a route for a node.
|
||||
/// </summary>
|
||||
|
||||
@@ -142,6 +142,40 @@ namespace Umbraco.Web
|
||||
/// <remarks>That is, lowercase, no trailing slash after path, no .aspx...</remarks>
|
||||
internal Uri UmbracoUrl { get; set; }
|
||||
|
||||
private Func<XmlDocument> _xmlDelegate;
|
||||
|
||||
/// <summary>
|
||||
/// Gets/sets the delegate used to retreive the Xml content, generally the setter is only used for unit tests
|
||||
/// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request
|
||||
/// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff
|
||||
/// that when run inside of a unit test fails.
|
||||
/// </remarks>
|
||||
internal Func<XmlDocument> GetXmlDelegate
|
||||
{
|
||||
get
|
||||
{
|
||||
return _xmlDelegate ?? (_xmlDelegate = () =>
|
||||
{
|
||||
if (InPreviewMode)
|
||||
{
|
||||
if (_previewContent == null)
|
||||
{
|
||||
_previewContent = new PreviewContent(UmbracoUser, new Guid(StateHelper.Cookies.Preview.GetValue()), true);
|
||||
if (_previewContent.ValidPreviewSet)
|
||||
_previewContent.LoadPreviewset();
|
||||
}
|
||||
if (_previewContent.ValidPreviewSet)
|
||||
return _previewContent.XmlContent;
|
||||
}
|
||||
return content.Instance.XmlContent;
|
||||
});
|
||||
}
|
||||
set { _xmlDelegate = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the XML Cache document
|
||||
/// </summary>
|
||||
@@ -152,19 +186,7 @@ namespace Umbraco.Web
|
||||
/// </remarks>
|
||||
internal XmlDocument GetXml()
|
||||
{
|
||||
if (InPreviewMode)
|
||||
{
|
||||
if (_previewContent == null)
|
||||
{
|
||||
_previewContent = new PreviewContent(UmbracoUser, new Guid(StateHelper.Cookies.Preview.GetValue()), true);
|
||||
if (_previewContent.ValidPreviewSet)
|
||||
_previewContent.LoadPreviewset();
|
||||
}
|
||||
if (_previewContent.ValidPreviewSet)
|
||||
return _previewContent.XmlContent;
|
||||
}
|
||||
return content.Instance.XmlContent;
|
||||
|
||||
return GetXmlDelegate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
BIN
src/packages/RhinoMocks.3.6.1/RhinoMocks.3.6.1.nupkg
vendored
Normal file
BIN
src/packages/RhinoMocks.3.6.1/RhinoMocks.3.6.1.nupkg
vendored
Normal file
Binary file not shown.
BIN
src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.dll
vendored
Normal file
BIN
src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.dll
vendored
Normal file
Binary file not shown.
5624
src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.xml
vendored
Normal file
5624
src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.xml
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,31 @@ namespace umbraco.BusinessLogic
|
||||
/// The StateHelper class provides general helper methods for handling sessions, context, viewstate and cookies.
|
||||
/// </summary>
|
||||
public class StateHelper
|
||||
{
|
||||
{
|
||||
|
||||
private static HttpContextBase _httpContext;
|
||||
|
||||
/// <summary>
|
||||
/// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will
|
||||
/// use the HttpContext.Current
|
||||
/// </summary>
|
||||
internal static HttpContextBase HttpContext
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_httpContext == null && System.Web.HttpContext.Current != null)
|
||||
{
|
||||
_httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
|
||||
}
|
||||
else if (_httpContext == null && System.Web.HttpContext.Current == null)
|
||||
{
|
||||
throw new NullReferenceException("The HttpContext property has not been set or the object execution is not running inside of an HttpContext");
|
||||
}
|
||||
return _httpContext;
|
||||
}
|
||||
set { _httpContext = value; }
|
||||
}
|
||||
|
||||
#region Session Helpers
|
||||
|
||||
/// <summary>
|
||||
@@ -20,7 +44,7 @@ namespace umbraco.BusinessLogic
|
||||
/// <returns></returns>
|
||||
public static T GetSessionValue<T>(string key)
|
||||
{
|
||||
return GetSessionValue<T>(HttpContext.Current, key);
|
||||
return GetSessionValue<T>(HttpContext, key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -30,7 +54,20 @@ namespace umbraco.BusinessLogic
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns></returns>
|
||||
[Obsolete("Use the GetSessionValue accepting an HttpContextBase instead")]
|
||||
public static T GetSessionValue<T>(HttpContext context, string key)
|
||||
{
|
||||
return GetSessionValue<T>(new HttpContextWrapper(context), key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the session value.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns></returns>
|
||||
public static T GetSessionValue<T>(HttpContextBase context, string key)
|
||||
{
|
||||
if (context == null)
|
||||
return default(T);
|
||||
@@ -47,7 +84,7 @@ namespace umbraco.BusinessLogic
|
||||
/// <param name="value">The value.</param>
|
||||
public static void SetSessionValue(string key, object value)
|
||||
{
|
||||
SetSessionValue(HttpContext.Current, key, value);
|
||||
SetSessionValue(HttpContext, key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -56,7 +93,19 @@ namespace umbraco.BusinessLogic
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
[Obsolete("Use the SetSessionValue accepting an HttpContextBase instead")]
|
||||
public static void SetSessionValue(HttpContext context, string key, object value)
|
||||
{
|
||||
SetSessionValue(new HttpContextWrapper(context), key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the session value.
|
||||
/// </summary>
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
public static void SetSessionValue(HttpContextBase context, string key, object value)
|
||||
{
|
||||
if (context == null)
|
||||
return;
|
||||
@@ -75,7 +124,7 @@ namespace umbraco.BusinessLogic
|
||||
/// <returns></returns>
|
||||
public static T GetContextValue<T>(string key)
|
||||
{
|
||||
return GetContextValue<T>(HttpContext.Current, key);
|
||||
return GetContextValue<T>(HttpContext, key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -85,7 +134,20 @@ namespace umbraco.BusinessLogic
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns></returns>
|
||||
[Obsolete("Use the GetContextValue accepting an HttpContextBase instead")]
|
||||
public static T GetContextValue<T>(HttpContext context, string key)
|
||||
{
|
||||
return GetContextValue<T>(new HttpContextWrapper(context), key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the context value.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns></returns>
|
||||
public static T GetContextValue<T>(HttpContextBase context, string key)
|
||||
{
|
||||
if (context == null)
|
||||
return default(T);
|
||||
@@ -102,7 +164,7 @@ namespace umbraco.BusinessLogic
|
||||
/// <param name="value">The value.</param>
|
||||
public static void SetContextValue(string key, object value)
|
||||
{
|
||||
SetContextValue(HttpContext.Current, key, value);
|
||||
SetContextValue(HttpContext, key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -111,7 +173,19 @@ namespace umbraco.BusinessLogic
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
[Obsolete("Use the SetContextValue accepting an HttpContextBase instead")]
|
||||
public static void SetContextValue(HttpContext context, string key, object value)
|
||||
{
|
||||
SetContextValue(new HttpContextWrapper(context), key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the context value.
|
||||
/// </summary>
|
||||
/// <param name="context">The context.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="value">The value.</param>
|
||||
public static void SetContextValue(HttpContextBase context, string key, object value)
|
||||
{
|
||||
if (context == null)
|
||||
return;
|
||||
@@ -128,15 +202,15 @@ namespace umbraco.BusinessLogic
|
||||
/// <returns></returns>
|
||||
private static StateBag GetStateBag()
|
||||
{
|
||||
if (HttpContext.Current == null)
|
||||
return null;
|
||||
//if (HttpContext.Current == null)
|
||||
// return null;
|
||||
|
||||
Page page = HttpContext.Current.CurrentHandler as Page;
|
||||
var page = HttpContext.CurrentHandler as Page;
|
||||
if (page == null)
|
||||
return null;
|
||||
|
||||
Type pageType = typeof(Page);
|
||||
PropertyInfo viewState = pageType.GetProperty("ViewState", BindingFlags.GetProperty | BindingFlags.Instance);
|
||||
var pageType = typeof(Page);
|
||||
var viewState = pageType.GetProperty("ViewState", BindingFlags.GetProperty | BindingFlags.Instance);
|
||||
if (viewState == null)
|
||||
return null;
|
||||
|
||||
@@ -221,7 +295,7 @@ namespace umbraco.BusinessLogic
|
||||
{
|
||||
if (!Cookies.HasCookies)
|
||||
return null;
|
||||
var cookie = HttpContext.Current.Request.Cookies[key];
|
||||
var cookie = HttpContext.Request.Cookies[key];
|
||||
return cookie == null ? null : cookie.Value;
|
||||
}
|
||||
|
||||
@@ -245,7 +319,7 @@ namespace umbraco.BusinessLogic
|
||||
{
|
||||
if (!Cookies.HasCookies)
|
||||
return;
|
||||
var context = HttpContext.Current;
|
||||
var context = HttpContext;
|
||||
|
||||
HttpCookie cookie = new HttpCookie(key, value);
|
||||
cookie.Expires = DateTime.Now.AddDays(daysToPersist);
|
||||
@@ -282,7 +356,7 @@ namespace umbraco.BusinessLogic
|
||||
{
|
||||
get
|
||||
{
|
||||
System.Web.HttpContext context = HttpContext.Current;
|
||||
var context = HttpContext;
|
||||
// although just checking context should be enough?!
|
||||
// but in some (replaced) umbraco code, everything is checked...
|
||||
return context != null
|
||||
@@ -293,7 +367,7 @@ namespace umbraco.BusinessLogic
|
||||
|
||||
public static void ClearAll()
|
||||
{
|
||||
HttpContext.Current.Response.Cookies.Clear();
|
||||
HttpContext.Response.Cookies.Clear();
|
||||
}
|
||||
|
||||
public class Cookie
|
||||
@@ -402,14 +476,14 @@ namespace umbraco.BusinessLogic
|
||||
{
|
||||
// beware! will not clear browser's cookie
|
||||
// you probably want to use .Clear()
|
||||
HttpContext.Current.Response.Cookies.Remove(_key);
|
||||
HttpContext.Response.Cookies.Remove(_key);
|
||||
}
|
||||
|
||||
public HttpCookie RequestCookie
|
||||
{
|
||||
get
|
||||
{
|
||||
return HttpContext.Current.Request.Cookies[_key];
|
||||
return HttpContext.Request.Cookies[_key];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,13 +491,13 @@ namespace umbraco.BusinessLogic
|
||||
{
|
||||
get
|
||||
{
|
||||
return HttpContext.Current.Response.Cookies[_key];
|
||||
return HttpContext.Response.Cookies[_key];
|
||||
}
|
||||
set
|
||||
{
|
||||
// .Set() ensures the uniqueness of cookies in the cookie collection
|
||||
// ie it is the same as .Remove() + .Add() -- .Add() allows duplicates
|
||||
HttpContext.Current.Response.Cookies.Set(value);
|
||||
HttpContext.Response.Cookies.Set(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user