diff --git a/src/Umbraco.Core/Attempt.cs b/src/Umbraco.Core/Attempt.cs new file mode 100644 index 0000000000..927f68d7a4 --- /dev/null +++ b/src/Umbraco.Core/Attempt.cs @@ -0,0 +1,66 @@ +using System; + +namespace Umbraco.Core +{ + /// + /// Represents the result of an operation attempt + /// + /// + /// + [Serializable] + public struct Attempt + { + private readonly bool _success; + private readonly T _result; + private readonly Exception _error; + + /// + /// Gets a value indicating whether this represents a successful operation. + /// + /// + public bool Success + { + get { return _success; } + } + + /// + /// Gets the error associated with an unsuccessful attempt. + /// + /// The error. + public Exception Error { get { return _error; } } + + /// + /// Gets the parse result. + /// + /// + public T Result + { + get { return _result; } + } + + /// + /// Represents an unsuccessful parse operation + /// + public static readonly Attempt False; + + /// + /// Initializes a new instance of the struct. + /// + /// If set to true this tuple represents a successful parse result. + /// The parse result. + /// + public Attempt(bool success, T result) + { + _success = success; + _result = result; + _error = null; + } + + public Attempt(Exception error) + { + _success = false; + _result = default(T); + _error = error; + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/CustomBooleanTypeConverter.cs b/src/Umbraco.Core/CustomBooleanTypeConverter.cs new file mode 100644 index 0000000000..b7b30d1fa1 --- /dev/null +++ b/src/Umbraco.Core/CustomBooleanTypeConverter.cs @@ -0,0 +1,32 @@ +using System; +using System.ComponentModel; + +namespace Umbraco.Core +{ + /// + /// Allows for converting string representations of 0 and 1 to boolean + /// + 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); + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/ObjectExtensions.cs b/src/Umbraco.Core/ObjectExtensions.cs new file mode 100644 index 0000000000..e19335aba3 --- /dev/null +++ b/src/Umbraco.Core/ObjectExtensions.cs @@ -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> ObjectFactoryCache = new ConcurrentDictionary>(); + + public static IEnumerable AsEnumerableOfOne(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(); + } + + /// + /// Provides a shortcut way of safely casting an input when you cannot guarantee the is an instance type (i.e., when the C# AS keyword is not applicable) + /// + /// + /// The input. + /// + public static T SafeCast(this object input) + { + if (ReferenceEquals(null, input) || ReferenceEquals(default(T), input)) return default(T); + if (input is T) return (T)input; + return default(T); + } + + /// + /// Tries to convert the input object to the output type using TypeConverters + /// + /// + /// + /// + public static Attempt TryConvertTo(this object input) + { + var result = TryConvertTo(input, typeof(T)); + return !result.Success ? Attempt.False : new Attempt(true, (T)result.Result); + } + + /// + /// 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 . + /// + /// The input. + /// Type of the destination. + /// + public static Attempt TryConvertTo(this object input, Type destinationType) + { + if (input == null) return Attempt.False; + + if (destinationType == typeof(object)) return new Attempt(true, input); + + if (input.GetType() == destinationType) return new Attempt(true, input); + + if (!destinationType.IsGenericType || destinationType.GetGenericTypeDefinition() != typeof(Nullable<>)) + { + if (TypeHelper.IsTypeAssignableFrom(destinationType, input.GetType()) + && TypeHelper.IsTypeAssignableFrom(input)) + { + var casted = Convert.ChangeType(input, destinationType); + return new Attempt(true, casted); + } + } + + var inputConverter = TypeDescriptor.GetConverter(input); + if (inputConverter != null) + { + if (inputConverter.CanConvertTo(destinationType)) + { + return new Attempt(true, inputConverter.ConvertTo(input, destinationType)); + } + } + + if (destinationType == typeof(bool)) + { + var boolConverter = new CustomBooleanTypeConverter(); + if (boolConverter.CanConvertFrom(input.GetType())) + { + return new Attempt(true, boolConverter.ConvertFrom(input)); + } + } + + var outputConverter = TypeDescriptor.GetConverter(destinationType); + if (outputConverter != null) + { + if (outputConverter.CanConvertFrom(input.GetType())) + { + return new Attempt(true, outputConverter.ConvertFrom(input)); + } + } + + try + { + if (TypeHelper.IsTypeAssignableFrom(input)) + { + var casted = Convert.ChangeType(input, destinationType); + return new Attempt(true, casted); + } + } + catch (Exception) + { + /* Swallow */ + } + + return Attempt.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 + //} + + ///// + ///// Convert an object to a JSON string with camelCase formatting + ///// + ///// + ///// + //public static string ToJsonString(this object obj) + //{ + // return obj.ToJsonString(PropertyNamesCaseType.CamelCase); + //} + + ///// + ///// Convert an object to a JSON string with the specified formatting + ///// + ///// The obj. + ///// Type of the property names case. + ///// + //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); + //} + + /// + /// Converts an object into a dictionary + /// + /// + /// + /// + /// + /// + /// + public static IDictionary ToDictionary(this T o, + params Expression>[] ignoreProperties) + { + return o.ToDictionary(ignoreProperties.Select(e => o.GetPropertyInfo(e)).Select(propInfo => propInfo.Name).ToArray()); + } + + /// + /// Turns object into dictionary + /// + /// + /// Properties to ignore + /// + public static IDictionary ToDictionary(this object o, params string[] ignoreProperties) + { + if (o != null) + { + var props = TypeDescriptor.GetProperties(o); + var d = new Dictionary(); + foreach (var prop in props.Cast().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(); + } + + 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; + } + + + /// + /// Attempts to serialize the value to an XmlString using ToXmlString + /// + /// + /// + /// + public static Attempt TryConvertToXmlString(this object value, Type type) + { + try + { + var output = value.ToXmlString(type); + return new Attempt(true, output); + } + catch (NotSupportedException ex) + { + return new Attempt(ex); + } + } + + /// + /// Returns an XmlSerialized safe string representation for the value + /// + /// + /// The Type can only be a primitive type or Guid and byte[] otherwise an exception is thrown + /// + 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]"; + } + } + + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 0c2e227317..634f029655 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -12,6 +12,7 @@ using System.Web; namespace Umbraco.Core { + /// /// String extension methods /// @@ -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; diff --git a/src/Umbraco.Core/TypeHelper.cs b/src/Umbraco.Core/TypeHelper.cs index 231c5b3b4c..f61fda920a 100644 --- a/src/Umbraco.Core/TypeHelper.cs +++ b/src/Umbraco.Core/TypeHelper.cs @@ -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# /// - public static class TypeHelper + internal static class TypeHelper { private static readonly ConcurrentDictionary, bool> TypeCheckCache = new ConcurrentDictionary, bool>(); private static readonly ConcurrentDictionary ValueTypeCache = new ConcurrentDictionary(); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index a972e320fe..3106a9d6b3 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -49,8 +49,10 @@ Properties\SolutionInfo.cs + + @@ -63,6 +65,7 @@ + @@ -87,6 +90,7 @@ + diff --git a/src/Umbraco.Core/XmlExtensions.cs b/src/Umbraco.Core/XmlExtensions.cs new file mode 100644 index 0000000000..ab526f6532 --- /dev/null +++ b/src/Umbraco.Core/XmlExtensions.cs @@ -0,0 +1,30 @@ +using System; +using System.Xml; + +namespace Umbraco.Core +{ + + /// + /// Extension methods for xml objects + /// + internal static class XmlExtensions + { + + public static T AttributeValue(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(); + if (result.Success) + return result.Result; + + return default(T); + } + + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/XmlHelper.cs b/src/Umbraco.Core/XmlHelper.cs index eb20fb1595..b30e502672 100644 --- a/src/Umbraco.Core/XmlHelper.cs +++ b/src/Umbraco.Core/XmlHelper.cs @@ -9,7 +9,8 @@ namespace Umbraco.Core /// internal class XmlHelper { - /// + + /// /// Imports a XML node from text. /// /// The text. diff --git a/src/Umbraco.Tests/AsynchronousRollingFileAppenderTest.cs b/src/Umbraco.Tests/AsynchronousRollingFileAppenderTests.cs similarity index 94% rename from src/Umbraco.Tests/AsynchronousRollingFileAppenderTest.cs rename to src/Umbraco.Tests/AsynchronousRollingFileAppenderTests.cs index 7cf976178a..9e49bb3290 100644 --- a/src/Umbraco.Tests/AsynchronousRollingFileAppenderTest.cs +++ b/src/Umbraco.Tests/AsynchronousRollingFileAppenderTests.cs @@ -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\"; diff --git a/src/Umbraco.Tests/ContentStoreTests.cs b/src/Umbraco.Tests/ContentStoreTests.cs new file mode 100644 index 0000000000..331cd5036d --- /dev/null +++ b/src/Umbraco.Tests/ContentStoreTests.cs @@ -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(@" + + +]> + + + + + + + + + + + + +"); + //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("id")); + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Tests/TestHelpers/FakeHttpContextFactory.cs b/src/Umbraco.Tests/TestHelpers/FakeHttpContextFactory.cs new file mode 100644 index 0000000000..572157ff98 --- /dev/null +++ b/src/Umbraco.Tests/TestHelpers/FakeHttpContextFactory.cs @@ -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 +{ + /// + /// Creates a mock http context with supporting other contexts to test against + /// + 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; } + + /// + /// Mocks the http context to test against + /// + /// + /// + /// + private void CreateContext(Uri fullUrl, RouteData routeData = null) + { + //Request context + + RequestContext = MockRepository.GenerateMock(); + + //Request + + var request = MockRepository.GenerateMock(); + 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(); + + //Response + //var response = new FakeHttpResponse(); + var response = MockRepository.GenerateMock(); + response.Stub(x => x.ApplyAppPathModifier(null)).IgnoreArguments().Do(new Func(appPath => appPath)); + response.Stub(x => x.Cache).Return(cache); + + //Server + + var server = MockRepository.GenerateStub(); + server.Stub(x => x.MapPath(Arg.Is.Anything)).Return(Environment.CurrentDirectory); + + //HTTP Context + + HttpContext = MockRepository.GenerateMock(); + HttpContext.Stub(x => x.Cache).Return(HttpRuntime.Cache); + HttpContext.Stub(x => x.Items).Return(new Dictionary()); + 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); + } + } + + } +} diff --git a/src/Umbraco.Tests/TestHelper.cs b/src/Umbraco.Tests/TestHelpers/TestHelper.cs similarity index 93% rename from src/Umbraco.Tests/TestHelper.cs rename to src/Umbraco.Tests/TestHelpers/TestHelper.cs index fce91d4d5e..69b2a52cf4 100644 --- a/src/Umbraco.Tests/TestHelper.cs +++ b/src/Umbraco.Tests/TestHelpers/TestHelper.cs @@ -2,7 +2,7 @@ using System; using System.IO; using System.Reflection; -namespace Umbraco.Tests +namespace Umbraco.Tests.TestHelpers { /// /// Common helper properties and methods useful to testing diff --git a/src/Umbraco.Tests/TypeFinderTests.cs b/src/Umbraco.Tests/TypeFinderTests.cs index 2c61502a78..82c809e030 100644 --- a/src/Umbraco.Tests/TypeFinderTests.cs +++ b/src/Umbraco.Tests/TypeFinderTests.cs @@ -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; diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index e23c094eba..ceffd7db47 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -37,6 +37,9 @@ ..\packages\NUnit.2.6.0.12054\lib\nunit.framework.dll + + ..\packages\RhinoMocks.3.6.1\lib\net\Rhino.Mocks.dll + @@ -49,10 +52,11 @@ - + + @@ -60,7 +64,7 @@ - + @@ -71,6 +75,7 @@ + diff --git a/src/Umbraco.Tests/packages.config b/src/Umbraco.Tests/packages.config index 6c2c554293..ea5bd3ccda 100644 --- a/src/Umbraco.Tests/packages.config +++ b/src/Umbraco.Tests/packages.config @@ -2,4 +2,5 @@ + \ No newline at end of file diff --git a/src/Umbraco.Web/Properties/AssemblyInfo.cs b/src/Umbraco.Web/Properties/AssemblyInfo.cs index c593bb557f..3712c4a64e 100644 --- a/src/Umbraco.Web/Properties/AssemblyInfo.cs +++ b/src/Umbraco.Web/Properties/AssemblyInfo.cs @@ -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")] diff --git a/src/Umbraco.Web/Routing/DefaultRoutesCache.cs b/src/Umbraco.Web/Routing/DefaultRoutesCache.cs index 55a2c08e75..d2b37f2a3a 100644 --- a/src/Umbraco.Web/Routing/DefaultRoutesCache.cs +++ b/src/Umbraco.Web/Routing/DefaultRoutesCache.cs @@ -17,23 +17,33 @@ namespace Umbraco.Web.Routing /// /// Initializes a new instance of the class. /// - 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(); + } + + + } + /// /// Stores a route for a node. /// diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index 806ef7a438..f96497f45a 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -142,6 +142,40 @@ namespace Umbraco.Web /// That is, lowercase, no trailing slash after path, no .aspx... internal Uri UmbracoUrl { get; set; } + private Func _xmlDelegate; + + /// + /// 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 + /// + /// + /// 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. + /// + internal Func 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; } + } + /// /// Returns the XML Cache document /// @@ -152,19 +186,7 @@ namespace Umbraco.Web /// 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(); } /// diff --git a/src/packages/RhinoMocks.3.6.1/RhinoMocks.3.6.1.nupkg b/src/packages/RhinoMocks.3.6.1/RhinoMocks.3.6.1.nupkg new file mode 100644 index 0000000000..2d13fde968 Binary files /dev/null and b/src/packages/RhinoMocks.3.6.1/RhinoMocks.3.6.1.nupkg differ diff --git a/src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.dll b/src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.dll new file mode 100644 index 0000000000..c6f4f53882 Binary files /dev/null and b/src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.dll differ diff --git a/src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.xml b/src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.xml new file mode 100644 index 0000000000..d6ae366d25 --- /dev/null +++ b/src/packages/RhinoMocks.3.6.1/lib/net/Rhino.Mocks.xml @@ -0,0 +1,5624 @@ + + + + Rhino.Mocks + + + + + Defines constraints and return values for arguments of a mock. + Only use Arg inside a method call on a mock that is recording. + Example: + ExpectCall( + mock.foo( + Arg<int>.Is.GreaterThan(2), + Arg<string>.Is.Anything + )); + Use Arg.Text for string specific constraints + Use Arg<ListClass>.List for list specific constraints + + + + + + Register the predicate as a constraint for the current call. + + The predicate. + default(T) + + Allow you to use code to create constraints + + demo.AssertWasCalled(x => x.Bar(Arg{string}.Matches(a => a.StartsWith("b") && a.Contains("ba")))); + + + + + + Define a complex constraint for this argument by passing several constraints + combined with operators. (Use Is in simple cases.) + Example: Arg<string>.Matches(Is.Equal("Hello") || Text.EndsWith("u")); + + Constraints using Is, Text and List + Dummy to satisfy the compiler + + + + Define a Ref argument. + + Constraints for this argument + value returned by the mock + + + + + Define a out parameter. Use it together with the keyword out and use the + Dummy field available by the return value. + Example: mock.foo( out Arg<string>.Out("hello").Dummy ); + + + + + + + Define a simple constraint for this argument. (Use Matches in simple cases.) + Example: + Arg<int>.Is.Anthing + Arg<string>.Is.Equal("hello") + + + + + Define Constraints on list arguments. + + + + + Use the Arg class (without generic) to define Text constraints + + + + + Evaluate an equal constraint for . + + The object the parameter should equal to + + + + Define constraints on text arguments. + + + + + Used to manage the static state of the Arg<T> class"/> + + + + + Resets the static state + + + + + Returns return values for the out and ref parameters + Note: the array returned has the size of the number of out and ref + argument definitions + + + + + + Returns the constraints for all arguments. + Out arguments have an Is.Anything constraint and are also in the list. + + + + + + What should BackToRecord clear + + + + + Retain all expectations and behaviors and return to mock + + + + + All expectations + + + + + Event subscribers for this instance + + + + + Methods that should be forwarded to the base class implementation + + + + + Properties that should behave like properties + + + + + Remove all the behavior of the object + + + + + Interface for constraints + + + + + Determines if the object pass the constraints + + + + + And operator for constraints + + + + + Not operator for constraints + + + + + Or operator for constraints + + + + + Allow overriding of || or && + + + + + + + Allow overriding of || or && + + + + + + + Gets the message for this constraint + + + + + + Constrain that the public field has a specified value + + + + + Constrain that the public field matches another constraint. + + + + + Creates a new instance. + + Name of the public field. + Constraint to place on the public field value. + + + + Creates a new instance, specifying a disambiguating + for the public field. + + The type that declares the public field, used to disambiguate between public fields. + Name of the public field. + Constraint to place on the public field value. + + + + Determines if the object passes the constraint. + + + + + Gets the message for this constraint + + + + + + Creates a new instance. + + Name of the public field. + Expected value. + + + + Creates a new instance, specifying a disambiguating + for the public field. + + The type that declares the public field, used to disambiguate between public fields. + Name of the public field. + Expected value. + + + + Constrain that the property has a specified value + + + + + Constrain that the property matches another constraint. + + + + + Creates a new instance. + + Name of the property. + Constraint to place on the property value. + + + + Creates a new instance, specifying a disambiguating + for the property. + + The type that declares the property, used to disambiguate between properties. + Name of the property. + Constraint to place on the property value. + + + + Determines if the object passes the constraint. + + + + + Gets the message for this constraint + + + + + + Creates a new instance. + + Name of the property. + Expected value. + + + + Creates a new instance, specifying a disambiguating + for the property. + + The type that declares the property, used to disambiguate between properties. + Name of the property. + Expected value. + + + + Constrain that the parameter must be of the specified type + + + + + Creates a new instance. + + Type. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that determines whether an object is the same object as another. + + + + + Creates a new instance. + + Obj. + + + + Determines if the object passes the constraints. + + + + + Gets the message for this constraint. + + + + + Evaluate a parameter using constraints + + + + + Create new instance + + + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + A constraint based on lambda expression, we are using Expression{T} + because we want to be able to get good error reporting on that. + + + + + Initializes a new instance of the class. + + The expr. + + + + Determines if the object pass the constraints + + + + + + + Gets the message for this constraint + + + + + + Constrain that the list contains the same items as the parameter list + + + + + Creates a new instance. + + In list. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constrain that the parameter is one of the items in the list + + + + + Creates a new instance. + + In list. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constrain that the object is inside the parameter list + + + + + Creates a new instance. + + In list. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Applies another AbstractConstraint to the collection count. + + + + + Creates a new instance. + + The constraint that should be applied to the collection count. + + + + Determines if the parameter conforms to this constraint. + + + + + Gets the message for this constraint. + + + + + Applies another AbstractConstraint to a specific list element. + + + + + Creates a new instance. + + The zero-based index of the list element. + The constraint that should be applied to the list element. + + + + Determines if the parameter conforms to this constraint. + + + + + Gets the message for this constraint + + + + + + Applies another AbstractConstraint to a specific generic keyed list element. + + + + + Creates a new instance. + + The key of the list element. + The constraint that should be applied to the list element. + + + + Determines if the parameter conforms to this constraint. + + + + + Gets the message for this constraint + + + + + + Constrains that all elements are in the parameter list + + + + + Initializes a new instance of the class. + + The these. + + + + Determines if the object pass the constraints + + + + + + + Gets the message for this constraint + + + + + + Combines two constraints, constraint pass if either is fine. + + + + + Creates a new instance. + + C1. + C2. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Negate a constraint + + + + + Creates a new instance. + + C1. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Combines two constraints + + + + + + Creates a new instance. + + C1. + C2. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constrain the argument to validate according to regex pattern + + + + + Creates a new instance. + + Pattern. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that evaluate whatever an argument contains the specified string. + + + + + Creates a new instance. + + Inner string. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that evaluate whatever an argument ends with the specified string + + + + + Creates a new instance. + + End. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that evaluate whatever an argument start with the specified string + + + + + Creates a new instance. + + Start. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that evaluate whatever an object equals another + + + + + Creates a new instance. + + Obj. + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that always returns true + + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Constraint that evaluate whatever a comparable is greater than another + + + + + Creates a new instance. + + + + + Determines if the object pass the constraints + + + + + Gets the message for this constraint + + + + + + Initializes a new constraint object. + + The expected object, The actual object is passed in as a parameter to the method + + + + Evaluate this constraint. + + The actual object that was passed in the method call to the mock. + True when the constraint is met, else false. + + + + Checks if the properties of the object + are the same as the properies of the object. + + The expected object + The actual object + True when both objects have the same values, else False. + + + + + + + + + This is the real heart of the beast. + + + + Used by CheckReferenceType to check all properties of the reference type. + + The expected object + The actual object + True when both objects have the same values, else False. + + + + Used by CheckReferenceType to check all fields of the reference type. + + The expected object + The actual object + True when both objects have the same values, else False. + + + + Checks the items of both collections + + The expected collection + + True if both collections contain the same items in the same order. + + + + Builds a propertyname from the Stack _properties like 'Order.Product.Price' + to be used in the error message. + + A nested property name. + + + + Rhino.Mocks uses this property to generate an error message. + + + A message telling the tester why the constraint failed. + + + + + Provides access to the constraintes defined in the class to be used in context + with the syntax. + + The type of the argument + + + + Evaluate a greater than constraint for . + + The object the parameter should be greater than + + + + Evaluate a less than constraint for . + + The object the parameter should be less than + + + + Evaluate a less than or equal constraint for . + + The object the parameter should be less than or equal to + + + + Evaluate a greater than or equal constraint for . + + The object the parameter should be greater than or equal to + + + + Evaluate an equal constraint for . + + The object the parameter should equal to + + + + Converts the object type to a better match if this is a primitive type. + + The obj. + + + + + Converts the object type to match. + + + Because of implicit conversions and the way ArgConstraints this method is needed to check + object type and potentially change the object type for a better "match" so that obj1.Equals(obj2) + will return the proper "answer" + + The obj. + + + + + Evaluate a not equal constraint for . + + The object the parameter should not equal to + + + + Evaluate a same as constraint. + + The object the parameter should the same as. + + + + Evaluate a not same as constraint. + + The object the parameter should not be the same as. + + + + Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. + + + + + + + Serves as a hash function for a particular type. + + + A hash code for the current . + + + + + A constraints that accept anything + + + + + + A constraint that accept only nulls + + + + + + A constraint that accept only non null values + + + + + + A constraint that accept only value of the specified type. + The check is performed on the type that has been defined + as the argument type. + + + + + Provides access to the constraints defined in the class to be used in context + with the syntax. + + + + + Determines whether the specified object is in the parameter. + The parameter must be IEnumerable. + + Obj. + + + + + Determines whatever the parameter is in the collection. + + + + + Determines that the parameter collection is identical to the specified collection + + + + + Determines that the parameter collection has the specified number of elements. + + The constraint that should be applied to the collection count. + + + + Determines that an element of the parameter collections conforms to another AbstractConstraint. + + The zero-based index of the list element. + The constraint which should be applied to the list element. + + + + Determines that all elements of the specified collection are in the the parameter collection + + The collection to compare against + The constraint which should be applied to the list parameter. + + + + Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. + + + + + + + Serves as a hash function for a particular type. + + + A hash code for the current . + + + + + Provides a dummy field to pass as out or ref argument. + + + + + + Dummy field to satisfy the compiler. Used for out and ref arguments. + + + + + Central location for constraints for object's public fields + + + + + Constrains the parameter to have a public field with the specified value + + Name of the public field. + Expected value. + + + + + Constrains the parameter to have a public field with the specified value. + + The type that declares the public field, used to disambiguate between public fields. + Name of the public field. + Expected value. + + + + + Constrains the parameter to have a public field satisfying a specified constraint. + + Name of the public field. + Constraint for the public field. + + + + Constrains the parameter to have a public field satisfying a specified constraint. + + The type that declares the public field, used to disambiguate between public fields. + Name of the public field. + Constraint for the public field. + + + + Determines whether the parameter has the specified public field and that it is null. + + Name of the public field. + + + + + Determines whether the parameter has the specified public field and that it is null. + + The type that declares the public field, used to disambiguate between public fields. + Name of the public field. + + + + + Determines whether the parameter has the specified public field and that it is not null. + + Name of the public field. + + + + + Determines whether the parameter has the specified public field and that it is not null. + + The type that declares the public field, used to disambiguate between public fields. + Name of the public field. + + + + + Central location for constraints + + + + + Evaluate a greater than constraint for . + + The object the parameter should be greater than + + + + Evaluate a less than constraint for . + + The object the parameter should be less than + + + + Evaluate a less than or equal constraint for . + + The object the parameter should be less than or equal to + + + + Evaluate a greater than or equal constraint for . + + The object the parameter should be greater than or equal to + + + + Evaluate an equal constraint for . + + The object the parameter should equal to + + + + Evaluate a not equal constraint for . + + The object the parameter should not equal to + + + + Evaluate a same as constraint. + + The object the parameter should the same as. + + + + Evaluate a not same as constraint. + + The object the parameter should not be the same as. + + + + A constraints that accept anything + + + + + + A constraint that accept only nulls + + + + + + A constraint that accept only non null values + + + + + + A constraint that accept only value of the specified type + + + + + A constraint that accept only value of the specified type + + + + + Evaluate a parameter using a predicate + + The predicate to use + + + + Central location for constraints about lists and collections + + + + + Determines whether the specified obj is in the parameter. + The parameter must be IEnumerable. + + Obj. + + + + + Determines whatever the parameter is in the collection. + + + + + Determines that the parameter collection is identical to the specified collection + + + + + Determines that the parameter collection has the specified number of elements. + + The constraint that should be applied to the collection count. + + + + Determines that an element of the parameter collections conforms to another AbstractConstraint. + + The zero-based index of the list element. + The constraint which should be applied to the list element. + + + + Determines that an element of the parameter collections conforms to another AbstractConstraint. + + The key of the element. + The constraint which should be applied to the element. + + + + Determines that all elements of the specified collection are in the the parameter collection + + The collection to compare against + The constraint which should be applied to the list parameter. + + + + Central location for constraints for object's properties + + + + + Constrains the parameter to have property with the specified value + + Name of the property. + Expected value. + + + + + Constrains the parameter to have property with the specified value. + + The type that declares the property, used to disambiguate between properties. + Name of the property. + Expected value. + + + + + Constrains the parameter to have a property satisfying a specified constraint. + + Name of the property. + Constraint for the property. + + + + Constrains the parameter to have a property satisfying a specified constraint. + + The type that declares the property, used to disambiguate between properties. + Name of the property. + Constraint for the property. + + + + Determines whether the parameter has the specified property and that it is null. + + Name of the property. + + + + + Determines whether the parameter has the specified property and that it is null. + + The type that declares the property, used to disambiguate between properties. + Name of the property. + + + + + Determines whether the parameter has the specified property and that it is not null. + + Name of the property. + + + + + Determines whether the parameter has the specified property and that it is not null. + + The type that declares the property, used to disambiguate between properties. + Name of the property. + + + + + constraints the parameter to have the exact same property values as the expected object. + + An object, of the same type as the parameter, whose properties are set with the expected values. + An instance of the constraint that will do the actual check. + + The parameter's public property values and public field values will be matched against the expected object's + public property values and public field values. The first mismatch will be reported and no further matching is done. + The matching is recursive for any property or field that has properties or fields of it's own. + Collections are supported through IEnumerable, which means the constraint will check if the actual and expected + collection contain the same values in the same order, where the values contained by the collection can have properties + and fields of their own that will be checked as well because of the recursive nature of this constraint. + + + + + Central location for all text related constraints + + + + + Constrain the argument to starts with the specified string + + + + + Constrain the argument to end with the specified string + + + + + Constrain the argument to contain the specified string + + + + + Constrain the argument to validate according to regex pattern + + + + + Provides access to the constraintes defined in the class to be used in context + with the syntax. + + + + + Constrain the argument to starts with the specified string + + + + + + Constrain the argument to end with the specified string + + + + + Constrain the argument to contain the specified string + + + + + Constrain the argument to validate according to regex pattern + + + + + Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. + + + + + + + Serves as a hash function for a particular type. + + + A hash code for the current . + + + + + This class defines a lot of method signatures, which we will use + to allow compatability on net-2.0 + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + dummy + + + + + Allows expectations to be set on methods that should never be called. + For methods with void return value, you need to use LastCall or + DoNotExpect.Call() with a delegate. + + + + + Sets LastCall.Repeat.Never() on /any/ proxy on /any/ repository on the current thread. + This method if not safe for multi threading scenarios. + + + + + Accepts a delegate that will execute inside the method which + LastCall.Repeat.Never() will be applied to. + It is expected to be used with anonymous delegates / lambda expressions and only one + method should be called. + + + IService mockSrv = mocks.CreateMock(typeof(IService)) as IService; + DoNotExpect.Call(delegate{ mockSrv.Stop(); }); + ... + + + + + An expectaton violation was detected. + + + + + Creates a new instance. + + Message. + + + + Serialization constructor + + + + + Signals that an object was call on a mock repository which doesn't + belong to this mock repository or not a mock + + + + + Creates a new instance. + + Message. + + + + Serialization constructor + + + + + Allows to set expectation on methods that has return values. + For methods with void return value, you need to use LastCall + + + + + The method options for the last call on /any/ proxy on /any/ repository on the current thread. + This method if not safe for multi threading scenarios, use . + + + + + Accepts a delegate that will execute inside the method, and then return the resulting + instance. + It is expected to be used with anonymous delegates / lambda expressions and only one + method should be called. + + + IService mockSrv = mocks.CreateMock(typeof(IService)) as IService; + Expect.Call(delegate{ mockSrv.Start(); }).Throw(new NetworkException()); + ... + + + + + Get the method options for the last method call on the mockInstance. + + + + + A delegate that can be used to get better syntax on Expect.Call(delegate { foo.DoSomething(); }); + + + + + Abstract class that holds common information for + expectations. + + + + + Interface to validate that a method call is correct. + + + + + Validate the arguments for the method. + This method can be called numerous times, so be careful about side effects + + The arguments with which the method was called + + + + Add an actual method call to this expectation + + + + + Returns the return value or throw the exception and setup any output / ref parameters + that has been set. + + + + + Builds the verification failure message. + + + + + + Gets the error message. + + + + + + Range of expected calls + + + + + Number of call actually made for this method + + + + + If this expectation is still waiting for calls. + + + + + The return value for a method matching this expectation + + + + + Gets or sets the exception to throw on a method matching this expectation. + + + + + Gets a value indicating whether this instance's action is staisfied. + A staisfied instance means that there are no more requirements from + this method. A method with non void return value must register either + a return value or an exception to throw. + + + + + Gets the method this expectation is for. + + + + + Gets or sets what special condtions there are for this method + repeating. + + + + + Gets a value indicating whether this expectation was satisfied + + + + + Specify whatever this expectation has a return value set + You can't check ReturnValue for this because a valid return value include null. + + + + + An action to execute when the method is matched. + + + + + Set the out / ref parameters for the method call. + The indexing is zero based and ignores any non out/ref parameter. + It is possible not to pass all the parameters. This method can be called only once. + + + + + Documentation Message + + + + + Gets the invocation for this expectation + + The invocation. + + + + Occurs when the exceptation is match on a method call + + + + + Allow to set the return value in the future, if it was already set. + + + + + Number of actuall calls made that passed this expectation + + + + + Range of expected calls that should pass this expectation. + + + + + The return value for a method matching this expectation + + + + + The exception to throw on a method matching this expectation. + + + + + The method this expectation is for. + + + + + The return value for this method was set + + + + + Whether this method will repeat + unlimited number of times. + + + + + A delegate that will be run when the + expectation is matched. + + + + + The arguments that matched this expectation. + + + + + Documentation message + + + + + The method originalInvocation + + + + + Get the hash code + + + + + Add an actual actualMethodCall call to this expectation + + + + + Builds the verification failure message. + + + + + + Returns the return value or throw the exception and setup output / ref parameters + + + + + Validate the arguments for the method on the child methods + + The arguments with which the method was called + + + + Creates a new instance. + + The originalInvocation for this method, required because it contains the generic type infromation + Number of method calls for this expectations + + + + Creates a new instance. + + Expectation. + + + + Validate the arguments for the method on the child methods + + The arguments with which the method was called + + + + Determines if this object equal to obj + + + + + The error message for these arguments + + + + + Asserts that the delegate has the same parameters as the expectation's method call + + + + + Setter for the outpur / ref parameters for this expecataion. + Can only be set once. + + + + + Specify whether this expectation has a return value set + You can't check ReturnValue for this because a valid return value include null. + + + + + Gets the method this expectation is for. + + + + + Gets the originalInvocation for this expectation + + The originalInvocation. + + + + Gets or sets what special condtions there are for this method + + + + + Range of expected calls + + + + + Number of call actually made for this method + + + + + If this expectation is still waiting for calls. + + + + + Gets a value indicating whether this expectation was satisfied + + + + + The return value for a method matching this expectation + + + + + An action to execute when the method is matched. + + + + + Gets or sets the exception to throw on a method matching this expectation. + + + + + Gets a value indicating whether this instance's action is staisfied. + A staisfied instance means that there are no more requirements from + this method. A method with non void return value must register either + a return value or an exception to throw or an action to execute. + + + + + Documentation message + + + + + Occurs when the exceptation is match on a method call + + + + + Allow to set the return value in the future, if it was already set. + + + + + Gets the error message. + + + + + + Expectation that matches any arguments for the method. + + + + + Creates a new instance. + + Invocation for this expectation + Number of method calls for this expectations + + + + Creates a new instance. + + Expectation. + + + + Validate the arguments for the method. + + The arguments with which the method was called + + + + Determines if the object equal to expectation + + + + + Get the hash code + + + + + Gets the error message. + + + + + + Summary description for ArgsEqualExpectation. + + + + + Creates a new instance. + + Expected args. + The invocation for this expectation + Number of method calls for this expectations + + + + Validate the arguments for the method. + + The arguments with which the method was called + + + + Determines if the object equal to expectation + + + + + Get the hash code + + + + + Gets the error message. + + + + + + Get the expected args. + + + + + Call a specified callback to verify the expectation + + + + + Creates a new instance. + + Expectation. + Callback. + + + + Creates a new instance. + + Invocation for this expectation + Callback. + Number of method calls for this expectations + + + + Validate the arguments for the method on the child methods + + The arguments with which the method was called + + + + Determines if the object equal to expectation + + + + + Get the hash code + + + + + Gets the error message. + + + + + + Expect the method's arguments to match the contraints + + + + + Creates a new instance. + + Invocation for this expectation + Constraints. + Number of method calls for this expectations + + + + Creates a new instance. + + Expectation. + Constraints. + + + + Validate the arguments for the method. + + The arguments with which the method was called + + + + Determines if the object equal to expectation + + + + + Get the hash code + + + + + Gets the error message. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Summary for AndSpecification + + + + + + + + + + + + + + + + + + + + + + Summary description for FollowsEventNamingStandard + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Summary descritpion for NamedEventExistsOnDeclaringType + + + + + + + + + Doesn't log anything, just makes happy noises + + + + + Log expectations - allows to see what is going on inside Rhino Mocks + + + + + Logs the expectation as is was recorded + + The invocation. + The expectation. + + + + Logs the expectation as it was recorded + + The invocation. + The expectation. + + + + Logs the unexpected method call. + + The invocation. + The message. + + + + Logs the expectation as is was recorded + + The invocation. + The expectation. + + + + Logs the expectation as it was recorded + + The invocation. + The expectation. + + + + Logs the unexpected method call. + + The invocation. + The message. + + + + Operation on a remoting proxy + + + It is not possible to directly communicate to a real proxy via transparent proxy. + Transparent proxy impersonates a user type and only methods of that user type are callable. + The only methods that are guaranteed to exist on any transparent proxy are methods defined + in Object: namely ToString(), GetHashCode(), and Equals()). + + These three methods are the only way to tell the real proxy to do something. + Equals() is the most suitable of all, since it accepts an arbitrary object parameter. + The RemotingProxy code is built so that if it is compared to an IRemotingProxyOperation, + transparentProxy.Equals(operation) will call operation.Process(realProxy). + This way we can retrieve a real proxy from transparent proxy and perform + arbitrary operation on it. + + + + + Generates remoting proxies and provides utility functions + + + + + Create the proxy using remoting + + + + + Check whether an object is a transparent proxy with a RemotingProxy behind it + + Object to check + true if the object is a transparent proxy with a RemotingProxy instance behind it, false otherwise + We use Equals() method to communicate with the real proxy behind the object. + See IRemotingProxyOperation for more details + + + + Retrieve a mocked object from a transparent proxy + + Transparent proxy with a RemotingProxy instance behind it + Mocked object associated with the proxy + We use Equals() method to communicate with the real proxy behind the object. + See IRemotingProxyOperation for more details + + + + Implementation of IInvocation based on remoting proxy + + Some methods are marked NotSupported since they either don't make sense + for remoting proxies, or they are never called by Rhino Mocks + + + + Rudimetry implementation that simply logs methods calls as text. + + + + + Initializes a new instance of the class. + + The writer. + + + + Logs the expectation as it was recorded + + The invocation. + The expectation. + + + + Logs the expectation as it was recorded + + The invocation. + The expectation. + + + + Logs the unexpected method call. + + The invocation. + The message. + + + + Behave like a stub, all properties and events acts normally, methods calls + return default values by default (but can use expectations to set them up), etc. + + + + + Records all the expectations for a mock + + + + + Different actions on this mock + + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Verify that this mock expectations have passed. + + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Gets a mock state that match the original mock state of the object. + + + + + Get the options for the last method call + + + + + Set the exception to throw when Verify is called. + This is used to report exception that may have happened but where caught in the code. + This way, they are reported anyway when Verify() is called. + + + + + This method is called to indicate that a property behavior call. + This is done so we generate good error message in the common case of people using + Stubbed properties with Return(). + + + + + Gets the matching verify state for this state + + + + + Get the options for the last method call + + + + + Get the options for the last method call + + + + + Set the exception to throw when Verify is called. + This is used to report exception that may have happened but where caught in the code. + This way, they are reported anyway when Verify() is called. + + + + + This method is called to indicate that a property behavior call. + This is done so we generate good error message in the common case of people using + Stubbed properties with Return(). + + + + + Creates a new instance. + + Repository. + The proxy that generates the method calls + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Verify that this mock expectations have passed. + + + + + Gets a mock state that match the original mock state of the object. + + + + + Asserts the previous method is closed (had an expectation set on it so we can replay it correctly) + + + + + Get the default call count range expectation + + + + + + Gets the last expectation. + + + + + Gets the total method calls count. + + + + + Get the options for the last method call + + + + + Gets the matching verify state for this state + + + + + Initializes a new instance of the class. + + The proxy that generates the method calls + Repository. + + + + We don't care much about expectations here, so we will remove the expectation if + it is not closed. + + + + + Verify that we can move to replay state and move + to the reply state. + + + + + + Get the default call count range expectation + + + + + + Validate expectations on recorded methods, but in general completely ignoring them. + Similar to except that it would return a + when BackToRecord is called. + + + + + Validate all expectations on a mock + + + + + The repository for this state + + + + + The proxy object for this state + + + + + Get the options for the last method call + + + + + Creates a new instance. + + The previous state for this method + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Add a method call for this state' mock. + This allows derived method to cleanly get a the setupresult behavior while adding + their own. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Set the exception to throw when Verify is called. + This is used to report exception that may have happened but where caught in the code. + This way, they are reported anyway when Verify() is called. + + + + + not relevant + + + + + Verify that this mock expectations have passed. + + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Gets a mock state that match the original mock state of the object. + + + + + Get the options for the last method call + + + + + Gets the matching verify state for this state + + + + + Initializes a new instance of the class. + + The previous state for this method + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Gets a mock state that matches the original mock state of the object. + + + + + Write rhino mocks log info to the trace + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + if set to true [log recorded]. + if set to true [log replayed]. + if set to true [log unexpected]. + + + + Logs the expectation as is was recorded + + The invocation. + The expectation. + + + + Logs the expectation as it was recorded + + The invocation. + The expectation. + + + + Logs the unexpected method call. + + The invocation. + The message. + + + + Writes log information as stack traces about rhino mocks activity + + + + + Allows to redirect output to a different location. + + + + + Logs the expectation as is was recorded + + The invocation. + The expectation. + + + + Logs the expectation as it was recorded + + The invocation. + The expectation. + + + + Logs the unexpected method call. + + The invocation. + The message. + + + + Marker interface used to indicate that this is a partial mock. + + + + + Options for CallOriginalMethod + + + + + No expectation is created, the method will be called directly + + + + + Normal expectation is created, but when the method is later called, it will also call the original method + + + + + This is a data structure that is used by + to pass + the current method to the relevant delegate + + + + + Initializes a new instance of the class. + + The invocation. + + + + Gets the args for this method invocation + + + + + Get the method that was caused this invocation + + + + + Gets or sets the return value for this method invocation + + The return value. + + + + Adds optional new usage: + using(mockRepository.Record()) { + Expect.Call(mock.Method()).Return(retVal); + } + using(mockRepository.Playback()) { + // Execute code + } + N.B. mockRepository.ReplayAll() and mockRepository.VerifyAll() + calls are taken care of by Record/Playback + + + Creates proxied instances of types. + + + + Generates a stub without needing a + Arguments for 's constructor + The of stub to create. + The stub + + + + Generates a stub without needing a + The of stub. + Arguments for the 's constructor. + The stub + + + + Generate a mock object without needing a + type of mock object to create. + Arguments for 's constructor + the mock object + + + + Generate a multi-mock object without needing a + The typeof object to generate a mock for. + A second interface to generate a multi-mock for. + Arguments for 's constructor + the multi-mock object + + + + Generate a multi-mock object without without needing a + The typeof object to generate a mock for. + An interface to generate a multi-mock for. + A second interface to generate a multi-mock for. + Arguments for 's constructor + the multi-mock object + + + + Creates a multi-mock without without needing a + The type of mock to create, this can be a class + Any extra interfaces to add to the multi-mock, these can only be interfaces. + Arguments for 's constructor + the multi-mock object + + + + Creates a strict mock without without needing a + Any arguments required for the 's constructor + The type of mock object to create. + The mock object with strict replay semantics + + + + Creates a strict multi-mock without needing a + Any arguments required for the 's constructor + The type of mock object to create, this can be a class. + An interface to generate a multi-mock for, this must be an interface! + The multi-mock object with strict replay semantics + + + + Creates a strict multi-mock without needing a + Any arguments required for the 's constructor + The type of mock object to create, this can be a class. + An interface to generate a multi-mock for, this must be an interface! + A second interface to generate a multi-mock for, this must be an interface! + The multi-mock object with strict replay semantics + + + + Creates a strict multi-mock without needing a + The type of mock object to create, this can be a class + Any extra interfaces to generate a multi-mock for, these must be interaces! + Any arguments for the 's constructor + The strict multi-mock object + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Generate a mock object with dynamic replay semantics and remoting without needing the mock repository + + + + + Generate a mock object with strict replay semantics and remoting without needing the mock repository + + + + Helper method to create a mock object without a repository instance and put the object back into replay mode. + The type of mock object to create + A delegate that uses a mock repository instance to create the underlying mock + The mock object in the replay mode. + + + + + + + + + + + + + + This is a map of types to ProxyGenerators. + + + + + This is used to record the last repository that has a method called on it. + + + + + this is used to get to the last proxy on this repository. + + + + + For mock delegates, maps the proxy instance from intercepted invocations + back to the delegate that was originally returned to client code, if any. + + + + + All the proxies in the mock repositories + + + + + This is here because we can't put it in any of the recorders, since repeatable methods + have no orderring, and if we try to handle them using the usual manner, we would get into + wierd situations where repeatable method that was defined in an orderring block doesn't + exists until we enter this block. + + + + + Creates a new instance. + + + + + Move the repository to ordered mode + + + + + Move the repository to un-ordered mode + + + + + Creates a mock for the specified type. + + Type. + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a strict mock for the specified type. + + Type. + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a remoting mock for the specified type. + + Type. + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a strict remoting mock for the specified type. + + Type. + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a remoting mock for the specified type. + + + Arguments for the class' constructor, if mocking a concrete class + + + + + Creates a strict remoting mock for the specified type. + + + Arguments for the class' constructor, if mocking a concrete class + + + + + Creates a mock from several types, with strict semantics. + Only may be a class. + + + + + Creates a strict mock from several types, with strict semantics. + Only may be a class. + + + + + Creates a mock from several types, with strict semantics. + Only may be a class. + + The main type to mock. + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class. + + + + Creates a strict mock from several types, with strict semantics. + Only may be a class. + + The main type to mock. + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class. + + + + Creates a mock from several types, with dynamic semantics. + Only may be a class. + + The main type to mock. + Extra interface types to mock. + + + + Creates a mock from several types, with dynamic semantics. + Only may be a class. + + The main type to mock. + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class. + + + Creates a dynamic mock for the specified type. + Type. + Arguments for the class' constructor, if mocking a concrete class + + + Creates a dynamic mock for the specified type. + Type. + Arguments for the class' constructor, if mocking a concrete class + + + Creates a dynamic mock for the specified type. + + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a mock object that defaults to calling the class methods if no expectation is set on the method. + Type. + Arguments for the class' constructor. + + + Creates a mock object that defaults to calling the class methods. + Type. + Extra interface types to mock. + + + Creates a mock object that defaults to calling the class methods. + Type. + Extra interface types to mock. + Arguments for the class' constructor. + + + Creates a mock object using remoting proxies + Type to mock - must be MarshalByRefObject + Mock object + Proxy mock can mock non-virtual methods, but not static methods + Creates the mock state for this proxy + + + + Cause the mock state to change to replay, any further call is compared to the + ones that were called in the record state. + + This method *cannot* be called from inside an ordering. + the object to move to replay state + + + + Cause the mock state to change to replay, any further call is compared to the + ones that were called in the record state. + + the object to move to replay state + + + + Move the mocked object back to record state.You can (and it's recommended) to run {Verify()} before you use this method. + Will delete all current expectations! + + + + Move the mocked object back to record state. + Optionally, can delete all current expectations, but allows more granularity about how + it would behave with regard to the object state. + + + + + Verify that all the expectations for this object were fulfilled. + + the object to verify the expectations for + + + + Get the method options for the last call on + mockedInstance. + + The mock object + Method options for the last call + + + + Maps an invocation proxy back to the mock object instance that was originally + returned to client code which might have been a delegate to this proxy. + + The mock object proxy from the intercepted invocation + The mock object + + + This is provided to allow advance extention functionality, where Rhino Mocks standard functionality is not enough. + The type to mock + Delegate that create the first state of the mocked object (usualy the record state). + Additional types to be implemented, this can be only interfaces + optional arguments for the constructor + + + + + Method: GetMockedObject + Get an IProxy from a mocked object instance, or throws if the + object is not a mock object. + + + + + Method: GetMockedObjectOrNull + Get an IProxy from a mocked object instance, or null if the + object is not a mock object. + + + + Pops the recorder. + + + Pushes the recorder. + New recorder. + + + + All the mock objects in this repository will be moved + to record state. + + + + + All the mock objects in this repository will be moved + to record state. + + + + + Replay all the mocks from this repository + + + + + Verify all the mocks from this repository + + + + + Gets the proxy generator for a specific type. Having a single ProxyGenerator + with multiple types linearly degrades the performance so this implementation + keeps one ProxyGenerator per type. + + + + Set the exception to be thrown when verified is called. + + + + Creates a mock for the spesified type with strict mocking semantics. + Strict semantics means that any call that wasn't explicitly recorded is considered an error and would cause an exception to be thrown. + + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a mock for the spesified type with strict mocking semantics. + Strict semantics means that any call that wasn't explicitly recorded is considered an error and would cause an exception to be thrown. + + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a dynamic mock for the specified type. + + Arguments for the class' constructor, if mocking a concrete class + + + + Creates a mock object from several types. + + + + + Creates a strict mock object from several types. + + + + + Create a mock object from several types with dynamic semantics. + + + + + Create a mock object from several types with partial semantics. + + + + + Create a mock object from several types with strict semantics. + + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class + + + + Create a strict mock object from several types with strict semantics. + + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class + + + + Create a mock object from several types with dynamic semantics. + + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class + + + + Create a mock object from several types with partial semantics. + + Extra interface types to mock. + Arguments for the class' constructor, if mocking a concrete class + + + + Create a mock object with from a class that defaults to calling the class methods + + Arguments for the class' constructor, if mocking a concrete class + + + + Create a stub object, one that has properties and events ready for use, and + can have methods called on it. It requires an explicit step in order to create + an expectation for a stub. + + The arguments for constructor. + + + + Create a stub object, one that has properties and events ready for use, and + can have methods called on it. It requires an explicit step in order to create + an expectation for a stub. + + The type. + The arguments for constructor. + The stub + + + + Returns true if the passed mock is currently in replay mode. + + The mock to test. + True if the mock is in replay mode, false otherwise. + + + + Determines whether the specified proxy is a stub. + + The proxy. + + + + Register a call on a prperty behavior + + + + + + Gets the recorder. + + + + + + Gets the replayer for this repository. + + + + + + Gets the last proxy which had a method call. + + + + + Delegate: CreateMockState + This is used internally to cleanly handle the creation of different + RecordMockStates. + + + + + A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks + + + + + Create an expectation on this mock for this action to occur + + + The mock. + The action. + + + + + Reset all expectations on this mock object + + + The mock. + + + + Reset the selected expectation on this mock object + + + The mock. + The options to reset the expectations on this mock. + + + + Cause the mock state to change to replay, any further call is compared to the + ones that were called in the record state. + + the mocked object to move to replay state + + + + Gets the mock repository for this specificied mock object + + + The mock. + + + + + Create an expectation on this mock for this action to occur + + + + The mock. + The action. + + + + + Tell the mock object to perform a certain action when a matching + method is called. + Does not create an expectation for this method. + + + The mock. + The action. + + + + + Tell the mock object to perform a certain action when a matching + method is called. + Does not create an expectation for this method. + + + + The mock. + The action. + + + + + Gets the arguments for calls made on this mock object and the method that was called + in the action. + + + The mock. + The action. + + + Here we will get all the arguments for all the calls made to DoSomething(int) + + var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0)) + + + + + + Gets the arguments for calls made on this mock object and the method that was called + in the action and matches the given constraints + + + The mock. + The action. + The setup constraints. + + + Here we will get all the arguments for all the calls made to DoSomething(int) + + var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0)) + + + + + + Asserts that a particular method was called on this mock object + + + The mock. + The action. + + + + Asserts that a particular method was called on this mock object that match + a particular constraint set. + + + The mock. + The action. + The setup constraints. + + + + Asserts that a particular method was called on this mock object that match + a particular constraint set. + + + The mock. + The action. + + + + Asserts that a particular method was called on this mock object that match + a particular constraint set. + + + The mock. + The action. + The setup constraints. + + + + Asserts that a particular method was NOT called on this mock object + + + The mock. + The action. + + + + Asserts that a particular method was NOT called on this mock object that match + a particular constraint set. + + + The mock. + The action. + The setup constraints. + + + + Asserts that a particular method was NOT called on this mock object + + + The mock. + The action. + + + + Asserts that a particular method was NOT called on this mock object + + + The mock. + The action. + The setup constraints. + + + + Finds the approprite implementation type of this item. + This is the class or an interface outside of the rhino mocks. + + The mocked obj. + + + + + Verifies all expectations on this mock object + + The mock object. + + + + Gets the event raiser for the event that was called in the action passed + + The type of the event source. + The mock object. + The event subscription. + + + + + Raise the specified event using the passed arguments. + The even is extracted from the passed labmda + + The type of the event source. + The mock object. + The event subscription. + The sender. + The instance containing the event data. + + + + Raise the specified event using the passed arguments. + The even is extracted from the passed labmda + + The type of the event source. + The mock object. + The event subscription. + The args. + + + TODO: Make this better! It currently breaks down when mocking classes or + ABC's that call other virtual methods which are getting intercepted too. I wish + we could just walk Expression{Action{Action{T}} to assert only a single + method is being made. + + The workaround is to not call foo.AssertWasCalled .. rather foo.VerifyAllExpectations() + The type of mock object + The mock repository + The actual mock object to assert expectations on. + + + + Fake type that disallow creating it. + Should have been System.Type, but we can't use it. + + + + + Utility class for dealing with messing generics scenarios. + + + + + There are issues with trying to get this to work correctly with open generic types, since this is an edge case, + I am letting the runtime handle it. + + + + + Gets the real type, including de-constructing and constructing the type of generic + methods parameters. + + The type. + The invocation. + + + + + Because we need to support complex types here (simple generics were handled above) we + need to be aware of the following scenarios: + List[T] and List[Foo[T]] + + + + + ExpectationsList + + + + + Dictionary + + + + + Dictionary class + + + + + Create a new instance of ProxyStateDictionary + + + + + Allows to call a method and immediately get it's options. + + + + + Interface to allow calling a method and immediately get it's options. + + + + + Get the method options for the call + + The method call should go here, the return value is ignored + + + + Creates a new instance. + + + + + Get the method options for the call + + The method call should go here, the return value is ignored + + + + Allows to call a method and immediately get it's options. + Set the expected number for the call to Any() + + + + + Creates a new instance. + + Proxy. + Mocked instance. + + + + Get the method options for the call + + The method call should go here, the return value is ignored + + + + This class is reponsible for taking a delegate and creating a wrapper + interface around it, so it can be mocked. + + + + + The scope for all the delegate interfaces create by this mock repository. + + + + + Gets a type with an "Invoke" method suitable for use as a target of the + specified delegate type. + + + + + + + Raise events for all subscribers for an event + + + + + Raise events for all subscribers for an event + + + + + Raise the event + + + + + The most common form for the event handler signature + + + + + Create an event raiser for the specified event on this instance. + + + + + Creates a new instance of EventRaiser + + + + + Raise the event + + + + + The most common signature for events + Here to allow intellisense to make better guesses about how + it should suggest parameters. + + + + + Allows to define what would happen when a method + is called. + + + + + Allows to define what would happen when a method + is called. + + + + + Set the return value for the method. + + The object the method will return + IRepeat that defines how many times the method will return this value + + + + Allow to override this return value in the future + + IRepeat that defines how many times the method will return this value + + + + Throws the specified exception when the method is called. + + Exception to throw + + + + Ignores the arguments for this method. Any argument will be matched + againt this method. + + + + + Add constraints for the method's arguments. + + + + + Set a callback method for the last call + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched + and allow to optionally modify the invocation as needed + + + + + Call the original method on the class, bypassing the mocking layers. + + + + + + Call the original method on the class, optionally bypassing the mocking layers. + + + + + + Use the property as a simple property, getting/setting the values without + causing mock expectations. + + + + + Expect last (property) call as property setting, ignore the argument given + + + + + + Expect last (property) call as property setting with a given argument. + + + + + + + Get an event raiser for the last subscribed event. + + + + + Set the parameter values for out and ref parameters. + This is done using zero based indexing, and _ignoring_ any non out/ref parameter. + + + + + Documentation message for the expectation + + Message + + + + Better syntax to define repeats. + + + + + Allows to specify the number of time for method calls + + + + + Repeat the method twice. + + + + + Repeat the method once. + + + + + Repeat the method at least once, then repeat as many time as it would like. + + + + + Repeat the method any number of times. + This has special affects in that this method would now ignore orderring. + + + + + Set the range to repeat an action. + + Min. + Max. + + + + Set the amount of times to repeat an action. + + + + + This method must not appear in the replay state. + This has special affects in that this method would now ignore orderring. + + + + + Creates a new instance. + + the repository for this expectation + the recorder for this proxy + the proxy for this expectation + Expectation. + + + + Add constraints for the method's arguments. + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Set the return value for the method. + + The object the method will return + IRepeat that defines how many times the method will return this value + + + + Set the return value for the method, but allow to override this return value in the future + + IRepeat that defines how many times the method will return this value + + + + Throws the specified exception when the method is called. + + Exception to throw + + + + Ignores the arguments for this method. Any argument will be matched + againt this method. + + + + + Call the original method on the class, bypassing the mocking layers. + + + + + + Call the original method on the class, optionally bypassing the mocking layers + + + + + + Use the property as a simple property, getting/setting the values without + causing mock expectations. + + + + + Expect last (property) call as property setting, ignore the argument given + + + + + + Expect last (property) call as property setting with a given argument. + + + + + + + Gets the event raiser for the last event + + + + + Set the parameter values for out and ref parameters. + This is done using zero based indexing, and _ignoring_ any non out/ref parameter. + + + + + Repeat the method twice. + + + + + Repeat the method once. + + + + + Repeat the method at least once, then repeat as many time as it would like. + + + + + This method must not appear in the replay state. + + + + + Documentation message for the expectation + + Message + + + + Repeat the method any number of times. + + + + + Set the range to repeat an action. + + Min. + Max. + + + + Set the amount of times to repeat an action. + + + + + Better syntax to define repeats. + + + + + This class will provide hash code for hashtables without needing + to call the GetHashCode() on the object, which may very well be mocked. + This class has no state so it is a singelton to avoid creating a lot of objects + that does the exact same thing. See flyweight patterns. + + + + + Get the hash code for a proxy object without calling GetHashCode() + on the object. + + + + + Compares two instances of mocked objects + + + + + Compare two mocked objects + + + + + The next hash code value for a mock object. + This is safe for multi threading. + + + + + The sole instance of + + + + + This is a dummy type that is used merely to give DynamicProxy the proxy instance that + it needs to create IProxy's types. + + + + + Interface to find the repository of a mocked object + + + + + Return true if it should call the original method on the object + instead of pass it to the message chain. + + The method to call + + + + Register a method to be called on the object directly + + + + + Register a property on the object that will behave as a simple property + + + + + Check if the method was registered as a property method. + + + + + Do get/set on the property, according to need. + + + + + Do add/remove on the event + + + + + Get the subscribers of a spesific event + + + + + Gets the declaring type of the method, taking into acccount the possible generic + parameters that it was created with. + + + + + Clears the state of the object, remove original calls, property behavior, subscribed events, etc. + + + + + Get all the method calls arguments that were made against this object with the specificed + method. + + + Only method calls in replay mode are counted + + + + + Records the method call + + + + + Mocks that are tied to this mock lifestyle + + + + + The unique hash code of this mock, which is not related + to the value of the GetHashCode() call on the object. + + + + + Gets the repository. + + + + + Gets the implemented types by this mocked object + + The implemented. + + + + Gets or sets the constructor arguments. + + The constructor arguments. + + + + The mocked instance that this is representing + + + + + Create a new instance of + + + + + Return true if it should call the original method on the object + instead of pass it to the message chain. + + The method to call + + + + Register a method to be called on the object directly + + + + + Register a property on the object that will behave as a simple property + Return true if there is already a value for the property + + + + + Check if the method was registered as a property method. + + + + + Do get/set on the property, according to need. + + + + + Do add/remove on the event + + + + + Get the subscribers of a spesific event + + + + + Gets the declaring type of the method, taking into acccount the possible generic + parameters that it was created with. + + + + + Get all the method calls arguments that were made against this object with the specificed + method. + + + + + Only method calls in replay mode are counted + + + + + Records the method call + + + + + + + Clears the state of the object, remove original calls, property behavior, subscribed events, etc. + + + + + Mocks that are tied to this mock lifestyle + + + + + The unique hash code of this proxy, which is not related + to the value of the GetHashCode() call on the object. + + + + + Gets the repository. + + + + + Gets or sets the constructor arguments. + + The constructor arguments. + + + + The mocked instance that this is representing + + + + + Gets the implemented types by this mocked object + + The implemented. + + + + Range for expected method calls + + + + + Creates a new instance. + + Min. + Max. + + + + Return the string representation of this range. + + + + + Gets or sets the min. + + + + + + Gets or sets the max. + + + + + + Records all the expectations for a mock and + return a ReplayDynamicMockState when Replay() + is called. + + + + + Creates a new instance. + + Repository. + The proxy that generates the method calls + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Get the default call count range expectation + + + + + + Gets a mock state that match the original mock state of the object. + + + + + Records all the expectations for a mock and + return a ReplayPartialMockState when Replay() + is called. + + + + + Creates a new instance. + + Repository. + The proxy that generates the method calls + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Gets a mock state that matches the original mock state of the object. + + + + + Options for special repeat option + + + + + This method can be called only as many times as the IMethodOptions.Expect allows. + + + + + This method should never be called + + + + + This method can be call any number of times + + + + + This method will call the original method + + + + + This method will call the original method, bypassing the mocking layer + + + + + This method will simulate simple property behavior + + + + + Validate all expectations on a mock and ignores calls to + any method that was not setup properly. + + + + + Creates a new instance. + + The previous state for this method + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Gets a mock state that match the original mock state of the object. + + + + + Validate all expectations on a mock and ignores calls to + any method that was not setup properly. + + + + + Creates a new instance. + + The previous state for this method + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Gets a mock state that match the original mock state of the object. + + + + + Summary description for RhinoInterceptor. + + + + + Creates a new instance. + + + + + Intercept a method call and direct it to the repository. + + + + + Validate arguments for methods + + + + + Validate that the passed argument is not null. + + The object to validate + The name of the argument + + If the obj is null, an ArgumentNullException with the passed name + is thrown. + + + + + Validate that the arguments are equal. + + Expected args. + Actual Args. + + + + Validate that the two arguments are equals, including validation for + when the arguments are collections, in which case it will validate their values. + + + + + This method is safe for use even if any of the objects is a mocked object + that override equals. + + + + + Throw an object already verified when accessed + + + + + Create a new instance of VerifiedMockState + + The previous mock state, used to get the initial record state + + + + Add a method call for this state' mock. + + The invocation for this method + The method that was called + The arguments this method was called with + + + + Verify that this mock expectations have passed. + + + + + Verify that we can move to replay state and move + to the reply state. + + + + + Gets a mock state that match the original mock state of the object. + + + + + Get the options for the last method call + + + + + Set the exception to throw when Verify is called. + This is used to report exception that may have happened but where caught in the code. + This way, they are reported anyway when Verify() is called. + + + + + not relevant + + + + + Gets the matching verify state for this state + + + + + Get the options for the last method call + + + + + Records the actions on all the mocks created by a repository. + + + + + Records the specified call with the specified args on the mocked object. + + + + + Get the expectation for this method on this object with this arguments + + + + + This check the methods that were setup using the SetupResult.For() + or LastCall.Repeat.Any() and that bypass the whole expectation model. + + + + + Gets the all expectations for a mocked object and method combination, + regardless of the expected arguments / callbacks / contraints. + + Mocked object. + Method. + List of all relevant expectation + + + + Gets the all expectations for proxy. + + Mocked object. + List of all relevant expectation + + + + Removes all the repeatable expectations for proxy. + + Mocked object. + + + + Replaces the old expectation with the new expectation for the specified proxy/method pair. + This replace ALL expectations that equal to old expectations. + + Proxy. + Method. + Old expectation. + New expectation. + + + + Adds the recorder and turn it into the active recorder. + + Recorder. + + + + Moves to previous recorder. + + + + + Gets the recorded expectation or null. + + + + + Gets the next expected calls string. + + + + + Moves to parent recorder. + + + + + Set the expectation so it can repeat any number of times. + + + + + Removes the expectation from the recorder + + + + + Clear the replayer to call (and all its chain of replayers) + This also removes it from the list of expectations, so it will never be considered again + + + + + Get the expectation for this method on this object with this arguments + + + + + Gets a value indicating whether this instance has expectations that weren't satisfied yet. + + + true if this instance has expectations; otherwise, false. + + + + + Allows to set various options for the last method call on + a specified object. + If the method has a return value, it's recommended to use Expect + + + + + Allows to get an interface to work on the last call. + + The mocked object + Interface that allows to set options for the last method call on this object + + + + Set the return value for the method. + + The object the method will return + IRepeat that defines how many times the method will return this value + + + + Set the return value for the method. This overload is needed for LastCall.Return(null) + + The object the method will return + IRepeat that defines how many times the method will return this value + + + + Throws the specified exception when the method is called. + + Exception to throw + + + + Ignores the arguments for this method. Any argument will be matched + againt this method. + + + + + Add constraints for the method's arguments. + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Set a callback method for the last call + + + + + Call the original method on the class, bypassing the mocking layers, for the last call. + + + + + Call the original method on the class, optionally bypassing the mocking layers, for the last call. + + + + + Set a delegate to be called when the expectation is matched. + The delegate return value will be returned from the expectation. + + + + + Gets an interface that will raise the last event when called. + + + + + Set the parameter values for out and ref parameters. + This is done using zero based indexing, and _ignoring_ any non out/ref parameter. + + + + + Documentation message for the expectation + + Message + + + + Use the property as a simple property, getting/setting the values without + causing mock expectations. + + + + + Better syntax to define repeats. + + + + + Base class for method recorders, handle delegating to inner recorder if needed. + + + + + List of the expected actions on for this recorder + The legal values are: + * Expectations + * Method Recorders + + + + + The current recorder. + + + + + The current replayer; + + + + + The parent recorder of this one, may be null. + + + + + This contains a list of all the replayers that should be ignored + for a spesific method call. A replayer gets into this list by calling + ClearReplayerToCall() on its parent. This list is Clear()ed on each new invocation. + + + + + All the repeatable methods calls. + + + + + Counts the recursion depth of the current expectation search stack + + + + + Creates a new instance. + + + + + Creates a new instance. + + Parent recorder. + Repeatable methods + + + + Records the specified call with the specified args on the mocked object. + + + + + Get the expectation for this method on this object with this arguments + + + + + Gets the all expectations for a mocked object and method combination, + regardless of the expected arguments / callbacks / contraints. + + Mocked object. + Method. + List of all relevant expectation + + + + Gets the all expectations for proxy. + + Mocked object. + List of all relevant expectation + + + + Replaces the old expectation with the new expectation for the specified proxy/method pair. + This replace ALL expectations that equal to old expectations. + + Proxy. + Method. + Old expectation. + New expectation. + + + + Remove the all repeatable expectations for proxy. + + Mocked object. + + + + Set the expectation so it can repeat any number of times. + + + + + Removes the expectation from the recorder + + + + + Adds the recorder and turn it into the active recorder. + + Recorder. + + + + Moves to previous recorder. + + + + + Moves to parent recorder. + + + + + Gets the recorded expectation or null. + + + + + Clear the replayer to call (and all its chain of replayers). + This also removes it from the list of expectations, so it will never be considered again + + + + + Get the expectation for this method on this object with this arguments + + + + + Gets the next expected calls string. + + + + + Handles the real getting of the recorded expectation or null. + + + + + Handle the real execution of this method for the derived class + + + + + Handle the real execution of this method for the derived class + + + + + Handle the real execution of this method for the derived class + + + + + Handle the real execution of this method for the derived class + + + + + Handle the real execution of this method for the derived class + + + + + Handle the real execution of this method for the derived class + + + + + Should this replayer be considered valid for this call? + + + + + This check the methods that were setup using the SetupResult.For() + or LastCall.Repeat.Any() and that bypass the whole expectation model. + + + + + Gets a value indicating whether this instance has expectations that weren't satisfied yet. + + + true if this instance has expectations; otherwise, false. + + + + + Handle the real execution of this method for the derived class + + + + + Ordered collection of methods, methods must arrive in specified order + in order to pass. + + + + + Unordered collection of method records, any expectation that exist + will be matched. + + + + + The parent recorder we have redirected to. + Useful for certain edge cases in orderring. + See: FieldProblem_Entropy for the details. + + + + + Creates a new instance. + + Parent recorder. + Repeatable methods + + + + Creates a new instance. + + + + + Records the specified call with the specified args on the mocked object. + + Mocked object. + Method. + Expectation. + + + + Get the expectation for this method on this object with this arguments + + Invocation for this method + Mocked object. + Method. + Args. + True is the call was recorded, false otherwise + + + + Gets the all expectations for a mocked object and method combination, + regardless of the expected arguments / callbacks / contraints. + + Mocked object. + Method. + List of all relevant expectation + + + + Gets the all expectations for proxy. + + Mocked object. + List of all relevant expectation + + + + Replaces the old expectation with the new expectation for the specified proxy/method pair. + This replace ALL expectations that equal to old expectations. + + Proxy. + Method. + Old expectation. + New expectation. + + + + Handle the real execution of this method for the derived class + + + + + Handles the real getting of the recorded expectation or null. + + + + + Handle the real execution of this method for the derived class + + + + + Gets the next expected calls string. + + + + + Create an exception for an unexpected method call. + + + + + Gets a value indicating whether this instance has expectations that weren't satisfied yet. + + + true if this instance has expectations; otherwise, false. + + + + + Creates a new instance. + + Parent recorder. + Repetable methods + + + + Creates a new instance. + + + + + Handles the real getting of the recorded expectation or null. + + + + + Get the expectation for this method on this object with this arguments + + + + + Gets the next expected calls string. + + + + + Hold an expectation for a method call on an object + + + + + Creates a new instance. + + Proxy. + Method. + Expectation. + + + + Determines if the object equal to this instance + + Obj. + + + + + Gets the hash code. + + + + + + Gets the proxy. + + + + + + Gets the method. + + + + + + Gets the expectation. + + + + + + Holds a pair of mocked object and a method + and allows to compare them against each other. + This allows us to have a distinction between mockOne.MyMethod() and + mockTwo.MyMethod()... + + + + + Creates a new instance. + + Proxy. + Method. + + + + Determines whatever obj equals to this instance. + ProxyMethodPairs are equal when they point to the same /instance/ of + an object, and to the same method. + + Obj. + + + + + Gets the hash code. + + + + + + Gets the proxy. + + + + + + Gets the method. + + + + + + Change the recorder from ordered to unordered and vice versa + + + + + Creates a new instance. + + + + + Disposes this instance. + + + + + Accessor for the current mocker + + + + + The current mocker + + + + + Used for [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] + Used for [assembly: InternalsVisibleTo(RhinoMocks.NormalName)] + + + + + Strong name for the Dynamic Proxy assemblies. Used for InternalsVisibleTo specification. + + + + + Normal name for dynamic proxy assemblies. Used for InternalsVisibleTo specification. + + + + + Logs all method calls for methods + + + + + Setup method calls to repeat any number of times. + + + + + Get the method options and set the last method call to repeat + any number of times. + This also means that the method would transcend ordering + + + + + Get the method options for the last method call on the mockInstance and set it + to repeat any number of times. + This also means that the method would transcend ordering + + + + + Utility class for working with method calls. + + + + + Return the string representation of a method call and its arguments. + + The method + The method arguments + Invocation of the method, used to get the generics arguments + Delegate to format the parameter + The string representation of this method call + + + + Return the string representation of a method call and its arguments. + + The invocation of the method, used to get the generic parameters + The method + The method arguments + The string representation of this method call + + + + Delegate to format the argument for the string representation of + the method call. + + + + + Utility to get the default value for a type + + + + + The default value for a type. + Null for reference types and void + 0 for value types. + First element for enums + Note that we need to get the value even for opened generic types, such as those from + generic methods. + + Type. + The invocation. + the default value + + + + Allows easier access to MockRepository, works closely with Mocker.Current to + allow access to a context where the mock repository is automatially verified at + the end of the code block. + + + + + Initialize a code block where Mocker.Current is initialized. + At the end of the code block, all the expectation will be verified. + This overload will create a new MockRepository. + + The code that will be executed under the mock context + + + + Initialize a code block where Mocker.Current is initialized. + At the end of the code block, all the expectation will be verified. + This overload will create a new MockRepository. + + The mock repository to use, at the end of the code block, VerifyAll() will be called on the repository. + The code that will be executed under the mock context + + + + Create a FluentMocker + + The mock repository to use. + + + + A method with no arguments and no return value that will be called under the mock context. + + + + + FluentMocker implements some kind of fluent interface attempt + for saying "With the Mocks [mocks], Expecting (in same order) [things] verify [that]." + + + + + Interface to verify previously defined expectations + + + + + Verifies if a piece of code + + + + + Defines unordered expectations + + A delegate describing the expectations + an IMockVerifier + + + + Defines ordered expectations + + A delegate describing the expectations + an IMockVerifier + + + + Verifies previously defined expectations + + + + + This delegate is compatible with the System.Func{T,R} signature + We have to define our own to get compatability with 2.0 + + + + + This attribute is here so we can get better Pex integration + Using this means that Pex will not try to inspect the work of + the actual proxies being generated by Rhino Mocks + + + + diff --git a/src/umbraco.businesslogic/StateHelper.cs b/src/umbraco.businesslogic/StateHelper.cs index 10103cffdb..3884549f3f 100644 --- a/src/umbraco.businesslogic/StateHelper.cs +++ b/src/umbraco.businesslogic/StateHelper.cs @@ -9,7 +9,31 @@ namespace umbraco.BusinessLogic /// The StateHelper class provides general helper methods for handling sessions, context, viewstate and cookies. /// public class StateHelper - { + { + + private static HttpContextBase _httpContext; + + /// + /// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will + /// use the HttpContext.Current + /// + 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 /// @@ -20,7 +44,7 @@ namespace umbraco.BusinessLogic /// public static T GetSessionValue(string key) { - return GetSessionValue(HttpContext.Current, key); + return GetSessionValue(HttpContext, key); } /// @@ -30,7 +54,20 @@ namespace umbraco.BusinessLogic /// The context. /// The key. /// + [Obsolete("Use the GetSessionValue accepting an HttpContextBase instead")] public static T GetSessionValue(HttpContext context, string key) + { + return GetSessionValue(new HttpContextWrapper(context), key); + } + + /// + /// Gets the session value. + /// + /// + /// The context. + /// The key. + /// + public static T GetSessionValue(HttpContextBase context, string key) { if (context == null) return default(T); @@ -47,7 +84,7 @@ namespace umbraco.BusinessLogic /// The value. public static void SetSessionValue(string key, object value) { - SetSessionValue(HttpContext.Current, key, value); + SetSessionValue(HttpContext, key, value); } /// @@ -56,7 +93,19 @@ namespace umbraco.BusinessLogic /// The context. /// The key. /// The value. + [Obsolete("Use the SetSessionValue accepting an HttpContextBase instead")] public static void SetSessionValue(HttpContext context, string key, object value) + { + SetSessionValue(new HttpContextWrapper(context), key, value); + } + + /// + /// Sets the session value. + /// + /// The context. + /// The key. + /// The value. + public static void SetSessionValue(HttpContextBase context, string key, object value) { if (context == null) return; @@ -75,7 +124,7 @@ namespace umbraco.BusinessLogic /// public static T GetContextValue(string key) { - return GetContextValue(HttpContext.Current, key); + return GetContextValue(HttpContext, key); } /// @@ -85,7 +134,20 @@ namespace umbraco.BusinessLogic /// The context. /// The key. /// + [Obsolete("Use the GetContextValue accepting an HttpContextBase instead")] public static T GetContextValue(HttpContext context, string key) + { + return GetContextValue(new HttpContextWrapper(context), key); + } + + /// + /// Gets the context value. + /// + /// + /// The context. + /// The key. + /// + public static T GetContextValue(HttpContextBase context, string key) { if (context == null) return default(T); @@ -102,7 +164,7 @@ namespace umbraco.BusinessLogic /// The value. public static void SetContextValue(string key, object value) { - SetContextValue(HttpContext.Current, key, value); + SetContextValue(HttpContext, key, value); } /// @@ -111,7 +173,19 @@ namespace umbraco.BusinessLogic /// The context. /// The key. /// The value. + [Obsolete("Use the SetContextValue accepting an HttpContextBase instead")] public static void SetContextValue(HttpContext context, string key, object value) + { + SetContextValue(new HttpContextWrapper(context), key, value); + } + + /// + /// Sets the context value. + /// + /// The context. + /// The key. + /// The value. + public static void SetContextValue(HttpContextBase context, string key, object value) { if (context == null) return; @@ -128,15 +202,15 @@ namespace umbraco.BusinessLogic /// 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); } } }