From 233b0f93c70c85dfda65522eb1eb8fb9bb145cff Mon Sep 17 00:00:00 2001 From: Ivo Stoilov Date: Fri, 15 Sep 2023 11:35:57 +0300 Subject: [PATCH 1/9] Test execution hangs unexpectedly (#198) o closes telerik/MATTeam#622 --- .../Core/Behaviors/RecursiveMockingBehavior.cs | 10 +++++++--- .../Core/Behaviors/ThrowAsyncExceptionBehavior.cs | 14 +++++++------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/Telerik.JustMock/Core/Behaviors/RecursiveMockingBehavior.cs b/Telerik.JustMock/Core/Behaviors/RecursiveMockingBehavior.cs index 8282374a..93b1d7c5 100644 --- a/Telerik.JustMock/Core/Behaviors/RecursiveMockingBehavior.cs +++ b/Telerik.JustMock/Core/Behaviors/RecursiveMockingBehavior.cs @@ -163,9 +163,9 @@ private object CreateMock(Type returnType, MocksRepository repository, Invocatio ? CreateMock(elementType, repository, invocation) : elementType.GetDefaultValue(); - Expression>> taskFromResult = () => MockingUtil.TaskFromResult((object)null); - mock = ((MethodCallExpression)taskFromResult.Body).Method - .GetGenericMethodDefinition() + var taskFromResultMethod = typeof(MockingUtil).GetMethod("TaskFromResult", BindingFlags.Static | BindingFlags.Public); + + mock = taskFromResultMethod .MakeGenericMethod(elementType) .Invoke(null, new object[] { taskResultValue }); } @@ -189,6 +189,10 @@ private object CreateMock(Type returnType, MocksRepository repository, Invocatio { mock = String.Empty; } + else if (returnType.IsValueType) + { + mock = returnType.GetDefaultValue(); + } else { try diff --git a/Telerik.JustMock/Core/Behaviors/ThrowAsyncExceptionBehavior.cs b/Telerik.JustMock/Core/Behaviors/ThrowAsyncExceptionBehavior.cs index 54c5427c..24008a48 100644 --- a/Telerik.JustMock/Core/Behaviors/ThrowAsyncExceptionBehavior.cs +++ b/Telerik.JustMock/Core/Behaviors/ThrowAsyncExceptionBehavior.cs @@ -18,6 +18,7 @@ limitations under the License. using System; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using System.Threading.Tasks; using Telerik.JustMock.Core.Context; using Telerik.JustMock.Setup; @@ -49,13 +50,12 @@ public void Process(Invocation invocation) var elementType = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>) ? returnType.GetGenericArguments()[0] : typeof(object); - Expression>> taskFromException = - () => MockingUtil.TaskFromException((Exception)null); - var mock = - ((MethodCallExpression)taskFromException.Body).Method - .GetGenericMethodDefinition() - .MakeGenericMethod(elementType) - .Invoke(null, new object[] { this.exception }); + + var taskFromException = typeof(MockingUtil).GetMethod("TaskFromException", BindingFlags.Static | BindingFlags.Public); + + var mock = taskFromException + .MakeGenericMethod(elementType) + .Invoke(null, new object[] { this.exception }); var parentMock = invocation.MockMixin; var mockMixin = MocksRepository.GetMockMixin(mock, null); From 6b56ef45d496a5abf381e7258ae02944c5391196 Mon Sep 17 00:00:00 2001 From: Ivo Stoilov Date: Thu, 28 Sep 2023 21:55:49 +0300 Subject: [PATCH 2/9] Executing tests in a specific order results in a failure (#199) o added environment variable to control the newonj interception o closes telerik/MATTeam#621 --- Telerik.JustMock/Core/ProfilerInterceptor.cs | 12 +++- .../Expectations/CommonExpectation.cs | 61 +++++++++++++++++-- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/Telerik.JustMock/Core/ProfilerInterceptor.cs b/Telerik.JustMock/Core/ProfilerInterceptor.cs index 91a15abb..5bf23373 100644 --- a/Telerik.JustMock/Core/ProfilerInterceptor.cs +++ b/Telerik.JustMock/Core/ProfilerInterceptor.cs @@ -1,6 +1,6 @@ /* JustMock Lite - Copyright © 2010-2015,2021,2022 Progress Software Corporation + Copyright © 2010-2015,2021-2023 Progress Software Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -161,6 +161,14 @@ static ProfilerInterceptor() } else { + var newObjInterceptionOnOverwriteEnabledEnv = Environment.GetEnvironmentVariable("JUSTMOCK_NEWOBJ_INTERCEPTION_ON_OVERWRITE_ENABLED"); + NewObjInterceptionOnOverwriteEnabled = + !string.IsNullOrEmpty(newObjInterceptionOnOverwriteEnabledEnv) + ? + newObjInterceptionOnOverwriteEnabledEnv == "1" + : + true; + bridge = bridge.MakeGenericType(typeof(object)); #if !DEBUG @@ -684,6 +692,8 @@ public static void ThrowElevatedMockingException(MemberInfo member = null) public static readonly Func CreateStrongNameAssemblyNameImpl; public static readonly Func CreateInstanceWithArgsImpl; + public static bool NewObjInterceptionOnOverwriteEnabled { get; private set; } + private static readonly Type bridge; private static readonly Func GetTypeIdImpl; private static readonly Dictionary enabledInterceptions = new Dictionary(); diff --git a/Telerik.JustMock/Expectations/CommonExpectation.cs b/Telerik.JustMock/Expectations/CommonExpectation.cs index 86f8fc89..c752bfa5 100644 --- a/Telerik.JustMock/Expectations/CommonExpectation.cs +++ b/Telerik.JustMock/Expectations/CommonExpectation.cs @@ -1,6 +1,6 @@ /* JustMock Lite - Copyright © 2010-2015,2019,2021 Progress Software Corporation + Copyright © 2010-2015,2019,2021,2023 Progress Software Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,9 +19,11 @@ limitations under the License. using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using System.Reflection; using System.Threading; using Telerik.JustMock.Core; using Telerik.JustMock.Core.Behaviors; +using Telerik.JustMock.Core.Context; using Telerik.JustMock.Core.MatcherTree; using Telerik.JustMock.Expectations.Abstraction; @@ -41,8 +43,8 @@ public partial class CommonExpectation : IAction, IInsta IMockMixin IMethodMock.Mock { get; set; } bool IMethodMock.IsSequential { get; set; } - bool IMethodMock.IsInOrder { get; set; } - bool IMethodMock.IsUsed { get; set; } + bool IMethodMock.IsInOrder { get; set; } + bool IMethodMock.IsUsed { get; set; } CallPattern IMethodMock.CallPattern { get; set; } ICollection IMethodMock.Behaviors { get { return this.behaviors; } } InvocationOccurrenceBehavior IMethodMock.OccurencesBehavior { get { return this.occurences; } } @@ -91,6 +93,55 @@ internal CommonExpectation() /// protected void ProcessDoInstead(Delegate delg, bool ignoreDelegateReturnValue) { + +#if !PORTABLE + // force interception of construcor declaring type used in each newobj IL instruction + // in elevated mode, this will allow those types to be successfully resolved by the + // profiler while instrumenting newobj instructions on the JIT phase + if (ProfilerInterceptor.IsProfilerAttached + && ProfilerInterceptor.NewObjInterceptionOnOverwriteEnabled + && !ProfilerInterceptor.IsReJitEnabled) + { + MockingUtil.MethodBodyDisassembler.DisassembleMethodInfo(this.CallPattern.Method) + .Where(instr => instr.OpCode == System.Reflection.Emit.OpCodes.Newobj) + .ToList() + .ForEach(instr => + { + try + { + var objCtor = this.CallPattern.Method.DeclaringType.Module.ResolveMethod(instr.Operand.Int); + MockingContext.CurrentRepository.EnableInterception(objCtor.DeclaringType); + } + catch (ArgumentException) + { + // as a last shot, try to load referenced assemblies by the constructor declaring type + try + { + var notLoadedReferencedAssemblyNames = this.CallPattern.Method.DeclaringType.Assembly.GetReferencedAssemblies() + .Where(assemblyName => + !AppDomain.CurrentDomain.GetAssemblies() + .Select(assembly => assembly.GetName()) + .Contains(assemblyName)); + + foreach (var notLoadedReferencedAssemblyName in notLoadedReferencedAssemblyNames) + { + var manuallyLoadedReferencedAssembly = Assembly.Load(notLoadedReferencedAssemblyName.FullName); + if (manuallyLoadedReferencedAssembly.GetExportedTypes() + .SelectMany(type => type.GetConstructors()) + .Select(ctor => ctor.MetadataToken) + .Contains(instr.Operand.Int)) + { + break; + } + } + } + catch (Exception) { } + } + catch (Exception) { } + }); + } +#endif + if (delg == null) { var returnType = CallPattern.Method.GetReturnType(); @@ -442,8 +493,8 @@ public IOccurrence InOrder(string message = null) { return ProfilerInterceptor.GuardInternal(() => { - (this as IMethodMock).IsInOrder = true; - this.behaviors.Add(new InOrderBehavior(this.Repository, this.Mock, message)); + (this as IMethodMock).IsInOrder = true; + this.behaviors.Add(new InOrderBehavior(this.Repository, this.Mock, message)); return this; }); } From a69af1b413c1a1326bc29aa4f223eb158b5f90de Mon Sep 17 00:00:00 2001 From: Tsvetko Hadzhitsenev Date: Fri, 29 Sep 2023 17:54:42 +0300 Subject: [PATCH 3/9] Converted to package ref --- ...JustMock.NonElevatedExamples.VS2017.csproj | 22 ++++++------------- .../packages.config | 5 ----- ...JustMock.NonElevatedExamples.VS2019.csproj | 22 ++++++------------- .../packages.config | 5 ----- ...JustMock.NonElevatedExamples.VS2017.vbproj | 16 ++++++-------- .../packages.config | 5 ----- ...JustMock.NonElevatedExamples.VS2019.vbproj | 12 +++------- .../packages.config | 5 ----- 8 files changed, 24 insertions(+), 68 deletions(-) delete mode 100644 Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/packages.config delete mode 100644 Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/packages.config delete mode 100644 Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/packages.config delete mode 100644 Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/packages.config diff --git a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.csproj b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.csproj index c8e23f20..6c82ba64 100644 --- a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.csproj +++ b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.csproj @@ -20,6 +20,7 @@ + PackageReference true @@ -39,12 +40,6 @@ 4 - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll - - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll - @@ -77,16 +72,13 @@ - + + 2.2.8 + + + 2.2.8 + - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/packages.config b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/packages.config deleted file mode 100644 index bc45eeab..00000000 --- a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2017/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.csproj b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.csproj index 75572365..d37c61a1 100644 --- a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.csproj +++ b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.csproj @@ -20,6 +20,7 @@ + PackageReference true @@ -39,12 +40,6 @@ 4 - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll - - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll - @@ -77,16 +72,13 @@ - + + 2.2.8 + + + 2.2.8 + - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/packages.config b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/packages.config deleted file mode 100644 index 1c8e18df..00000000 --- a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2019/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.vbproj b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.vbproj index f341b007..82742544 100644 --- a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.vbproj +++ b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/JustMock.NonElevatedExamples.VS2017.vbproj @@ -20,6 +20,7 @@ + PackageReference true @@ -52,14 +53,6 @@ On - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll - True - - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll - True - @@ -116,7 +109,12 @@ - + + 2.2.8 + + + 2.2.8 + diff --git a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/packages.config b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/packages.config deleted file mode 100644 index bc45eeab..00000000 --- a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2017/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.vbproj b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.vbproj index a92fa2de..f34b6b91 100644 --- a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.vbproj +++ b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/JustMock.NonElevatedExamples.VS2019.vbproj @@ -52,14 +52,6 @@ On - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll - True - - - ..\packages\MSTest.TestFramework.2.2.8\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll - True - @@ -108,7 +100,9 @@ - + + 2.2.8 + diff --git a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/packages.config b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/packages.config deleted file mode 100644 index 1c8e18df..00000000 --- a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2019/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file From 3265dfed2f1ff113ce26c69d929ca5c483a3460a Mon Sep 17 00:00:00 2001 From: Tsvetko Hadzhitsenev Date: Fri, 29 Sep 2023 18:08:36 +0300 Subject: [PATCH 4/9] Updated VS 2022 projects --- .../JustMock.NonElevatedExamples.VS2022.csproj | 4 ++-- .../JustMock.NonElevatedExamples.VS2022.vbproj | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj index 102b25d5..14a2d4d8 100644 --- a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj +++ b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj @@ -2,7 +2,7 @@ JustMock.NonElevatedExamples.VS2022 - net6 + net7.0 false @@ -15,7 +15,7 @@ - $(registry:HKEY_LOCAL_MACHINE\Software\Telerik\JustMock@BinaryPath)netcoreapp2.0\Telerik.JustMock.dll + $(registry:HKEY_LOCAL_MACHINE\Software\Telerik\JustMock@BinaryPath)\netcoreapp2.0\Telerik.JustMock.dll diff --git a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.vbproj b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.vbproj index 4551466b..0f06b907 100644 --- a/Examples/VBExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.vbproj +++ b/Examples/VBExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.vbproj @@ -15,7 +15,7 @@ - $(registry:HKEY_LOCAL_MACHINE\Software\Telerik\JustMock@BinaryPath)netcoreapp2.0\Telerik.JustMock.dll + $(registry:HKEY_LOCAL_MACHINE\Software\Telerik\JustMock@BinaryPath)\netcoreapp2.0\Telerik.JustMock.dll From 06aee991b3345d817637302366f9ec4a2a1c8ae3 Mon Sep 17 00:00:00 2001 From: Tsvetko Hadzhitsenev Date: Mon, 2 Oct 2023 23:08:19 +0300 Subject: [PATCH 5/9] Update JustMock.NonElevatedExamples.VS2022.csproj --- .../JustMock.NonElevatedExamples.VS2022.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj index 14a2d4d8..f9c508f9 100644 --- a/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj +++ b/Examples/CSExamples/JustMock.NonElevatedExamples.VS2022/JustMock.NonElevatedExamples.VS2022.csproj @@ -2,7 +2,7 @@ JustMock.NonElevatedExamples.VS2022 - net7.0 + net6.0 false From 306084632ee3c628ccd32f29dba86986f0ca0741 Mon Sep 17 00:00:00 2001 From: Ivo Stoilov Date: Tue, 12 Dec 2023 17:17:56 +0200 Subject: [PATCH 6/9] Update Castle Core (#202) o closes #657 --- .../Telerik.JustMock.MSTest2.Tests.csproj | 6 +- .../Telerik.JustMock.NUnit.Tests.csproj | 10 +- .../Telerik.JustMock.XUnit.Tests.csproj | 2 +- .../Core/AttributesToAvoidReplicating.cs | 42 + .../Core/Context/StackTraceExtensions.cs | 2 +- .../CustomAttributeExtensions.cs | 58 - .../IntrospectionExtensions.cs | 35 - .../NetCoreReflectionExtensions.cs | 37 - .../RuntimeReflectionExtensions.cs | 33 - .../TypeBuilderExtensions.cs | 38 - .../Configuration/AbstractConfiguration.cs | 4 +- .../ConfigurationAttributeCollection.cs | 2 +- .../Configuration/ConfigurationCollection.cs | 4 +- .../Configuration/IConfiguration.cs | 6 +- .../Configuration/MutableConfiguration.cs | 9 +- .../Xml/XmlConfigurationDeserializer.cs | 3 +- .../Extensions/SilverlightExtensions.cs | 148 --- .../Castle.Core/Extensions/SimpleConverter.cs | 95 -- .../Castle.Core/IServiceEnabledComponent.cs | 4 +- .../Castle.Core/IServiceProviderEx.cs | 4 +- .../Castle.Core/IServiceProviderExAccessor.cs | 4 +- .../Castle.Core/Internal/AttributesUtil.cs | 11 +- .../Internal/CollectionExtensions.cs | 124 -- .../Castle.Core/Internal/ILockHolder.cs | 23 - .../Internal/IUpgradeableLockHolder.cs | 22 - .../Internal/InterfaceAttributeUtil.cs | 10 +- .../Castle.Core/Internal/InternalsVisible.cs | 2 +- .../Castle.Core/Internal/MonitorLockHolder.cs | 49 - .../Castle.Core/Internal/NoOpLock.cs | 31 - .../Internal/NoOpUpgradeableLock.cs | 41 - .../Castle.Core/Internal/PermissionUtil.cs | 42 - .../Internal/SlimReadLockHolder.cs | 48 - .../Internal/SlimWriteLockHolder.cs | 49 - .../Internal/SynchronizedDictionary.cs | 120 ++ .../Castle.Core/Internal/TypeExtensions.cs | 2 +- .../Castle.Core/Internal/WeakKey.cs | 2 +- .../Castle.Core/Internal/WeakKeyComparer.cs | 6 +- .../Castle.Core/Internal/WeakKeyDictionary.cs | 4 +- .../Logging/AbstractExtendedLoggerFactory.cs | 22 +- .../Logging/AbstractLoggerFactory.cs | 23 +- .../Castle.Core/Logging/ConsoleFactory.cs | 12 +- .../Castle.Core/Logging/ConsoleLogger.cs | 30 +- .../Castle.Core/Logging/DiagnosticsLogger.cs | 13 +- .../Logging/DiagnosticsLoggerFactory.cs | 9 +- .../Castle.Core/Logging/IContextProperties.cs | 4 +- .../Castle.Core/Logging/IContextStack.cs | 4 +- .../Castle.Core/Logging/IContextStacks.cs | 4 +- .../Castle.Core/Logging/IExtendedLogger.cs | 4 +- .../Logging/IExtendedLoggerFactory.cs | 8 +- .../Castle.Core/Logging/ILogger.cs | 127 ++- .../Castle.Core/Logging/ILoggerFactory.cs | 8 +- .../Logging/LevelFilteredLogger.cs | 213 ++-- .../Castle.Core/Logging/LoggerException.cs | 14 +- .../Castle.Core/Logging/LoggerLevel.cs | 8 +- .../Castle.Core/Logging/NullLogFactory.cs | 16 +- .../Castle.Core/Logging/NullLogger.cs | 74 +- .../Castle.Core/Logging/StreamLogger.cs | 30 +- .../Logging/StreamLoggerFactory.cs | 14 +- .../Castle.Core/Logging/TraceLogger.cs | 66 +- .../Castle.Core/Logging/TraceLoggerFactory.cs | 20 +- .../Core/DynamicProxy/Castle.Core/Pair.cs | 78 -- .../DynamicProxy/Castle.Core/ProxyServices.cs | 12 +- .../Castle.Core/ReferenceEqualityComparer.cs | 6 +- .../ReflectionBasedDictionaryAdapter.cs | 24 +- .../Castle.Core/Resource/AbstractResource.cs | 4 +- .../Resource/AbstractStreamResource.cs | 12 +- .../Resource/AssemblyBundleResource.cs | 10 +- .../Castle.Core/Resource/AssemblyResource.cs | 44 +- .../Resource/AssemblyResourceFactory.cs | 6 +- .../Castle.Core/Resource/ConfigResource.cs | 10 +- .../Resource/ConfigResourceFactory.cs | 4 +- .../Castle.Core/Resource/CustomUri.cs | 30 +- .../Castle.Core/Resource/FileResource.cs | 42 +- .../Resource/FileResourceFactory.cs | 12 +- .../Castle.Core/Resource/IResource.cs | 24 +- .../Castle.Core/Resource/IResourceFactory.cs | 19 +- .../Castle.Core/Resource/ResourceException.cs | 12 +- .../Resource/StaticContentResource.cs | 14 +- .../Castle.Core/Resource/UncResource.cs | 30 +- .../Resource/UncResourceFactory.cs | 4 +- .../Castle.Core/Smtp/DefaultSmtpSender.cs | 73 +- .../Castle.Core/Smtp/IEmailSender.cs | 4 +- .../StringObjectDictionaryAdapter.cs | 4 +- .../Castle.DynamicProxy/AbstractInvocation.cs | 66 +- .../Castle.DynamicProxy/AllMethodsHook.cs | 37 +- .../Contributors/ClassMembersCollector.cs | 7 +- ...s => ClassProxySerializableContributor.cs} | 166 +-- .../ClassProxyTargetContributor.cs | 83 +- ...ClassProxyWithTargetInstanceContributor.cs | 37 - .../ClassProxyWithTargetTargetContributor.cs | 100 +- .../Contributors/CompositeTypeContributor.cs | 109 +- .../DelegateProxyTargetContributor.cs | 79 -- .../DelegateTypeMembersCollector.cs} | 30 +- .../Contributors/Delegates.cs | 10 +- .../Contributors/FieldReferenceComparer.cs | 4 +- .../IInvocationCreationContributor.cs | 10 +- .../IMembersCollectorSink.cs} | 21 +- .../Contributors/ITypeContributor.cs | 6 +- .../Contributors/InterfaceMembersCollector.cs | 12 +- .../InterfaceMembersOnClassCollector.cs | 4 +- .../InterfaceProxyInstanceContributor.cs | 57 - .../InterfaceProxySerializableContributor.cs | 54 + .../InterfaceProxyTargetContributor.cs | 42 +- ...rfaceProxyWithOptionalTargetContributor.cs | 7 +- ...oxyWithTargetInterfaceTargetContributor.cs | 4 +- .../InterfaceProxyWithoutTargetContributor.cs | 52 +- .../InvocationWithDelegateContributor.cs | 24 +- ...nvocationWithGenericDelegateContributor.cs | 17 +- .../Contributors/MembersCollector.cs | 226 ++-- .../Contributors/MixinContributor.cs | 63 +- .../NonInheritableAttributesContributor.cs | 47 + .../Contributors/ProxyInstanceContributor.cs | 209 ---- .../ProxyTargetAccessorContributor.cs | 74 ++ .../Contributors/SerializableContributor.cs | 153 +++ .../WrappedClassMembersCollector.cs | 14 +- .../CustomAttributeInfo.cs | 48 +- .../DefaultProxyBuilder.cs | 81 +- .../Castle.DynamicProxy/DynProxy.snk | Bin 596 -> 0 bytes .../DynamicProxyException.cs | 39 + .../ExceptionMessageBuilder.cs | 12 +- .../Generators/AttributeDisassembler.cs | 312 ----- .../AttributesToAvoidReplicating.cs | 71 +- .../Generators/BaseClassProxyGenerator.cs | 219 ++++ .../Generators/BaseInterfaceProxyGenerator.cs | 296 +++++ .../Generators/BaseProxyGenerator.cs | 265 ++--- .../Generators/CacheKey.cs | 12 +- .../Generators/ClassProxyGenerator.cs | 191 +--- .../ClassProxyWithTargetGenerator.cs | 208 +--- .../CompositionInvocationTypeGenerator.cs | 14 +- .../Generators/DelegateProxyGenerationHook.cs | 49 - .../Generators/DelegateProxyGenerator.cs | 133 --- .../DelegateTypeGenerator.cs | 12 +- .../Emitters/AbstractTypeEmitter.cs | 188 ++- .../Generators/Emitters/ArgumentsUtil.cs | 63 +- .../Generators/Emitters/ClassEmitter.cs | 45 +- .../Generators/Emitters/CodeBuilder.cs | 68 ++ .../CodeBuilders/AbstractCodeBuilder.cs | 86 -- .../CodeBuilders/ConstructorCodeBuilder.cs | 59 - .../CodeBuilders/MethodCodeBuilder.cs | 25 - .../Generators/Emitters/ConstructorEmitter.cs | 65 +- .../Generators/Emitters/EventEmitter.cs | 8 +- .../Generators/Emitters/GenericUtil.cs | 117 +- .../Generators/Emitters/IMemberEmitter.cs | 4 +- .../Emitters/LdcOpCodesDictionary.cs | 9 +- .../Emitters/LdindOpCodesDictionary.cs | 8 +- .../Generators/Emitters/MethodEmitter.cs | 68 +- .../Emitters/NestedClassCollection.cs | 22 - .../Generators/Emitters/NestedClassEmitter.cs | 22 +- .../Generators/Emitters/OpCodeUtil.cs | 60 +- .../Emitters/PropertiesCollection.cs | 25 - .../Generators/Emitters/PropertyEmitter.cs | 4 +- .../SimpleAST/AddressOfReferenceExpression.cs | 35 - .../Emitters/SimpleAST/ArgumentReference.cs | 52 +- .../Emitters/SimpleAST/AsTypeReference.cs | 8 +- .../SimpleAST/AssignArgumentStatement.cs | 14 +- .../SimpleAST/AssignArrayStatement.cs | 14 +- .../Emitters/SimpleAST/AssignStatement.cs | 14 +- .../SimpleAST/BindDelegateExpression.cs | 59 - ...ferenceExpression.cs => BlockStatement.cs} | 20 +- .../Emitters/SimpleAST/ByRefReference.cs | 4 +- .../Emitters/SimpleAST/ConstReference.cs | 57 - .../ConstructorInvocationStatement.cs | 36 +- .../Emitters/SimpleAST/ConvertExpression.cs | 52 +- .../SimpleAST/DefaultValueExpression.cs | 26 +- .../SimpleAST/EndExceptionBlockStatement.cs | 8 +- .../Emitters/SimpleAST/ExpressionStatement.cs | 34 - .../Emitters/SimpleAST/FieldReference.cs | 20 +- .../Emitters/SimpleAST/FinallyStatement.cs | 8 +- .../IExpression.cs} | 10 +- ...ILEmitter.cs => IExpressionOrStatement.cs} | 8 +- .../IStatement.cs} | 18 +- .../Emitters/SimpleAST/IfNullExpression.cs | 24 +- .../Emitters/SimpleAST/IndirectReference.cs | 10 +- ...Expression.cs => LiteralBoolExpression.cs} | 26 +- .../SimpleAST/LiteralIntExpression.cs | 10 +- ...tatement.cs => LiteralStringExpression.cs} | 25 +- .../SimpleAST/LoadArrayElementExpression.cs | 45 - .../LoadRefArrayElementExpression.cs | 19 +- .../Emitters/SimpleAST/LocalReference.cs | 14 +- .../SimpleAST/MethodInvocationExpression.cs | 20 +- .../SimpleAST/MethodTokenExpression.cs | 22 +- .../SimpleAST/MultiStatementExpression.cs | 42 - .../Emitters/SimpleAST/NewArrayExpression.cs | 11 +- .../SimpleAST/NewInstanceExpression.cs | 40 +- .../NullCoalescingOperatorExpression.cs | 22 +- .../Emitters/SimpleAST/NullExpression.cs | 8 +- .../Emitters/SimpleAST/Reference.cs | 15 +- .../ReferencesToObjectArrayExpression.cs | 30 +- .../Emitters/SimpleAST/ReturnStatement.cs | 21 +- .../Emitters/SimpleAST/SelfReference.cs | 4 +- .../Emitters/SimpleAST/Statement.cs | 23 - .../Emitters/SimpleAST/ThrowStatement.cs | 19 +- .../Emitters/SimpleAST/TryStatement.cs | 8 +- .../Emitters/SimpleAST/TypeReference.cs | 4 +- .../Emitters/SimpleAST/TypeTokenExpression.cs | 8 +- .../Emitters/StindOpCodesDictionary.cs | 8 +- .../Generators/Emitters/StrongNameUtil.cs | 41 +- .../Emitters/TypeConstructorEmitter.cs | 8 +- .../ForwardingMethodGenerator.cs | 10 +- .../Generators/GeneratorException.cs | 41 - .../Generators/GeneratorUtil.cs | 53 +- .../Generators/IGenerator.cs | 6 +- .../Generators/INamingScope.cs | 4 +- .../InheritanceInvocationTypeGenerator.cs | 6 +- .../InterfaceProxyWithTargetGenerator.cs | 282 +---- ...erfaceProxyWithTargetInterfaceGenerator.cs | 46 +- .../InterfaceProxyWithoutTargetGenerator.cs | 95 +- .../Generators/InvocationTypeGenerator.cs | 83 +- .../Generators/MetaEvent.cs | 39 +- .../Generators/MetaMethod.cs | 26 +- .../Generators/MetaProperty.cs | 30 +- .../Generators/MetaType.cs | 18 +- .../Generators/MetaTypeElement.cs | 81 +- ...ection.cs => MetaTypeElementCollection.cs} | 33 +- .../Generators/MetaTypeElementUtil.cs | 58 - .../Generators/MethodFinder.cs | 6 +- .../Generators/MethodGenerator.cs | 12 +- .../Generators/MethodSignatureComparer.cs | 53 +- .../MethodWithInvocationGenerator.cs | 65 +- .../MinimalisticMethodGenerator.cs} | 16 +- .../Generators/NamingScope.cs | 4 +- .../OptionallyForwardingMethodGenerator.cs | 43 +- .../IAttributeDisassembler.cs | 39 - .../Castle.DynamicProxy/IChangeProxyTarget.cs | 4 +- .../Castle.DynamicProxy/IInterceptor.cs | 19 +- .../IInterceptorSelector.cs | 4 +- .../Castle.DynamicProxy/IInvocation.cs | 12 +- .../IInvocationProceedInfo.cs | 31 + .../Castle.DynamicProxy/IProxyBuilder.cs | 20 +- .../IProxyGenerationHook.cs | 4 +- .../Castle.DynamicProxy/IProxyGenerator.cs | 2 +- .../IProxyTargetAccessor.cs | 8 +- .../Internal/AttributeUtil.cs | 109 +- .../Internal/CompositionInvocation.cs | 12 +- .../Internal/InheritanceInvocation.cs | 12 +- .../InheritanceInvocationWithoutTarget.cs | 36 + .../InterfaceMethodWithoutTargetInvocation.cs | 61 + .../Internal/InternalsUtil.cs | 61 - .../Internal/InvocationHelper.cs | 66 +- .../Castle.DynamicProxy/Internal/TypeUtil.cs | 131 +-- .../InvalidMixinConfigurationException.cs | 42 - ...validProxyConstructorArgumentsException.cs | 33 - .../Castle.DynamicProxy/MixinData.cs | 96 +- .../Castle.DynamicProxy/ModuleScope.cs | 1016 ++++++++--------- .../PersistentProxyBuilder.cs | 22 +- .../ProxyGenerationException.cs | 29 - .../ProxyGenerationOptions.cs | 182 ++- .../Castle.DynamicProxy/ProxyGenerator.cs | 148 +-- .../Castle.DynamicProxy/ProxyUtil.cs | 143 +-- .../Serialization/CacheMappingsAttribute.cs | 8 +- .../Serialization/ProxyObjectReference.cs | 60 +- .../Serialization/ProxyTypeConstants.cs | 2 +- .../StandardInterceptor.cs | 10 +- .../Tokens/DelegateMethods.cs | 4 +- .../Tokens/FormatterServicesMethods.cs | 2 +- .../Tokens/InterceptorSelectorMethods.cs | 4 +- .../Tokens/InvocationMethods.cs | 13 +- .../Tokens/MethodBaseMethods.cs | 4 +- .../Tokens/SerializationInfoMethods.cs | 10 +- .../Tokens/TypeBuilderMethods.cs | 31 - .../Castle.DynamicProxy/Tokens/TypeMethods.cs | 4 +- .../Tokens/TypeUtilMethods.cs | 4 +- Telerik.JustMock/Core/DynamicProxy/VERSION | 1 + .../Core/DynamicProxyMockFactory.cs | 52 +- Telerik.JustMock/Core/Internal/ILockHolder.cs | 26 + .../Core/Internal/IUpgradeableLockHolder.cs | 25 + .../Castle.Core => }/Internal/Lock.cs | 31 +- .../Castle.Core => }/Internal/MonitorLock.cs | 35 +- .../Core/Internal/MonitorLockHolder.cs | 52 + .../Internal/MonitorUpgradeableLockHolder.cs | 35 +- Telerik.JustMock/Core/Internal/NoOpLock.cs | 34 + .../Core/Internal/NoOpUpgradeableLock.cs | 44 + .../Core/Internal/SlimReadLockHolder.cs | 51 + .../Internal/SlimReadWriteLock.cs | 35 +- .../Internal/SlimUpgradeableReadLockHolder.cs | 33 +- .../Core/Internal/SlimWriteLockHolder.cs | 52 + Telerik.JustMock/Core/MocksRepository.cs | 2 +- .../Core/TransparentProxy/ProxyInvocation.cs | 7 +- Telerik.JustMock/Telerik.JustMock.csproj | 34 +- 279 files changed, 5183 insertions(+), 7063 deletions(-) create mode 100644 Telerik.JustMock/Core/AttributesToAvoidReplicating.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/CustomAttributeExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/IntrospectionExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/NetCoreReflectionExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/RuntimeReflectionExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/TypeBuilderExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SilverlightExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SimpleConverter.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/CollectionExtensions.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/ILockHolder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/IUpgradeableLockHolder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLockHolder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpLock.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpUpgradeableLock.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/PermissionUtil.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadLockHolder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimWriteLockHolder.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SynchronizedDictionary.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.Core/Pair.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/{ClassProxyInstanceContributor.cs => ClassProxySerializableContributor.cs} (56%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetInstanceContributor.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateProxyTargetContributor.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Generators/DelegateMembersCollector.cs => Contributors/DelegateTypeMembersCollector.cs} (55%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Generators => Contributors}/IInvocationCreationContributor.cs (77%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Generators/Emitters/ConstructorCollection.cs => Contributors/IMembersCollectorSink.cs} (56%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyInstanceContributor.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxySerializableContributor.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/NonInheritableAttributesContributor.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyInstanceContributor.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyTargetAccessorContributor.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/SerializableContributor.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DynProxy.snk create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DynamicProxyException.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributeDisassembler.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseClassProxyGenerator.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseInterfaceProxyGenerator.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerationHook.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerator.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Contributors => Generators}/DelegateTypeGenerator.cs (90%) create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/AbstractCodeBuilder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/ConstructorCodeBuilder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/MethodCodeBuilder.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassCollection.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertiesCollection.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AddressOfReferenceExpression.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BindDelegateExpression.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/{ReferenceExpression.cs => BlockStatement.cs} (59%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstReference.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ExpressionStatement.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/{EventCollection.cs => SimpleAST/IExpression.cs} (72%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/{IILEmitter.cs => IExpressionOrStatement.cs} (76%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/{MethodCollection.cs => SimpleAST/IStatement.cs} (71%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/{Expression.cs => LiteralBoolExpression.cs} (61%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/{NopStatement.cs => LiteralStringExpression.cs} (63%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadArrayElementExpression.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MultiStatementExpression.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Statement.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Contributors => Generators}/ForwardingMethodGenerator.cs (82%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorException.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/{TypeElementCollection.cs => MetaTypeElementCollection.cs} (67%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementUtil.cs rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Contributors/MinimialisticMethodGenerator.cs => Generators/MinimalisticMethodGenerator.cs} (76%) rename Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/{Contributors => Generators}/OptionallyForwardingMethodGenerator.cs (67%) delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IAttributeDisassembler.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocationProceedInfo.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocationWithoutTarget.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InterfaceMethodWithoutTargetInvocation.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InternalsUtil.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidMixinConfigurationException.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidProxyConstructorArgumentsException.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationException.cs delete mode 100644 Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeBuilderMethods.cs create mode 100644 Telerik.JustMock/Core/DynamicProxy/VERSION create mode 100644 Telerik.JustMock/Core/Internal/ILockHolder.cs create mode 100644 Telerik.JustMock/Core/Internal/IUpgradeableLockHolder.cs rename Telerik.JustMock/Core/{DynamicProxy/Castle.Core => }/Internal/Lock.cs (50%) rename Telerik.JustMock/Core/{DynamicProxy/Castle.Core => }/Internal/MonitorLock.cs (55%) create mode 100644 Telerik.JustMock/Core/Internal/MonitorLockHolder.cs rename Telerik.JustMock/Core/{DynamicProxy/Castle.Core => }/Internal/MonitorUpgradeableLockHolder.cs (54%) create mode 100644 Telerik.JustMock/Core/Internal/NoOpLock.cs create mode 100644 Telerik.JustMock/Core/Internal/NoOpUpgradeableLock.cs create mode 100644 Telerik.JustMock/Core/Internal/SlimReadLockHolder.cs rename Telerik.JustMock/Core/{DynamicProxy/Castle.Core => }/Internal/SlimReadWriteLock.cs (68%) rename Telerik.JustMock/Core/{DynamicProxy/Castle.Core => }/Internal/SlimUpgradeableReadLockHolder.cs (67%) create mode 100644 Telerik.JustMock/Core/Internal/SlimWriteLockHolder.cs diff --git a/Telerik.JustMock.MSTest2.Tests/Telerik.JustMock.MSTest2.Tests.csproj b/Telerik.JustMock.MSTest2.Tests/Telerik.JustMock.MSTest2.Tests.csproj index c63b8690..6eaa6dfa 100644 --- a/Telerik.JustMock.MSTest2.Tests/Telerik.JustMock.MSTest2.Tests.csproj +++ b/Telerik.JustMock.MSTest2.Tests/Telerik.JustMock.MSTest2.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1;netcoreapp3.1;net5.0 - net451;net472;$(NetCoreSupportedVersions) + netcoreapp3.1;net5.0 + net461;net472;$(NetCoreSupportedVersions) Debug;Release;ReleaseFree;DebugFree Telerik.JustMock.MSTest2.Tests Telerik.JustMock.Tests @@ -90,7 +90,7 @@ - + \ No newline at end of file diff --git a/Telerik.JustMock.NUnit.Tests/Telerik.JustMock.NUnit.Tests.csproj b/Telerik.JustMock.NUnit.Tests/Telerik.JustMock.NUnit.Tests.csproj index 5cead419..1c582c65 100644 --- a/Telerik.JustMock.NUnit.Tests/Telerik.JustMock.NUnit.Tests.csproj +++ b/Telerik.JustMock.NUnit.Tests/Telerik.JustMock.NUnit.Tests.csproj @@ -1,6 +1,6 @@  - net451;netcoreapp2.1;netcoreapp3.1 + net451;netcoreapp3.1 Debug;Release;DebugFree;ReleaseFree Telerik.JustMock.NUnit.Tests Telerik.JustMock.Tests @@ -69,10 +69,10 @@ - - - + + + - + \ No newline at end of file diff --git a/Telerik.JustMock.XUnit.Tests/Telerik.JustMock.XUnit.Tests.csproj b/Telerik.JustMock.XUnit.Tests/Telerik.JustMock.XUnit.Tests.csproj index 58baaacf..4fba7c04 100644 --- a/Telerik.JustMock.XUnit.Tests/Telerik.JustMock.XUnit.Tests.csproj +++ b/Telerik.JustMock.XUnit.Tests/Telerik.JustMock.XUnit.Tests.csproj @@ -1,6 +1,6 @@  - net452;net472;netcoreapp2.1;netcoreapp3.1 + net452;net472;netcoreapp3.1 Debug;Release;DebugFree;ReleaseFree Telerik.JustMock.XUnit.Tests Telerik.JustMock.Tests diff --git a/Telerik.JustMock/Core/AttributesToAvoidReplicating.cs b/Telerik.JustMock/Core/AttributesToAvoidReplicating.cs new file mode 100644 index 00000000..7de242af --- /dev/null +++ b/Telerik.JustMock/Core/AttributesToAvoidReplicating.cs @@ -0,0 +1,42 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +using System; + +namespace Telerik.JustMock.Core +{ + /// + /// A list of attributes that must not be replicated when building a proxy. JustMock + /// tries to copy all attributes from the types and methods being proxied, but that is + /// not always a good idea for every type of attribute. Add additional attributes + /// to this list that prevent the proxy from working correctly. + /// +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + public class AttributesToAvoidReplicating + { + public static void Add(Type attribute) + { + ProfilerInterceptor.GuardInternal(() => Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(attribute)); + } + + public static void Add() + { + ProfilerInterceptor.GuardInternal(() => Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add()); + } + } +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +} diff --git a/Telerik.JustMock/Core/Context/StackTraceExtensions.cs b/Telerik.JustMock/Core/Context/StackTraceExtensions.cs index e486a427..b14c93a1 100644 --- a/Telerik.JustMock/Core/Context/StackTraceExtensions.cs +++ b/Telerik.JustMock/Core/Context/StackTraceExtensions.cs @@ -21,7 +21,7 @@ limitations under the License. using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using Telerik.JustMock.Core.Castle.Core.Internal; +using Telerik.JustMock.Core.Internal; namespace Telerik.JustMock.Core.Context { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/CustomAttributeExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/CustomAttributeExtensions.cs deleted file mode 100644 index a45d0377..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/CustomAttributeExtensions.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2004-2015 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if FEATURE_LEGACY_REFLECTION_API - -namespace System.Reflection -{ - using System.Collections.Generic; - - // This allows us to use the new reflection API while still supporting .NET 3.5 and 4.0. - // - // Methods like Attribute.IsDefined no longer exist in .NET Core so this provides a shim - // for .NET 3.5 and 4.0. - // - // This class only implemented the required extensions so add more if needed in the order - // from https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Extensions/ref/System.Reflection.Extensions.cs - internal static class CustomAttributeExtensions - { - public static IEnumerable GetCustomAttributes(this Assembly element) where T : Attribute - { - foreach (T a in Attribute.GetCustomAttributes(element, typeof(T))) - { - yield return a; - } - } - - public static IEnumerable GetCustomAttributes(this MemberInfo element, bool inherit) where T : Attribute - { - foreach (T a in Attribute.GetCustomAttributes(element, typeof(T), inherit)) - { - yield return a; - } - } - - public static bool IsDefined(this MemberInfo element, Type attributeType) - { - return Attribute.IsDefined(element, attributeType); - } - - public static bool IsDefined(this ParameterInfo element, Type attributeType) - { - return Attribute.IsDefined(element, attributeType); - } - } -} - -#endif \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/IntrospectionExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/IntrospectionExtensions.cs deleted file mode 100644 index 3630ae1c..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/IntrospectionExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2004-2015 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if FEATURE_LEGACY_REFLECTION_API - -namespace System.Reflection -{ - internal static class IntrospectionExtensions - { - // This allows us to use the new reflection API which separates Type and TypeInfo - // while still supporting .NET 3.5 and 4.0. This class matches the API of the same - // class in .NET 4.5+, and so is only needed on .NET Framework versions before that. - // - // Return the System.Type for now, we will probably need to create a TypeInfo class - // which inherits from Type like .NET 4.5+ and implement the additional methods and - // properties. - public static Type GetTypeInfo(this Type type) - { - return type; - } - } -} - -#endif \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/NetCoreReflectionExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/NetCoreReflectionExtensions.cs deleted file mode 100644 index a894acf1..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/NetCoreReflectionExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2004-2015 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if FEATURE_NETCORE_REFLECTION_API - -namespace System.Reflection -{ - using System.Linq; - - internal static class NetCoreReflectionExtensions - { - // .NET Core needs to expose GetConstructor that takes both flags and parameter types, - // because we need to get the private constructor for a type with multiple constructors. - // It should also provide the same for GetMethod, which luckily we don't need yet. - public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingAttr, object binder, Type[] types, object[] modifiers) - { - if (binder != null) throw new NotSupportedException("Parameter binder must be null."); - if (modifiers != null) throw new NotSupportedException("Parameter modifiers must be null."); - - return type.GetConstructors(bindingAttr) - .SingleOrDefault(ctor => ctor.GetParameters().Select(p => p.ParameterType).SequenceEqual(types)); - } - } -} - -#endif \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/RuntimeReflectionExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/RuntimeReflectionExtensions.cs deleted file mode 100644 index 53ba0abf..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/RuntimeReflectionExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2004-2015 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if FEATURE_LEGACY_REFLECTION_API - -namespace System.Reflection -{ - // This allows us to use the new reflection API while still supporting .NET 3.5 and 4.0. - // - // Methods like Type.GetInterfaceMap no longer exist in .NET Core so this provides a shim - // for .NET 3.5 and 4.0. - internal static class RuntimeReflectionExtensions - { - // Delegate to the old name for this method. - public static InterfaceMapping GetRuntimeInterfaceMap(this Type type, Type interfaceType) - { - return type.GetInterfaceMap(interfaceType); - } - } -} - -#endif \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/TypeBuilderExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/TypeBuilderExtensions.cs deleted file mode 100644 index e71d7a10..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Compatibility/TypeBuilderExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2004-2015 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if FEATURE_LEGACY_REFLECTION_API || NETCORE - -namespace System.Reflection -{ - using System.Reflection.Emit; - - // This allows us to use the new reflection API while still supporting .NET 3.5 and 4.0. - internal static class TypeBuilderExtensions - { - // TypeBuilder and GenericTypeParameterBuilder no longer inherit from Type but TypeInfo, - // so there is now an AsType method to get the Type which we are providing here to shim to itself. - public static Type AsType(this TypeBuilder builder) - { - return builder; - } - - public static Type AsType(this GenericTypeParameterBuilder builder) - { - return builder; - } - } -} - -#endif \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/AbstractConfiguration.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/AbstractConfiguration.cs index 91e5724e..e6ef7083 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/AbstractConfiguration.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/AbstractConfiguration.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -83,7 +83,7 @@ public virtual object GetValue(Type type, object defaultValue) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } try diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationAttributeCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationAttributeCollection.cs index 70b21dd4..59219321 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationAttributeCollection.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationAttributeCollection.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationCollection.cs index 7787894f..d4a54a80 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationCollection.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/ConfigurationCollection.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public ConfigurationCollection(IEnumerable value) : base(value) { } - public IConfiguration this[String name] + public IConfiguration this[string name] { get { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/IConfiguration.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/IConfiguration.cs index 58966d07..31b0e9c3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/IConfiguration.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/IConfiguration.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ internal interface IConfiguration /// /// The Name of the node. /// - String Name { get; } + string Name { get; } /// /// Gets the value of the node. @@ -37,7 +37,7 @@ internal interface IConfiguration /// /// The Value of the node. /// - String Value { get; } + string Value { get; } /// /// Gets an of diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/MutableConfiguration.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/MutableConfiguration.cs index ae66137c..cf543780 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/MutableConfiguration.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/MutableConfiguration.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ namespace Telerik.JustMock.Core.Castle.Core.Configuration { using System; - /// - /// Summary description for MutableConfiguration. - /// #if FEATURE_SERIALIZATION [Serializable] #endif @@ -28,11 +25,11 @@ internal class MutableConfiguration : AbstractConfiguration /// Initializes a new instance of the class. /// /// The name. - public MutableConfiguration(String name) : this(name, null) + public MutableConfiguration(string name) : this(name, null) { } - public MutableConfiguration(String name, String value) + public MutableConfiguration(string name, string value) { Name = name; Value = value; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/Xml/XmlConfigurationDeserializer.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/Xml/XmlConfigurationDeserializer.cs index f57b5059..107de4cb 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/Xml/XmlConfigurationDeserializer.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Configuration/Xml/XmlConfigurationDeserializer.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ internal class XmlConfigurationDeserializer /// Deserializes the specified node into an abstract representation of configuration. /// /// The node. - /// public IConfiguration Deserialize(XmlNode node) { return GetDeserializedNode(node); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SilverlightExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SilverlightExtensions.cs deleted file mode 100644 index c1cd5703..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SilverlightExtensions.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if SILVERLIGHT - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.SilverlightExtensions -{ - using System; - using System.Collections.Generic; - using System.Reflection; - - internal class SilverlightAssertException : Exception - { - public SilverlightAssertException(string message) : base(message) - { - } - - public SilverlightAssertException() - { - } - } - - internal static class Extensions - { - public static Type[] FindInterfaces(this Type type, TypeFilter filter, object filterCriteria) - { - if (filter == null) - throw new ArgumentNullException("filter"); - - List ifaces = new List(); - foreach (Type iface in type.GetInterfaces()) - { - if (filter(iface, filterCriteria)) - ifaces.Add(iface); - } - - return ifaces.ToArray(); - } - - /// - /// The silverlight System.Type is missing the IsNested property so this exposes similar functionality. - /// - /// - /// - public static bool IsNested(this Type type) - { - return type.DeclaringType != null; - } - } -} - -namespace System.Reflection -{ - internal delegate bool TypeFilter(Type m, object filterCriteria); -} - -namespace System.Diagnostics -{ - internal sealed class Trace - { - public static void WriteLine(string message) - { - //TODO:??? - } - - public static void Write(Exception e, string message) - { - //TODO:??? - } - - public static void Assert(bool condition) - { - if (!condition) - { - //TODO:??? - throw new Telerik.JustMock.Core.Castle.DynamicProxy.SilverlightExtensions.SilverlightAssertException(); - } - } - - public static void Assert(bool condition, string message) - { - if (!condition) - { - //TODO:??? - throw new Telerik.JustMock.Core.Castle.DynamicProxy.SilverlightExtensions.SilverlightAssertException(message); - } - } - } -} -namespace System.ComponentModel -{ - using System.Collections.Generic; - - using Telerik.JustMock.Core.Castle.Core.Extensions; - - internal static class TypeDescriptor - { - private static readonly IDictionary converters = new Dictionary(); - - static TypeDescriptor() - { - SimpleConverter.Register(); - } - - public static TypeConverter GetConverter(Type type) - { - TypeConverter converter; - converters.TryGetValue(type, out converter); - return converter; - } - - public static void RegisterConverter(Type forType, TypeConverter converter) - { - converters[forType] = converter; - } - } -} -#endif - -#if SL4 - -namespace System.ComponentModel -{ - internal delegate void PropertyChangingEventHandler(object sender, PropertyChangingEventArgs e); - internal class PropertyChangingEventArgs : EventArgs - { - - public PropertyChangingEventArgs(string propertyName) - { - PropertyName = propertyName; - } - - public virtual string PropertyName { get; private set; } - } -} - -#endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SimpleConverter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SimpleConverter.cs deleted file mode 100644 index 5cd8c983..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Extensions/SimpleConverter.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Extensions -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Globalization; - -#if SILVERLIGHT - - internal class SimpleConverter : TypeConverter - { - private static readonly Dictionary> converters = new Dictionary> - { - {typeof (int), i => int.Parse(i)}, - {typeof (short), s => short.Parse(s)}, - {typeof (long), l => long.Parse(l)}, - {typeof (float), f => float.Parse(f)}, - {typeof (double), d => double.Parse(d)}, - {typeof (decimal), d => decimal.Parse(d)}, - {typeof (Guid), g => new Guid(g)}, - { - typeof (TimeSpan), - s => TimeSpan.Parse(s) - }, - { - typeof (DateTime), - t => DateTime.Parse(t) - } - }; - - private readonly Func conversionFunction; - private readonly Type type; - - public SimpleConverter(Type type, Func conversionFunction) - { - this.type = type; - this.conversionFunction = conversionFunction; - } - - public static void Register() - { - foreach (var key in converters) - { - var converter = new SimpleConverter(key.Key, key.Value); - TypeDescriptor.RegisterConverter(key.Key, converter); - TypeDescriptor.RegisterConverter(typeof (Nullable<>).MakeGenericType(key.Key), converter); - } - } - - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof (string); - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - return destinationType.IsAssignableFrom(type); - } - - private object Convert(string sourceString) - { - if (sourceString == null) - { - return null; - } - return conversionFunction.Invoke(sourceString); - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - return Convert(value as string); - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, - Type destinationType) - { - return Convert(value as string); - } - } -#endif -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceEnabledComponent.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceEnabledComponent.cs index 8a93996f..fc8fe4c3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceEnabledComponent.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceEnabledComponent.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderEx.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderEx.cs index 7d52ebf5..86d85fd5 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderEx.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderEx.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderExAccessor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderExAccessor.cs index fc47282a..841e4a54 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderExAccessor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/IServiceProviderExAccessor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/AttributesUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/AttributesUtil.cs index 746d73af..9135f8d0 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/AttributesUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/AttributesUtil.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ public static T GetAttribute(this Type type) where T : Attribute /// The type attributes. public static IEnumerable GetAttributes(this Type type) where T : Attribute { - foreach (T a in type.GetTypeInfo().GetCustomAttributes(typeof(T), false)) + foreach (T a in type.GetCustomAttributes(typeof(T), false)) { yield return a; } @@ -121,7 +121,7 @@ public static T[] GetTypeAttributes(Type type) where T : Attribute public static AttributeUsageAttribute GetAttributeUsage(this Type attributeType) { - var attributes = attributeType.GetTypeInfo().GetCustomAttributes(true).ToArray(); + var attributes = attributeType.GetCustomAttributes(true).ToArray(); return attributes.Length != 0 ? attributes[0] : DefaultAttributeUsage; } @@ -131,7 +131,6 @@ public static AttributeUsageAttribute GetAttributeUsage(this Type attributeType) /// Gets the type converter. /// /// The member. - /// public static Type GetTypeConverter(MemberInfo member) { var attrib = GetAttribute(member); @@ -143,5 +142,5 @@ public static Type GetTypeConverter(MemberInfo member) return null; } - } -} \ No newline at end of file + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/CollectionExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/CollectionExtensions.cs deleted file mode 100644 index b07f68f4..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/CollectionExtensions.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.ComponentModel; - using System.Linq; - - [EditorBrowsable(EditorBrowsableState.Never)] - internal static class CollectionExtensions - { - public static T Find(this T[] items, Predicate predicate) - { - return Array.Find(items, predicate); - } - - public static T[] FindAll(this T[] items, Predicate predicate) - { - return Array.FindAll(items, predicate); - } - - /// - /// Checks whether or not collection is null or empty. Assumes collection can be safely enumerated multiple times. - /// - /// - /// - public static bool IsNullOrEmpty(this IEnumerable @this) - { - return @this == null || @this.GetEnumerator().MoveNext() == false; - } - - /// - /// Generates a HashCode for the contents for the list. Order of items does not matter. - /// - /// The type of object contained within the list. - /// The list. - /// The generated HashCode. - public static int GetContentsHashCode(IList list) - { - if (list == null) - { - return 0; - } - - var result = 0; - for (var i = 0; i < list.Count; i++) - { - if (list[i] != null) - { - // simply add since order does not matter - result += list[i].GetHashCode(); - } - } - - return result; - } - - /// - /// Determines if two lists are equivalent. Equivalent lists have the same number of items and each item is found within the other regardless of respective position within each. - /// - /// The type of object contained within the list. - /// The first list. - /// The second list. - /// True if the two lists are equivalent. - public static bool AreEquivalent(IList listA, IList listB) - { - if (listA == null && listB == null) - { - return true; - } - - if (listA == null || listB == null) - { - return false; - } - - if (listA.Count != listB.Count) - { - return false; - } - - // copy contents to another list so that contents can be removed as they are found, - // in order to consider duplicates - var listBAvailableContents = listB.ToList(); - - // order is not important, just make sure that each entry in A is also found in B - for (var i = 0; i < listA.Count; i++) - { - var found = false; - - for (var j = 0; j < listBAvailableContents.Count; j++) - { - if (Equals(listA[i], listBAvailableContents[j])) - { - found = true; - listBAvailableContents.RemoveAt(j); - break; - } - } - - if (!found) - { - return false; - } - } - - return true; - } - } -} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/ILockHolder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/ILockHolder.cs deleted file mode 100644 index 1203d44d..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/ILockHolder.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - using System; - - internal interface ILockHolder:IDisposable - { - bool LockAcquired { get; } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/IUpgradeableLockHolder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/IUpgradeableLockHolder.cs deleted file mode 100644 index 42a911b1..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/IUpgradeableLockHolder.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - internal interface IUpgradeableLockHolder : ILockHolder - { - ILockHolder Upgrade(); - ILockHolder Upgrade(bool waitForLock); - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InterfaceAttributeUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InterfaceAttributeUtil.cs index c1d18195..8d5764be 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InterfaceAttributeUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InterfaceAttributeUtil.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -45,10 +45,10 @@ private bool IsMostDerivedType public static object[] GetAttributes(Type type, bool inherit) { - if (type.GetTypeInfo().IsInterface == false) - throw new ArgumentOutOfRangeException("type"); + if (type.IsInterface == false) + throw new ArgumentOutOfRangeException(nameof(type)); - var attributes = type.GetTypeInfo().GetCustomAttributes(false).ToArray(); + var attributes = type.GetCustomAttributes(false).ToArray(); var baseTypes = type.GetInterfaces(); if (baseTypes.Length == 0 || !inherit) @@ -91,7 +91,7 @@ private Aged[] CollectTypes(Type derivedType, Type[] baseTypes) private object[] GetAttributes(object[] attributes) { for (index = types.Length - 1; index > 0; index--) - ProcessType(CurrentType.GetTypeInfo().GetCustomAttributes(false).ToArray()); + ProcessType(CurrentType.GetCustomAttributes(false).ToArray()); ProcessType(attributes); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InternalsVisible.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InternalsVisible.cs index b7066fc7..17d21870 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InternalsVisible.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/InternalsVisible.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLockHolder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLockHolder.cs deleted file mode 100644 index dac7d149..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLockHolder.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - using System.Threading; - - internal class MonitorLockHolder : ILockHolder - { - private readonly object locker; - private bool lockAcquired; - - public MonitorLockHolder(object locker, bool waitForLock) - { - this.locker = locker; - if(waitForLock) - { - Monitor.Enter(locker); - lockAcquired = true; - return; - } - - lockAcquired = Monitor.TryEnter(locker, 0); - } - - public void Dispose() - { - if (!LockAcquired) return; - Monitor.Exit(locker); - lockAcquired = false; - } - - public bool LockAcquired - { - get { return lockAcquired; } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpLock.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpLock.cs deleted file mode 100644 index b2360356..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpLock.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - internal class NoOpLock : ILockHolder - { - public static readonly ILockHolder Lock = new NoOpLock(); - - public void Dispose() - { - - } - - public bool LockAcquired - { - get { return true; } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpUpgradeableLock.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpUpgradeableLock.cs deleted file mode 100644 index 490b83f5..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/NoOpUpgradeableLock.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - internal class NoOpUpgradeableLock : IUpgradeableLockHolder - { - public static readonly IUpgradeableLockHolder Lock = new NoOpUpgradeableLock(); - - public void Dispose() - { - - } - - public bool LockAcquired - { - get { return true; } - } - - public ILockHolder Upgrade() - { - return NoOpLock.Lock; - } - - public ILockHolder Upgrade(bool waitForLock) - { - return NoOpLock.Lock; - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/PermissionUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/PermissionUtil.cs deleted file mode 100644 index a2a54f16..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/PermissionUtil.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#if FEATURE_SECURITY_PERMISSIONS - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - using System; - using System.Security; - using System.Security.Permissions; - - internal static class PermissionUtil - { -#if DOTNET40 - [SecuritySafeCritical] -#endif - public static bool IsGranted(this IPermission permission) - { -#if DOTNET35 - return SecurityManager.IsGranted(permission); -#else - var permissionSet = new PermissionSet(PermissionState.None); - permissionSet.AddPermission(permission); - - return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet); -#endif - } - } -} - -#endif \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadLockHolder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadLockHolder.cs deleted file mode 100644 index 7a3cea99..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadLockHolder.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - using System.Threading; - - internal class SlimReadLockHolder : ILockHolder - { - private readonly ReaderWriterLockSlim locker; - private bool lockAcquired; - - public SlimReadLockHolder(ReaderWriterLockSlim locker, bool waitForLock) - { - this.locker = locker; - if(waitForLock) - { - locker.EnterReadLock(); - lockAcquired = true; - return; - } - lockAcquired = locker.TryEnterReadLock(0); - } - - public void Dispose() - { - if (!LockAcquired) return; - locker.ExitReadLock(); - lockAcquired = false; - } - - public bool LockAcquired - { - get { return lockAcquired; } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimWriteLockHolder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimWriteLockHolder.cs deleted file mode 100644 index f36cf5f4..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimWriteLockHolder.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal -{ - using System.Threading; - - internal class SlimWriteLockHolder : ILockHolder - { - private readonly ReaderWriterLockSlim locker; - - private bool lockAcquired; - - public SlimWriteLockHolder(ReaderWriterLockSlim locker, bool waitForLock) - { - this.locker = locker; - if(waitForLock) - { - locker.EnterWriteLock(); - lockAcquired = true; - return; - } - lockAcquired = locker.TryEnterWriteLock(0); - } - - public void Dispose() - { - if(!LockAcquired) return; - locker.ExitWriteLock(); - lockAcquired = false; - } - - public bool LockAcquired - { - get { return lockAcquired; } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SynchronizedDictionary.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SynchronizedDictionary.cs new file mode 100644 index 00000000..81b5dfad --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SynchronizedDictionary.cs @@ -0,0 +1,120 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.Core.Internal +{ + using System; + using System.Collections.Generic; + using System.Threading; + + internal sealed class SynchronizedDictionary : IDisposable + { + private Dictionary items; + private ReaderWriterLockSlim itemsLock; + + public SynchronizedDictionary() + { + items = new Dictionary(); + itemsLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + } + + public void AddOrUpdateWithoutTakingLock(TKey key, TValue value) + { + items[key] = value; + } + + public void Dispose() + { + itemsLock.Dispose(); + } + + public TValue GetOrAdd(TKey key, Func valueFactory) + { + TValue value; + + itemsLock.EnterReadLock(); + try + { + if (items.TryGetValue(key, out value)) + { + return value; + } + } + finally + { + itemsLock.ExitReadLock(); + } + + itemsLock.EnterUpgradeableReadLock(); + try + { + if (items.TryGetValue(key, out value)) + { + return value; + } + else + { + value = valueFactory.Invoke(key); + + itemsLock.EnterWriteLock(); + try + { + items.Add(key, value); + return value; + } + finally + { + itemsLock.ExitWriteLock(); + } + } + } + finally + { + itemsLock.ExitUpgradeableReadLock(); + } + } + + public TValue GetOrAddWithoutTakingLock(TKey key, Func valueFactory) + { + TValue value; + + if (items.TryGetValue(key, out value)) + { + return value; + } + else + { + value = valueFactory.Invoke(key); + items.Add(key, value); + return value; + } + } + + public void ForEach(Action action) + { + itemsLock.EnterReadLock(); + try + { + foreach (var item in items) + { + action.Invoke(item.Key, item.Value); + } + } + finally + { + itemsLock.ExitReadLock(); + } + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/TypeExtensions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/TypeExtensions.cs index 8f054602..2912a4db 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/TypeExtensions.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/TypeExtensions.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2014 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKey.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKey.cs index d2be78d6..74bac0fd 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKey.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKey.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyComparer.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyComparer.cs index 5b6bb589..be7bd6e3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyComparer.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyComparer.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -28,7 +28,7 @@ public static readonly WeakKeyComparer public WeakKeyComparer(IEqualityComparer comparer) { if (comparer == null) - throw new ArgumentNullException("comparer"); + throw new ArgumentNullException(nameof(comparer)); this.comparer = comparer; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyDictionary.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyDictionary.cs index ffb4809a..cd15fcfc 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyDictionary.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/WeakKeyDictionary.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractExtendedLoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractExtendedLoggerFactory.cs index 696d0449..6ef174a3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractExtendedLoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractExtendedLoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,11 +17,7 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging using System; using System.IO; - internal abstract class AbstractExtendedLoggerFactory : -#if FEATURE_REMOTING - MarshalByRefObject, -#endif - IExtendedLoggerFactory + internal abstract class AbstractExtendedLoggerFactory : IExtendedLoggerFactory { /// /// Creates a new extended logger, getting the logger name from the specified type. @@ -30,7 +26,7 @@ public virtual IExtendedLogger Create(Type type) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } return Create(type.FullName); @@ -48,7 +44,7 @@ public virtual IExtendedLogger Create(Type type, LoggerLevel level) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } return Create(type.FullName, level); @@ -95,7 +91,6 @@ ILogger ILoggerFactory.Create(string name, LoggerLevel level) /// Gets the configuration file. /// /// i.e. log4net.config - /// protected static FileInfo GetConfigFile(string fileName) { FileInfo result; @@ -106,15 +101,12 @@ protected static FileInfo GetConfigFile(string fileName) } else { -#if FEATURE_APPDOMAIN string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; -#else - string baseDirectory = AppContext.BaseDirectory; -#endif result = new FileInfo(Path.Combine(baseDirectory, fileName)); } + return result; } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractLoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractLoggerFactory.cs index 0f634da7..879d8c9e 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractLoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/AbstractLoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -20,17 +20,13 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging #if FEATURE_SERIALIZATION [Serializable] #endif - internal abstract class AbstractLoggerFactory : -#if FEATURE_REMOTING - MarshalByRefObject, -#endif - ILoggerFactory + internal abstract class AbstractLoggerFactory : ILoggerFactory { public virtual ILogger Create(Type type) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } return Create(type.FullName); @@ -40,21 +36,20 @@ public virtual ILogger Create(Type type, LoggerLevel level) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } return Create(type.FullName, level); } - public abstract ILogger Create(String name); + public abstract ILogger Create(string name); - public abstract ILogger Create(String name, LoggerLevel level); + public abstract ILogger Create(string name, LoggerLevel level); /// /// Gets the configuration file. /// /// i.e. log4net.config - /// protected static FileInfo GetConfigFile(string fileName) { FileInfo result; @@ -65,11 +60,7 @@ protected static FileInfo GetConfigFile(string fileName) } else { -#if FEATURE_APPDOMAIN string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; -#else - string baseDirectory = AppContext.BaseDirectory; -#endif result = new FileInfo(Path.Combine(baseDirectory, fileName)); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleFactory.cs index dbccdf1f..1e9e30d0 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleFactory.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,11 +19,7 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging #if FEATURE_SERIALIZATION [Serializable] #endif - internal class ConsoleFactory : -#if FEATURE_REMOTING - MarshalByRefObject, -#endif - ILoggerFactory + internal class ConsoleFactory : ILoggerFactory { private LoggerLevel? level; @@ -41,7 +37,7 @@ public ILogger Create(Type type) return Create(type.FullName); } - public ILogger Create(String name) + public ILogger Create(string name) { if (level.HasValue) { @@ -55,7 +51,7 @@ public ILogger Create(Type type, LoggerLevel level) return new ConsoleLogger(type.Name, level); } - public ILogger Create(String name, LoggerLevel level) + public ILogger Create(string name, LoggerLevel level) { return new ConsoleLogger(name, level); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleLogger.cs index b09a5824..2412298d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ConsoleLogger.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,11 +17,11 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging using System; using System.Globalization; - /// - /// The Logger sending everything to the standard output streams. - /// This is mainly for the cases when you have a utility that - /// does not have a logger to supply. - /// + /// + /// The Logger sending everything to the standard output streams. + /// This is mainly for the cases when you have a utility that + /// does not have a logger to supply. + /// #if FEATURE_SERIALIZATION [Serializable] #endif @@ -30,18 +30,18 @@ internal class ConsoleLogger : LevelFilteredLogger /// /// Creates a new ConsoleLogger with the Level /// set to LoggerLevel.Debug and the Name - /// set to String.Empty. + /// set to string.Empty. /// - public ConsoleLogger() : this(String.Empty, LoggerLevel.Debug) + public ConsoleLogger() : this(string.Empty, LoggerLevel.Debug) { } /// /// Creates a new ConsoleLogger with the Name - /// set to String.Empty. + /// set to string.Empty. /// /// The logs Level. - public ConsoleLogger(LoggerLevel logLevel) : this(String.Empty, logLevel) + public ConsoleLogger(LoggerLevel logLevel) : this(string.Empty, logLevel) { } @@ -50,7 +50,7 @@ public ConsoleLogger(LoggerLevel logLevel) : this(String.Empty, logLevel) /// set to LoggerLevel.Debug. /// /// The logs Name. - public ConsoleLogger(String name) : this(name, LoggerLevel.Debug) + public ConsoleLogger(string name) : this(name, LoggerLevel.Debug) { } @@ -59,7 +59,7 @@ public ConsoleLogger(String name) : this(name, LoggerLevel.Debug) /// /// The logs Name. /// The logs Level. - public ConsoleLogger(String name, LoggerLevel logLevel) : base(name, logLevel) + public ConsoleLogger(string name, LoggerLevel logLevel) : base(name, logLevel) { } @@ -70,7 +70,7 @@ public ConsoleLogger(String name, LoggerLevel logLevel) : base(name, logLevel) /// The name of the logger /// The Message /// The Exception - protected override void Log(LoggerLevel loggerLevel, String loggerName, String message, Exception exception) + protected override void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception) { Console.Out.WriteLine("[{0}] '{1}' {2}", loggerLevel, loggerName, message); @@ -91,10 +91,10 @@ public override ILogger CreateChildLogger(string loggerName) { if (loggerName == null) { - throw new ArgumentNullException("loggerName", "To create a child logger you must supply a non null name"); + throw new ArgumentNullException(nameof(loggerName), "To create a child logger you must supply a non null name"); } - return new ConsoleLogger(String.Format(CultureInfo.CurrentCulture, "{0}.{1}", Name, loggerName), Level); + return new ConsoleLogger(string.Format(CultureInfo.CurrentCulture, "{0}.{1}", Name, loggerName), Level); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLogger.cs index 30f97c6d..fd259eea 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2022 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -25,6 +25,9 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging /// #if FEATURE_SERIALIZATION [Serializable] +#endif +#if NET6_0_OR_GREATER + [System.Runtime.Versioning.SupportedOSPlatform("windows")] #endif internal class DiagnosticsLogger : LevelFilteredLogger, IDisposable { @@ -46,7 +49,7 @@ public DiagnosticsLogger(string logName) : this(logName, "default") /// /// /// - public DiagnosticsLogger(string logName, string source) : base(LoggerLevel.Debug) + public DiagnosticsLogger(string logName, string source) : base(LoggerLevel.Trace) { // Create the source, if it does not already exist. if (!EventLog.SourceExists(source)) @@ -109,7 +112,7 @@ protected override void Log(LoggerLevel loggerLevel, string loggerName, string m var type = TranslateLevel(loggerLevel); - String contentToLog; + string contentToLog; if (exception == null) { @@ -147,4 +150,4 @@ private static EventLogEntryType TranslateLevel(LoggerLevel level) } } -#endif \ No newline at end of file +#endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLoggerFactory.cs index 477e4f79..36294b56 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/DiagnosticsLoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2022 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -20,6 +20,9 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging #if FEATURE_SERIALIZATION [Serializable] +#endif +#if NET6_0_OR_GREATER + [System.Runtime.Versioning.SupportedOSPlatform("windows")] #endif internal class DiagnosticsLoggerFactory : AbstractLoggerFactory { @@ -39,4 +42,4 @@ public override ILogger Create(string name, LoggerLevel level) } } -#endif \ No newline at end of file +#endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextProperties.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextProperties.cs index 2a7d1896..66a21a24 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextProperties.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextProperties.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStack.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStack.cs index ad71880f..b9facd85 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStack.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStack.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStacks.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStacks.cs index 674e6c61..023e8d4c 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStacks.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IContextStacks.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLogger.cs index b87d7470..f79815c7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLoggerFactory.cs index 587807d9..d097e5d3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/IExtendedLoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -30,7 +30,7 @@ internal interface IExtendedLoggerFactory : ILoggerFactory /// /// Creates a new extended logger. /// - new IExtendedLogger Create(String name); + new IExtendedLogger Create(string name); /// /// Creates a new extended logger, getting the logger name from the specified type. @@ -40,6 +40,6 @@ internal interface IExtendedLoggerFactory : ILoggerFactory /// /// Creates a new extended logger. /// - new IExtendedLogger Create(String name, LoggerLevel level); + new IExtendedLogger Create(string name, LoggerLevel level); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILogger.cs index bddba008..b182bb1f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -26,6 +26,12 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging /// internal interface ILogger { + /// + /// Determines if messages of priority "trace" will be logged. + /// + /// True if "trace" messages will be logged. + bool IsTraceEnabled { get; } + /// /// Determines if messages of priority "debug" will be logged. /// @@ -63,18 +69,67 @@ internal interface ILogger /// The Subname of this logger. /// The New ILogger instance. /// If the name has an empty element name. - ILogger CreateChildLogger(String loggerName); + ILogger CreateChildLogger(string loggerName); + + /// + /// Logs a trace message. + /// + /// The message to log + void Trace(string message); + + /// + /// Logs a trace message with lazily constructed message. The message will be constructed only if the is true. + /// + void Trace(Func messageFactory); + + /// + /// Logs a trace message. + /// + /// The exception to log + /// The message to log + void Trace(string message, Exception exception); + + /// + /// Logs a trace message. + /// + /// Format string for the message to log + /// Format arguments for the message to log + void TraceFormat(string format, params object[] args); + + /// + /// Logs a trace message. + /// + /// The exception to log + /// Format string for the message to log + /// Format arguments for the message to log + void TraceFormat(Exception exception, string format, params object[] args); + + /// + /// Logs a trace message. + /// + /// The format provider to use + /// Format string for the message to log + /// Format arguments for the message to log + void TraceFormat(IFormatProvider formatProvider, string format, params object[] args); + + /// + /// Logs a trace message. + /// + /// The exception to log + /// The format provider to use + /// Format string for the message to log + /// Format arguments for the message to log + void TraceFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args); /// /// Logs a debug message. /// /// The message to log - void Debug(String message); + void Debug(string message); /// /// Logs a debug message with lazily constructed message. The message will be constructed only if the is true. /// - /// void Debug(Func messageFactory); /// @@ -82,14 +137,14 @@ internal interface ILogger /// /// The exception to log /// The message to log - void Debug(String message, Exception exception); + void Debug(string message, Exception exception); /// /// Logs a debug message. /// /// Format string for the message to log /// Format arguments for the message to log - void DebugFormat(String format, params Object[] args); + void DebugFormat(string format, params object[] args); /// /// Logs a debug message. @@ -97,7 +152,7 @@ internal interface ILogger /// The exception to log /// Format string for the message to log /// Format arguments for the message to log - void DebugFormat(Exception exception, String format, params Object[] args); + void DebugFormat(Exception exception, string format, params object[] args); /// /// Logs a debug message. @@ -105,7 +160,7 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void DebugFormat(IFormatProvider formatProvider, String format, params Object[] args); + void DebugFormat(IFormatProvider formatProvider, string format, params object[] args); /// /// Logs a debug message. @@ -114,18 +169,17 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void DebugFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); + void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args); /// /// Logs an error message. /// /// The message to log - void Error(String message); + void Error(string message); /// /// Logs an error message with lazily constructed message. The message will be constructed only if the is true. /// - /// void Error(Func messageFactory); /// @@ -133,14 +187,14 @@ internal interface ILogger /// /// The exception to log /// The message to log - void Error(String message, Exception exception); + void Error(string message, Exception exception); /// /// Logs an error message. /// /// Format string for the message to log /// Format arguments for the message to log - void ErrorFormat(String format, params Object[] args); + void ErrorFormat(string format, params object[] args); /// /// Logs an error message. @@ -148,7 +202,7 @@ internal interface ILogger /// The exception to log /// Format string for the message to log /// Format arguments for the message to log - void ErrorFormat(Exception exception, String format, params Object[] args); + void ErrorFormat(Exception exception, string format, params object[] args); /// /// Logs an error message. @@ -156,7 +210,7 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void ErrorFormat(IFormatProvider formatProvider, String format, params Object[] args); + void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args); /// /// Logs an error message. @@ -165,18 +219,17 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void ErrorFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); + void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args); /// /// Logs a fatal message. /// /// The message to log - void Fatal(String message); + void Fatal(string message); /// /// Logs a fatal message with lazily constructed message. The message will be constructed only if the is true. /// - /// void Fatal(Func messageFactory); /// @@ -184,14 +237,14 @@ internal interface ILogger /// /// The exception to log /// The message to log - void Fatal(String message, Exception exception); + void Fatal(string message, Exception exception); /// /// Logs a fatal message. /// /// Format string for the message to log /// Format arguments for the message to log - void FatalFormat(String format, params Object[] args); + void FatalFormat(string format, params object[] args); /// /// Logs a fatal message. @@ -199,7 +252,7 @@ internal interface ILogger /// The exception to log /// Format string for the message to log /// Format arguments for the message to log - void FatalFormat(Exception exception, String format, params Object[] args); + void FatalFormat(Exception exception, string format, params object[] args); /// /// Logs a fatal message. @@ -207,7 +260,7 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void FatalFormat(IFormatProvider formatProvider, String format, params Object[] args); + void FatalFormat(IFormatProvider formatProvider, string format, params object[] args); /// /// Logs a fatal message. @@ -216,18 +269,17 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void FatalFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); + void FatalFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args); /// /// Logs an info message. /// /// The message to log - void Info(String message); + void Info(string message); /// /// Logs a info message with lazily constructed message. The message will be constructed only if the is true. /// - /// void Info(Func messageFactory); /// @@ -235,14 +287,14 @@ internal interface ILogger /// /// The exception to log /// The message to log - void Info(String message, Exception exception); + void Info(string message, Exception exception); /// /// Logs an info message. /// /// Format string for the message to log /// Format arguments for the message to log - void InfoFormat(String format, params Object[] args); + void InfoFormat(string format, params object[] args); /// /// Logs an info message. @@ -250,7 +302,7 @@ internal interface ILogger /// The exception to log /// Format string for the message to log /// Format arguments for the message to log - void InfoFormat(Exception exception, String format, params Object[] args); + void InfoFormat(Exception exception, string format, params object[] args); /// /// Logs an info message. @@ -258,7 +310,7 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void InfoFormat(IFormatProvider formatProvider, String format, params Object[] args); + void InfoFormat(IFormatProvider formatProvider, string format, params object[] args); /// /// Logs an info message. @@ -267,18 +319,17 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void InfoFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); + void InfoFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args); /// /// Logs a warn message. /// /// The message to log - void Warn(String message); + void Warn(string message); /// /// Logs a warn message with lazily constructed message. The message will be constructed only if the is true. /// - /// void Warn(Func messageFactory); /// @@ -286,14 +337,14 @@ internal interface ILogger /// /// The exception to log /// The message to log - void Warn(String message, Exception exception); + void Warn(string message, Exception exception); /// /// Logs a warn message. /// /// Format string for the message to log /// Format arguments for the message to log - void WarnFormat(String format, params Object[] args); + void WarnFormat(string format, params object[] args); /// /// Logs a warn message. @@ -301,7 +352,7 @@ internal interface ILogger /// The exception to log /// Format string for the message to log /// Format arguments for the message to log - void WarnFormat(Exception exception, String format, params Object[] args); + void WarnFormat(Exception exception, string format, params object[] args); /// /// Logs a warn message. @@ -309,7 +360,7 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void WarnFormat(IFormatProvider formatProvider, String format, params Object[] args); + void WarnFormat(IFormatProvider formatProvider, string format, params object[] args); /// /// Logs a warn message. @@ -318,6 +369,6 @@ internal interface ILogger /// The format provider to use /// Format string for the message to log /// Format arguments for the message to log - void WarnFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); + void WarnFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILoggerFactory.cs index 457804fc..1cd708e8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/ILoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -29,7 +29,7 @@ internal interface ILoggerFactory /// /// Creates a new logger. /// - ILogger Create(String name); + ILogger Create(string name); /// /// Creates a new logger, getting the logger name from the specified type. @@ -39,6 +39,6 @@ internal interface ILoggerFactory /// /// Creates a new logger. /// - ILogger Create(String name, LoggerLevel level); + ILogger Create(string name, LoggerLevel level); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LevelFilteredLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LevelFilteredLogger.cs index 2bd9c974..265825a7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LevelFilteredLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LevelFilteredLogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,30 +16,19 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging { using System; using System.Globalization; -#if FEATURE_SECURITY_PERMISSIONS -#if DOTNET40 - using System.Security; -#else - using System.Security.Permissions; -#endif -#endif - /// - /// The Level Filtered Logger class. This is a base class which - /// provides a LogLevel attribute and reroutes all functions into - /// one Log method. - /// + /// + /// The Level Filtered Logger class. This is a base class which + /// provides a LogLevel attribute and reroutes all functions into + /// one Log method. + /// #if FEATURE_SERIALIZATION [Serializable] #endif - internal abstract class LevelFilteredLogger : -#if FEATURE_REMOTING - MarshalByRefObject, -#endif - ILogger + internal abstract class LevelFilteredLogger : ILogger { private LoggerLevel level = LoggerLevel.Off; - private String name = "unnamed"; + private string name = "unnamed"; /// /// Creates a new LevelFilteredLogger. @@ -48,7 +37,7 @@ protected LevelFilteredLogger() { } - protected LevelFilteredLogger(String name) + protected LevelFilteredLogger(string name) { ChangeName(name); } @@ -58,29 +47,11 @@ protected LevelFilteredLogger(LoggerLevel loggerLevel) level = loggerLevel; } - protected LevelFilteredLogger(String loggerName, LoggerLevel loggerLevel) : this(loggerLevel) + protected LevelFilteredLogger(string loggerName, LoggerLevel loggerLevel) : this(loggerLevel) { ChangeName(loggerName); } -#if FEATURE_REMOTING - /// - /// Keep the instance alive in a remoting scenario - /// - /// -#if FEATURE_SECURITY_PERMISSIONS -#if DOTNET40 - [SecurityCritical] -#else - [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] -#endif -#endif - public override object InitializeLifetimeService() - { - return null; - } -#endif - public abstract ILogger CreateChildLogger(string loggerName); /// @@ -95,15 +66,112 @@ public LoggerLevel Level /// /// The name that this logger will be using. - /// Defaults to String.Empty + /// Defaults to string.Empty /// - public String Name + public string Name { get { return name; } } #region ILogger implementation + #region Trace + + /// + /// Logs a trace message. + /// + /// The message to log + public void Trace(string message) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, message, null); + } + } + + /// + /// Logs a trace message. + /// + /// A functor to create the message + public void Trace(Func messageFactory) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, messageFactory.Invoke(), null); + } + } + + /// + /// Logs a trace message. + /// + /// The exception to log + /// The message to log + public void Trace(string message, Exception exception) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, message, exception); + } + } + + /// + /// Logs a trace message. + /// + /// Format string for the message to log + /// Format arguments for the message to log + public void TraceFormat(string format, params object[] args) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, string.Format(CultureInfo.CurrentCulture, format, args), null); + } + } + + /// + /// Logs a trace message. + /// + /// The exception to log + /// Format string for the message to log + /// Format arguments for the message to log + public void TraceFormat(Exception exception, string format, params object[] args) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, string.Format(CultureInfo.CurrentCulture, format, args), exception); + } + } + + /// + /// Logs a trace message. + /// + /// The format provider to use + /// Format string for the message to log + /// Format arguments for the message to log + public void TraceFormat(IFormatProvider formatProvider, string format, params object[] args) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, string.Format(formatProvider, format, args), null); + } + } + + /// + /// Logs a trace message. + /// + /// The exception to log + /// The format provider to use + /// Format string for the message to log + /// Format arguments for the message to log + public void TraceFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) + { + if (IsTraceEnabled) + { + Log(LoggerLevel.Trace, string.Format(formatProvider, format, args), exception); + } + } + + #endregion + #region Debug /// @@ -157,7 +225,7 @@ public void DebugFormat(string format, params object[] args) return; } - Log(LoggerLevel.Debug, String.Format(CultureInfo.CurrentCulture, format, args), null); + Log(LoggerLevel.Debug, string.Format(CultureInfo.CurrentCulture, format, args), null); } /// @@ -173,7 +241,7 @@ public void DebugFormat(Exception exception, string format, params object[] args return; } - Log(LoggerLevel.Debug, String.Format(CultureInfo.CurrentCulture, format, args), exception); + Log(LoggerLevel.Debug, string.Format(CultureInfo.CurrentCulture, format, args), exception); } /// @@ -189,7 +257,7 @@ public void DebugFormat(IFormatProvider formatProvider, string format, params ob return; } - Log(LoggerLevel.Debug, String.Format(formatProvider, format, args), null); + Log(LoggerLevel.Debug, string.Format(formatProvider, format, args), null); } /// @@ -206,7 +274,7 @@ public void DebugFormat(Exception exception, IFormatProvider formatProvider, str return; } - Log(LoggerLevel.Debug, String.Format(formatProvider, format, args), exception); + Log(LoggerLevel.Debug, string.Format(formatProvider, format, args), exception); } #endregion @@ -264,7 +332,7 @@ public void InfoFormat(string format, params object[] args) return; } - Log(LoggerLevel.Info, String.Format(CultureInfo.CurrentCulture, format, args), null); + Log(LoggerLevel.Info, string.Format(CultureInfo.CurrentCulture, format, args), null); } /// @@ -280,7 +348,7 @@ public void InfoFormat(Exception exception, string format, params object[] args) return; } - Log(LoggerLevel.Info, String.Format(CultureInfo.CurrentCulture, format, args), exception); + Log(LoggerLevel.Info, string.Format(CultureInfo.CurrentCulture, format, args), exception); } /// @@ -296,7 +364,7 @@ public void InfoFormat(IFormatProvider formatProvider, string format, params obj return; } - Log(LoggerLevel.Info, String.Format(formatProvider, format, args), null); + Log(LoggerLevel.Info, string.Format(formatProvider, format, args), null); } /// @@ -313,7 +381,7 @@ public void InfoFormat(Exception exception, IFormatProvider formatProvider, stri return; } - Log(LoggerLevel.Info, String.Format(formatProvider, format, args), exception); + Log(LoggerLevel.Info, string.Format(formatProvider, format, args), exception); } #endregion @@ -371,7 +439,7 @@ public void WarnFormat(string format, params object[] args) return; } - Log(LoggerLevel.Warn, String.Format(CultureInfo.CurrentCulture, format, args), null); + Log(LoggerLevel.Warn, string.Format(CultureInfo.CurrentCulture, format, args), null); } /// @@ -387,7 +455,7 @@ public void WarnFormat(Exception exception, string format, params object[] args) return; } - Log(LoggerLevel.Warn, String.Format(CultureInfo.CurrentCulture, format, args), exception); + Log(LoggerLevel.Warn, string.Format(CultureInfo.CurrentCulture, format, args), exception); } /// @@ -403,7 +471,7 @@ public void WarnFormat(IFormatProvider formatProvider, string format, params obj return; } - Log(LoggerLevel.Warn, String.Format(formatProvider, format, args), null); + Log(LoggerLevel.Warn, string.Format(formatProvider, format, args), null); } /// @@ -420,7 +488,7 @@ public void WarnFormat(Exception exception, IFormatProvider formatProvider, stri return; } - Log(LoggerLevel.Warn, String.Format(formatProvider, format, args), exception); + Log(LoggerLevel.Warn, string.Format(formatProvider, format, args), exception); } #endregion @@ -478,7 +546,7 @@ public void ErrorFormat(string format, params object[] args) return; } - Log(LoggerLevel.Error, String.Format(CultureInfo.CurrentCulture, format, args), null); + Log(LoggerLevel.Error, string.Format(CultureInfo.CurrentCulture, format, args), null); } /// @@ -494,7 +562,7 @@ public void ErrorFormat(Exception exception, string format, params object[] args return; } - Log(LoggerLevel.Error, String.Format(CultureInfo.CurrentCulture, format, args), exception); + Log(LoggerLevel.Error, string.Format(CultureInfo.CurrentCulture, format, args), exception); } /// @@ -510,7 +578,7 @@ public void ErrorFormat(IFormatProvider formatProvider, string format, params ob return; } - Log(LoggerLevel.Error, String.Format(formatProvider, format, args), null); + Log(LoggerLevel.Error, string.Format(formatProvider, format, args), null); } /// @@ -527,7 +595,7 @@ public void ErrorFormat(Exception exception, IFormatProvider formatProvider, str return; } - Log(LoggerLevel.Error, String.Format(formatProvider, format, args), exception); + Log(LoggerLevel.Error, string.Format(formatProvider, format, args), exception); } #endregion @@ -585,7 +653,7 @@ public void FatalFormat(string format, params object[] args) return; } - Log(LoggerLevel.Fatal, String.Format(CultureInfo.CurrentCulture, format, args), null); + Log(LoggerLevel.Fatal, string.Format(CultureInfo.CurrentCulture, format, args), null); } /// @@ -601,7 +669,7 @@ public void FatalFormat(Exception exception, string format, params object[] args return; } - Log(LoggerLevel.Fatal, String.Format(CultureInfo.CurrentCulture, format, args), exception); + Log(LoggerLevel.Fatal, string.Format(CultureInfo.CurrentCulture, format, args), exception); } /// @@ -617,7 +685,7 @@ public void FatalFormat(IFormatProvider formatProvider, string format, params ob return; } - Log(LoggerLevel.Fatal, String.Format(formatProvider, format, args), null); + Log(LoggerLevel.Fatal, string.Format(formatProvider, format, args), null); } /// @@ -634,11 +702,20 @@ public void FatalFormat(Exception exception, IFormatProvider formatProvider, str return; } - Log(LoggerLevel.Fatal, String.Format(formatProvider, format, args), exception); + Log(LoggerLevel.Fatal, string.Format(formatProvider, format, args), exception); } #endregion + /// + /// Determines if messages of priority "trace" will be logged. + /// + /// true if log level flags include the bit + public bool IsTraceEnabled + { + get { return (Level >= LoggerLevel.Trace); } + } + /// /// Determines if messages of priority "debug" will be logged. /// @@ -690,23 +767,19 @@ public bool IsFatalEnabled /// Implementors output the log content by implementing this method only. /// Note that exception can be null /// - /// - /// - /// - /// - protected abstract void Log(LoggerLevel loggerLevel, String loggerName, String message, Exception exception); + protected abstract void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception); - protected void ChangeName(String newName) + protected void ChangeName(string newName) { if (newName == null) { - throw new ArgumentNullException("newName"); + throw new ArgumentNullException(nameof(newName)); } name = newName; } - private void Log(LoggerLevel loggerLevel, String message, Exception exception) + private void Log(LoggerLevel loggerLevel, string message, Exception exception) { Log(loggerLevel, Name, message, exception); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerException.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerException.cs index e5a4954b..f6c320b7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerException.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerException.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,31 +15,25 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging { using System; -#if FEATURE_SERIALIZATION using System.Runtime.Serialization; -#endif -#if FEATURE_SERIALIZATION [Serializable] -#endif internal class LoggerException : Exception { public LoggerException() { } - public LoggerException(String message) : base(message) + public LoggerException(string message) : base(message) { } - public LoggerException(String message, Exception innerException) : base(message, innerException) + public LoggerException(string message, Exception innerException) : base(message, innerException) { } -#if FEATURE_SERIALIZATION protected LoggerException(SerializationInfo info, StreamingContext context) : base(info, context) { } -#endif } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerLevel.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerLevel.cs index 483aef06..0a5529af 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerLevel.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/LoggerLevel.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -43,5 +43,9 @@ internal enum LoggerLevel /// Debug logging level /// Debug = 5, + /// + /// Trace logging level + /// + Trace = 6 } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogFactory.cs index c71d3dcc..c703d8dc 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,9 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging { using System; - /// - /// NullLogFactory used when logging is turned off. - /// + /// + /// NullLogFactory used when logging is turned off. + /// #if FEATURE_SERIALIZATION [Serializable] #endif @@ -28,8 +28,7 @@ internal class NullLogFactory : AbstractLoggerFactory /// Creates an instance of ILogger with the specified name. /// /// Name. - /// - public override ILogger Create(String name) + public override ILogger Create(string name) { return NullLogger.Instance; } @@ -39,8 +38,7 @@ public override ILogger Create(String name) /// /// Name. /// Level. - /// - public override ILogger Create(String name, LoggerLevel level) + public override ILogger Create(string name, LoggerLevel level) { return NullLogger.Instance; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogger.cs index 437eb23c..f82dc76d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/NullLogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -49,6 +49,15 @@ public IContextStacks ThreadStacks get { return NullContextStacks.Instance; } } + /// + /// No-op. + /// + /// false + public bool IsTraceEnabled + { + get { return false; } + } + /// /// No-op. /// @@ -104,6 +113,67 @@ public ILogger CreateChildLogger(string loggerName) return this; } + /// + /// No-op. + /// + /// Ignored + public void Trace(string message) + { + } + + public void Trace(Func messageFactory) + { + } + + /// + /// No-op. + /// + /// Ignored + /// Ignored + public void Trace(string message, Exception exception) + { + } + + /// + /// No-op. + /// + /// Ignored + /// Ignored + public void TraceFormat(string format, params object[] args) + { + } + + /// + /// No-op. + /// + /// Ignored + /// Ignored + /// Ignored + public void TraceFormat(Exception exception, string format, params object[] args) + { + } + + /// + /// No-op. + /// + /// Ignored + /// Ignored + /// Ignored + public void TraceFormat(IFormatProvider formatProvider, string format, params object[] args) + { + } + + /// + /// No-op. + /// + /// Ignored + /// Ignored + /// Ignored + /// Ignored + public void TraceFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) + { + } + /// /// No-op. /// diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLogger.cs index 2b54ae84..041bd6ea 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,14 +18,14 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging using System.IO; using System.Text; - /// - /// The Stream Logger class. This class can stream log information - /// to any stream, it is suitable for storing a log file to disk, - /// or to a MemoryStream for testing your components. - /// - /// - /// This logger is not thread safe. - /// + /// + /// The Stream Logger class. This class can stream log information + /// to any stream, it is suitable for storing a log file to disk, + /// or to a MemoryStream for testing your components. + /// + /// + /// This logger is not thread safe. + /// #if FEATURE_SERIALIZATION [Serializable] #endif @@ -44,7 +44,7 @@ internal class StreamLogger : LevelFilteredLogger, IDisposable /// The stream that will be used for logging, /// seeking while the logger is alive /// - public StreamLogger(String name, Stream stream) : this(name, new StreamWriter(stream)) + public StreamLogger(string name, Stream stream) : this(name, new StreamWriter(stream)) { } @@ -63,7 +63,7 @@ internal class StreamLogger : LevelFilteredLogger, IDisposable /// The encoding that will be used for this stream. /// /// - public StreamLogger(String name, Stream stream, Encoding encoding) : this(name, new StreamWriter(stream, encoding)) + public StreamLogger(string name, Stream stream, Encoding encoding) : this(name, new StreamWriter(stream, encoding)) { } @@ -86,7 +86,7 @@ internal class StreamLogger : LevelFilteredLogger, IDisposable /// The buffer size that will be used for this stream. /// /// - public StreamLogger(String name, Stream stream, Encoding encoding, int bufferSize) + public StreamLogger(string name, Stream stream, Encoding encoding, int bufferSize) : this(name, new StreamWriter(stream, encoding, bufferSize)) { } @@ -124,13 +124,13 @@ protected virtual void Dispose(bool disposing) /// /// The name of the log. /// The StreamWriter the log will write to. - protected StreamLogger(String name, StreamWriter writer) : base(name, LoggerLevel.Debug) + protected StreamLogger(string name, StreamWriter writer) : base(name, LoggerLevel.Trace) { this.writer = writer; writer.AutoFlush = true; } - protected override void Log(LoggerLevel loggerLevel, String loggerName, String message, Exception exception) + protected override void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception) { if (writer == null) { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLoggerFactory.cs index 3c089334..a0d7304a 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/StreamLoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,11 +18,11 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging using System.IO; using System.Text; - /// - /// Creates outputting - /// to files. The name of the file is derived from the log name - /// plus the 'log' extension. - /// + /// + /// Creates outputting + /// to files. The name of the file is derived from the log name + /// plus the 'log' extension. + /// #if FEATURE_SERIALIZATION [Serializable] #endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLogger.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLogger.cs index 2aeb2132..aee1d70e 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLogger.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLogger.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,27 +17,24 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging using System; using System.Diagnostics; using System.Collections.Generic; -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - using System.Security; -#endif - - /// - /// The TraceLogger sends all logging to the System.Diagnostics.TraceSource - /// built into the .net framework. - /// - /// - /// Logging can be configured in the system.diagnostics configuration - /// section. - /// - /// If logger doesn't find a source name with a full match it will - /// use source names which match the namespace partially. For example you can - /// configure from all castle components by adding a source name with the - /// name "Castle". - /// - /// If no portion of the namespace matches the source named "Default" will - /// be used. - /// - internal class TraceLogger : LevelFilteredLogger + + /// + /// The TraceLogger sends all logging to the System.Diagnostics.TraceSource + /// built into the .net framework. + /// + /// + /// Logging can be configured in the system.diagnostics configuration + /// section. + /// + /// If logger doesn't find a source name with a full match it will + /// use source names which match the namespace partially. For example you can + /// configure from all castle components by adding a source name with the + /// name "Castle". + /// + /// If no portion of the namespace matches the source named "Default" will + /// be used. + /// + internal class TraceLogger : LevelFilteredLogger { private static readonly Dictionary cache = new Dictionary(); @@ -47,9 +44,6 @@ internal class TraceLogger : LevelFilteredLogger /// Build a new trace logger based on the named TraceSource /// /// The name used to locate the best TraceSource. In most cases comes from the using type's fullname. -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public TraceLogger(string name) : base(name) { @@ -63,9 +57,6 @@ public TraceLogger(string name) /// The name used to locate the best TraceSource. In most cases comes from the using type's fullname. /// The default logging level at which this source should write messages. In almost all cases this /// default value will be overridden in the config file. -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public TraceLogger(string name, LoggerLevel level) : base(name, level) { @@ -79,17 +70,11 @@ public TraceLogger(string name, LoggerLevel level) /// /// The Subname of this logger. /// The New ILogger instance. -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public override ILogger CreateChildLogger(string loggerName) { return InternalCreateChildLogger(loggerName); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private ILogger InternalCreateChildLogger(string loggerName) { return new TraceLogger(string.Concat(Name, ".", loggerName), Level); @@ -107,9 +92,6 @@ protected override void Log(LoggerLevel loggerLevel, string loggerName, string m } } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private void Initialize() { lock (cache) @@ -172,9 +154,6 @@ private static string ShortenName(string name) return null; } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif private static bool IsSourceConfigured(TraceSource source) { if (source.Listeners.Count == 1 && @@ -191,7 +170,7 @@ private static LoggerLevel MapLoggerLevel(SourceLevels level) switch (level) { case SourceLevels.All: - return LoggerLevel.Debug; + return LoggerLevel.Trace; case SourceLevels.Verbose: return LoggerLevel.Debug; case SourceLevels.Information: @@ -210,6 +189,8 @@ private static SourceLevels MapSourceLevels(LoggerLevel level) { switch (level) { + case LoggerLevel.Trace: + return SourceLevels.All; case LoggerLevel.Debug: return SourceLevels.Verbose; case LoggerLevel.Info: @@ -228,6 +209,7 @@ private static TraceEventType MapTraceEventType(LoggerLevel level) { switch (level) { + case LoggerLevel.Trace: case LoggerLevel.Debug: return TraceEventType.Verbose; case LoggerLevel.Info: diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLoggerFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLoggerFactory.cs index aa1eaf53..46d52e52 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLoggerFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Logging/TraceLoggerFactory.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,10 +14,6 @@ namespace Telerik.JustMock.Core.Castle.Core.Logging { -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - using System.Security; -#endif - /// /// Used to create the TraceLogger implementation of ILogger interface. See . /// @@ -34,9 +30,6 @@ public TraceLoggerFactory(LoggerLevel level) this.level = level; } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public override ILogger Create(string name) { if (level.HasValue) @@ -46,25 +39,16 @@ public override ILogger Create(string name) return InternalCreate(name); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private ILogger InternalCreate(string name) { return new TraceLogger(name); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public override ILogger Create(string name, LoggerLevel level) { return InternalCreate(name, level); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private ILogger InternalCreate(string name, LoggerLevel level) { return new TraceLogger(name, level); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Pair.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Pair.cs deleted file mode 100644 index 444adb64..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Pair.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core -{ - using System; - - /// - /// General purpose class to represent a standard pair of values. - /// - /// Type of the first value - /// Type of the second value - internal class Pair : IEquatable> - { - private readonly TFirst first; - private readonly TSecond second; - - /// - /// Constructs a pair with its values - /// - /// - /// - public Pair(TFirst first, TSecond second) - { - this.first = first; - this.second = second; - } - - public TFirst First - { - get { return first; } - } - - public TSecond Second - { - get { return second; } - } - - public override string ToString() - { - return first + " " + second; - } - - public bool Equals(Pair other) - { - if (other == null) - { - return false; - } - return Equals(first, other.first) && Equals(second, other.second); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(this, obj)) - { - return true; - } - return Equals(obj as Pair); - } - - public override int GetHashCode() - { - return first.GetHashCode() + 29 * second.GetHashCode(); - } - } -} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ProxyServices.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ProxyServices.cs index 7b0ae60a..7775bb01 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ProxyServices.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ProxyServices.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,10 +17,10 @@ namespace Telerik.JustMock.Core.Castle.Core using System; using System.Reflection; - /// - /// List of utility methods related to dynamic proxy operations - /// - internal static class ProxyServices + /// + /// List of utility methods related to dynamic proxy operations + /// + internal static class ProxyServices { /// /// Determines whether the specified type is a proxy generated by @@ -32,7 +32,7 @@ internal static class ProxyServices /// public static bool IsDynamicProxy(Type type) { - string assemblyName = type.GetTypeInfo().Assembly.FullName; + string assemblyName = type.Assembly.FullName; return (assemblyName.StartsWith("DynamicAssemblyProxyGen", StringComparison.Ordinal) || assemblyName.StartsWith("DynamicProxyGenAssembly2", StringComparison.Ordinal)); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReferenceEqualityComparer.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReferenceEqualityComparer.cs index 7f109cc3..5edd6b9d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReferenceEqualityComparer.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReferenceEqualityComparer.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +22,7 @@ namespace Telerik.JustMock.Core.Castle.Core #if FEATURE_SERIALIZATION [Serializable] #endif - internal class ReferenceEqualityComparer : IEqualityComparer, IEqualityComparer + internal class ReferenceEqualityComparer : IEqualityComparer, IEqualityComparer { private static readonly ReferenceEqualityComparer instance = new ReferenceEqualityComparer(); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReflectionBasedDictionaryAdapter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReflectionBasedDictionaryAdapter.cs index d194047f..1481c014 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReflectionBasedDictionaryAdapter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/ReflectionBasedDictionaryAdapter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -20,10 +20,10 @@ namespace Telerik.JustMock.Core.Castle.Core using System.Linq; using System.Reflection; - /// - /// Readonly implementation of which uses an anonymous object as its source. Uses names of properties as keys, and property values as... well - values. Keys are not case sensitive. - /// - internal sealed class ReflectionBasedDictionaryAdapter : IDictionary + /// + /// Readonly implementation of which uses an anonymous object as its source. Uses names of properties as keys, and property values as... well - values. Keys are not case sensitive. + /// + internal sealed class ReflectionBasedDictionaryAdapter : IDictionary { private readonly Dictionary properties = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -36,7 +36,7 @@ public ReflectionBasedDictionaryAdapter(object target) { if (target == null) { - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); } Read(properties, target); } @@ -44,7 +44,6 @@ public ReflectionBasedDictionaryAdapter(object target) /// /// Gets the number of elements contained in the . /// - /// /// The number of elements contained in the . public int Count { @@ -54,7 +53,6 @@ public int Count /// /// Gets a value indicating whether access to the is synchronized (thread safe). /// - /// /// true if access to the is synchronized (thread safe); otherwise, false. public bool IsSynchronized { @@ -64,7 +62,6 @@ public bool IsSynchronized /// /// Gets an object that can be used to synchronize access to the . /// - /// /// An object that can be used to synchronize access to the . public object SyncRoot { @@ -74,7 +71,6 @@ public object SyncRoot /// /// Gets a value indicating whether the object is read-only. /// - /// /// true if the object is read-only; otherwise, false. public bool IsReadOnly { @@ -84,7 +80,6 @@ public bool IsReadOnly /// /// Gets or sets the with the specified key. /// - /// public object this[object key] { get @@ -100,7 +95,6 @@ public object this[object key] /// Gets an object containing the keys of the object. /// - /// /// An object containing the keys of the object. public ICollection Keys @@ -112,7 +106,6 @@ public ICollection Keys /// Gets an object containing the values in the object. /// - /// /// An object containing the values in the object. public ICollection Values @@ -123,7 +116,6 @@ public ICollection Values /// /// Gets a value indicating whether the object has a fixed size. /// - /// /// true if the object has a fixed size; otherwise, false. bool IDictionary.IsFixedSize { @@ -231,8 +223,6 @@ IDictionaryEnumerator IDictionary.GetEnumerator() /// Reads values of properties from and inserts them into using property names as keys. /// - /// - /// public static void Read(IDictionary targetDictionary, object valuesAsAnonymousObject) { var targetType = valuesAsAnonymousObject.GetType(); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractResource.cs index b74685ab..cf362428 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ public virtual string FileBasePath public abstract TextReader GetStreamReader(Encoding encoding); - public abstract IResource CreateRelative(String relativePath); + public abstract IResource CreateRelative(string relativePath); public void Dispose() { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractStreamResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractStreamResource.cs index 1bb38d0d..399907ab 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractStreamResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AbstractStreamResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource using System.IO; using System.Text; - internal delegate Stream StreamFactory(); + internal delegate Stream StreamFactory(); - /// - /// - /// - internal abstract class AbstractStreamResource : AbstractResource + /// + /// + /// + internal abstract class AbstractStreamResource : AbstractResource { /// /// This returns a new stream instance each time it is called. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyBundleResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyBundleResource.cs index 116088ba..023ec059 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyBundleResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyBundleResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource using System.Resources; using System.Text; - internal class AssemblyBundleResource : AbstractResource + internal class AssemblyBundleResource : AbstractResource { private readonly CustomUri resource; @@ -60,15 +60,11 @@ private static Assembly ObtainAssembly(string assemblyName) { try { -#if FEATURE_GAC - return Assembly.Load(assemblyName); -#else return Assembly.Load(new AssemblyName(assemblyName)); -#endif } catch (Exception ex) { - var message = String.Format(CultureInfo.InvariantCulture, "The assembly {0} could not be loaded", assemblyName); + var message = string.Format(CultureInfo.InvariantCulture, "The assembly {0} could not be loaded", assemblyName); throw new ResourceException(message, ex); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResource.cs index 08ccfc04..6e2add59 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource using System.IO; using System.Reflection; - internal class AssemblyResource : AbstractStreamResource + internal class AssemblyResource : AbstractStreamResource { private string assemblyName; private string resourcePath; - private String basePath; + private string basePath; public AssemblyResource(CustomUri resource) { @@ -33,7 +33,7 @@ public AssemblyResource(CustomUri resource) }; } - public AssemblyResource(CustomUri resource, String basePath) + public AssemblyResource(CustomUri resource, string basePath) { CreateStream = delegate { @@ -41,7 +41,7 @@ public AssemblyResource(CustomUri resource, String basePath) }; } - public AssemblyResource(String resource) + public AssemblyResource(string resource) { CreateStream = delegate { @@ -49,17 +49,17 @@ public AssemblyResource(String resource) }; } - public override IResource CreateRelative(String relativePath) + public override IResource CreateRelative(string relativePath) { throw new NotImplementedException(); } public override string ToString() { - return String.Format(CultureInfo.CurrentCulture, "AssemblyResource: [{0}] [{1}]", assemblyName, resourcePath); + return string.Format(CultureInfo.CurrentCulture, "AssemblyResource: [{0}] [{1}]", assemblyName, resourcePath); } - private Stream CreateResourceFromPath(String resource, String path) + private Stream CreateResourceFromPath(string resource, string path) { if (!resource.StartsWith("assembly" + CustomUri.SchemeDelimiter, StringComparison.CurrentCulture)) { @@ -69,18 +69,18 @@ private Stream CreateResourceFromPath(String resource, String path) return CreateResourceFromUri(new CustomUri(resource), path); } - private Stream CreateResourceFromUri(CustomUri resourcex, String path) + private Stream CreateResourceFromUri(CustomUri resourcex, string path) { - if (resourcex == null) throw new ArgumentNullException("resourcex"); + if (resourcex == null) throw new ArgumentNullException(nameof(resourcex)); assemblyName = resourcex.Host; resourcePath = ConvertToResourceName(assemblyName, resourcex.Path); Assembly assembly = ObtainAssembly(assemblyName); - String[] names = assembly.GetManifestResourceNames(); + string[] names = assembly.GetManifestResourceNames(); - String nameFound = GetNameFound(names); + string nameFound = GetNameFound(names); if (nameFound == null) { @@ -90,7 +90,7 @@ private Stream CreateResourceFromUri(CustomUri resourcex, String path) if (nameFound == null) { - String message = String.Format(CultureInfo.InvariantCulture, "The assembly resource {0} could not be located", resourcePath); + string message = string.Format(CultureInfo.InvariantCulture, "The assembly resource {0} could not be located", resourcePath); throw new ResourceException(message); } @@ -102,9 +102,9 @@ private Stream CreateResourceFromUri(CustomUri resourcex, String path) private string GetNameFound(string[] names) { string nameFound = null; - foreach(String name in names) + foreach(string name in names) { - if (String.Compare(resourcePath, name, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Compare(resourcePath, name, StringComparison.OrdinalIgnoreCase) == 0) { nameFound = name; break; @@ -113,11 +113,11 @@ private string GetNameFound(string[] names) return nameFound; } - private string ConvertToResourceName(String assembly, String resource) + private string ConvertToResourceName(string assembly, string resource) { assembly = GetSimpleName(assembly); // TODO: use path for relative name construction - return String.Format(CultureInfo.CurrentCulture, "{0}{1}", assembly, resource.Replace('/', '.')); + return string.Format(CultureInfo.CurrentCulture, "{0}{1}", assembly, resource.Replace('/', '.')); } private string GetSimpleName(string assembly) @@ -130,7 +130,7 @@ private string GetSimpleName(string assembly) return assembly.Substring(0, indexOfComma); } - private string ConvertToPath(String resource) + private string ConvertToPath(string resource) { string path = resource.Replace('.', '/'); if (path[0] != '/') @@ -140,19 +140,15 @@ private string ConvertToPath(String resource) return path; } - private static Assembly ObtainAssembly(String assemblyName) + private static Assembly ObtainAssembly(string assemblyName) { try { -#if FEATURE_GAC - return Assembly.Load(assemblyName); -#else return Assembly.Load(new AssemblyName(assemblyName)); -#endif } catch (Exception ex) { - String message = String.Format(CultureInfo.InvariantCulture, "The assembly {0} could not be loaded", assemblyName); + string message = string.Format(CultureInfo.InvariantCulture, "The assembly {0} could not be loaded", assemblyName); throw new ResourceException(message, ex); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResourceFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResourceFactory.cs index 52cfd467..51c42ba0 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResourceFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/AssemblyResourceFactory.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource { using System; - internal class AssemblyResourceFactory : IResourceFactory + internal class AssemblyResourceFactory : IResourceFactory { public bool Accept(CustomUri uri) { @@ -28,7 +28,7 @@ public IResource Create(CustomUri uri) return Create(uri, null); } - public IResource Create(CustomUri uri, String basePath) + public IResource Create(CustomUri uri, string basePath) { if (basePath == null) { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResource.cs index a09c8a8d..71fb2401 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ public ConfigResource(CustomUri uri) : this(uri.Host) { } - public ConfigResource(String sectionName) + public ConfigResource(string sectionName) { this.sectionName = sectionName; @@ -44,7 +44,7 @@ public ConfigResource(String sectionName) if (node == null) { - String message = String.Format(CultureInfo.InvariantCulture, + string message = string.Format(CultureInfo.InvariantCulture, "Could not find section '{0}' in the configuration file associated with this domain.", sectionName); throw new ConfigurationErrorsException(message); } @@ -63,14 +63,14 @@ public override TextReader GetStreamReader(Encoding encoding) throw new NotSupportedException("Encoding is not supported"); } - public override IResource CreateRelative(String relativePath) + public override IResource CreateRelative(string relativePath) { return new ConfigResource(relativePath); } public override string ToString() { - return String.Format(CultureInfo.CurrentCulture, "ConfigResource: [{0}]", sectionName); + return string.Format(CultureInfo.CurrentCulture, "ConfigResource: [{0}]", sectionName); } } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResourceFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResourceFactory.cs index 1d09cd39..554ee91c 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResourceFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ConfigResourceFactory.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ public IResource Create(CustomUri uri) return new ConfigResource(uri); } - public IResource Create(CustomUri uri, String basePath) + public IResource Create(CustomUri uri, string basePath) { return Create(uri); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/CustomUri.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/CustomUri.cs index c566d7c5..599191e5 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/CustomUri.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/CustomUri.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,28 +20,28 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource #if FEATURE_SERIALIZATION [Serializable] #endif - internal sealed class CustomUri + internal sealed class CustomUri { - public static readonly String SchemeDelimiter = "://"; - public static readonly String UriSchemeFile = "file"; - public static readonly String UriSchemeAssembly = "assembly"; + public static readonly string SchemeDelimiter = "://"; + public static readonly string UriSchemeFile = "file"; + public static readonly string UriSchemeAssembly = "assembly"; - private String scheme; - private String host; - private String path; + private string scheme; + private string host; + private string path; private bool isUnc; private bool isFile; private bool isAssembly; - public CustomUri(String resourceIdentifier) + public CustomUri(string resourceIdentifier) { if (resourceIdentifier == null) { - throw new ArgumentNullException("resourceIdentifier"); + throw new ArgumentNullException(nameof(resourceIdentifier)); } - if (resourceIdentifier == String.Empty) + if (resourceIdentifier == string.Empty) { - throw new ArgumentException("Empty resource identifier is not allowed", "resourceIdentifier"); + throw new ArgumentException("Empty resource identifier is not allowed", nameof(resourceIdentifier)); } ParseIdentifier(resourceIdentifier); @@ -72,12 +72,12 @@ public string Host get { return host; } } - public String Path + public string Path { get { return path; } } - private void ParseIdentifier(String identifier) + private void ParseIdentifier(string identifier) { int comma = identifier.IndexOf(':'); @@ -136,4 +136,4 @@ private void ParseIdentifier(String identifier) path = Environment.ExpandEnvironmentVariables(sb.ToString()); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResource.cs index 2c5e7f83..d91b6e30 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,13 +18,13 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource using System.Globalization; using System.IO; - /// - /// - /// - internal class FileResource : AbstractStreamResource + /// + /// + /// + internal class FileResource : AbstractStreamResource { private string filePath; - private String basePath; + private string basePath; public FileResource(CustomUri resource) { @@ -34,7 +34,7 @@ public FileResource(CustomUri resource) }; } - public FileResource(CustomUri resource, String basePath) + public FileResource(CustomUri resource, string basePath) { CreateStream = delegate { @@ -42,7 +42,7 @@ public FileResource(CustomUri resource, String basePath) }; } - public FileResource(String resourceName) + public FileResource(string resourceName) { CreateStream = delegate { @@ -50,7 +50,7 @@ public FileResource(String resourceName) }; } - public FileResource(String resourceName, String basePath) + public FileResource(string resourceName, string basePath) { CreateStream = delegate { @@ -60,36 +60,36 @@ public FileResource(String resourceName, String basePath) public override string ToString() { - return String.Format(CultureInfo.CurrentCulture, "FileResource: [{0}] [{1}]", filePath, basePath); + return string.Format(CultureInfo.CurrentCulture, "FileResource: [{0}] [{1}]", filePath, basePath); } - public override String FileBasePath + public override string FileBasePath { get { return basePath; } } - public override IResource CreateRelative(String relativePath) + public override IResource CreateRelative(string relativePath) { return new FileResource(relativePath, basePath); } - private Stream CreateStreamFromUri(CustomUri resource, String rootPath) + private Stream CreateStreamFromUri(CustomUri resource, string rootPath) { - if (resource == null) throw new ArgumentNullException("resource"); - if (rootPath == null) throw new ArgumentNullException("rootPath"); + if (resource == null) throw new ArgumentNullException(nameof(resource)); + if (rootPath == null) throw new ArgumentNullException(nameof(rootPath)); if (!resource.IsFile) - throw new ArgumentException("The specified resource is not a file", "resource"); + throw new ArgumentException("The specified resource is not a file", nameof(resource)); return CreateStreamFromPath(resource.Path, rootPath); } - private Stream CreateStreamFromPath(String resourcePath, String rootPath) + private Stream CreateStreamFromPath(string resourcePath, string rootPath) { if (resourcePath == null) - throw new ArgumentNullException("resourcePath"); + throw new ArgumentNullException(nameof(resourcePath)); if (rootPath == null) - throw new ArgumentNullException("rootPath"); + throw new ArgumentNullException(nameof(rootPath)); if (!Path.IsPathRooted(resourcePath) || !File.Exists(resourcePath)) { @@ -107,11 +107,11 @@ private Stream CreateStreamFromPath(String resourcePath, String rootPath) return File.OpenRead(resourcePath); } - private static void CheckFileExists(String path) + private static void CheckFileExists(string path) { if (!File.Exists(path)) { - String message = String.Format(CultureInfo.InvariantCulture, "File {0} could not be found", new FileInfo(path).FullName); + string message = string.Format(CultureInfo.InvariantCulture, "File {0} could not be found", new FileInfo(path).FullName); throw new ResourceException(message); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResourceFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResourceFactory.cs index a1155571..ae0ec607 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResourceFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/FileResourceFactory.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource { using System; - /// - /// - /// - internal class FileResourceFactory : IResourceFactory + /// + /// + /// + internal class FileResourceFactory : IResourceFactory { public FileResourceFactory() { @@ -35,7 +35,7 @@ public IResource Create(CustomUri uri) return Create(uri, null); } - public IResource Create(CustomUri uri, String basePath) + public IResource Create(CustomUri uri, string basePath) { if (basePath != null) return new FileResource(uri, basePath); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResource.cs index bfa8a332..25868a7b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,20 +18,17 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource using System.IO; using System.Text; - /// - /// Represents a 'streamable' resource. Can - /// be a file, a resource in an assembly. - /// - internal interface IResource : IDisposable + /// + /// Represents a 'streamable' resource. Can + /// be a file, a resource in an assembly. + /// + internal interface IResource : IDisposable { - /// - /// - /// /// /// Only valid for resources that /// can be obtained through relative paths /// - String FileBasePath { get; } + string FileBasePath { get; } /// /// Returns a reader for the stream @@ -39,7 +36,6 @@ internal interface IResource : IDisposable /// /// It's up to the caller to dispose the reader. /// - /// TextReader GetStreamReader(); /// @@ -48,8 +44,6 @@ internal interface IResource : IDisposable /// /// It's up to the caller to dispose the reader. /// - /// - /// TextReader GetStreamReader(Encoding encoding); /// @@ -57,8 +51,6 @@ internal interface IResource : IDisposable /// created according to the relativePath /// using itself as the root. /// - /// - /// - IResource CreateRelative(String relativePath); + IResource CreateRelative(string relativePath); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResourceFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResourceFactory.cs index 4e0264c1..e180feb8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResourceFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/IResourceFactory.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,10 +16,10 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource { using System; - /// - /// Depicts the contract for resource factories. - /// - internal interface IResourceFactory + /// + /// Depicts the contract for resource factories. + /// + internal interface IResourceFactory { /// /// Used to check whether the resource factory @@ -31,25 +31,18 @@ internal interface IResourceFactory /// only if the given identifier is supported /// by the resource factory /// - /// - /// bool Accept(CustomUri uri); /// /// Creates an instance /// for the given resource identifier /// - /// - /// IResource Create(CustomUri uri); /// /// Creates an instance /// for the given resource identifier /// - /// - /// - /// - IResource Create(CustomUri uri, String basePath); + IResource Create(CustomUri uri, string basePath); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ResourceException.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ResourceException.cs index 9fb4621f..e38c9206 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ResourceException.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/ResourceException.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,14 +15,10 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource { using System; -#if FEATURE_SERIALIZATION using System.Runtime.Serialization; -#endif -#if FEATURE_SERIALIZATION [Serializable] -#endif - internal class ResourceException : Exception + internal class ResourceException : Exception { public ResourceException() { @@ -35,10 +31,10 @@ public ResourceException(string message) : base(message) public ResourceException(string message, Exception innerException) : base(message, innerException) { } -#if FEATURE_SERIALIZATION + protected ResourceException(SerializationInfo info, StreamingContext context) : base(info, context) { } -#endif + } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/StaticContentResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/StaticContentResource.cs index b52922a8..d72f4c18 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/StaticContentResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/StaticContentResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,14 +18,14 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource using System.IO; using System.Text; - /// - /// Adapts a static string content as an - /// - internal class StaticContentResource : AbstractResource + /// + /// Adapts a static string content as an + /// + internal class StaticContentResource : AbstractResource { private readonly string contents; - public StaticContentResource(String contents) + public StaticContentResource(string contents) { this.contents = contents; } @@ -40,7 +40,7 @@ public override TextReader GetStreamReader(Encoding encoding) throw new NotImplementedException(); } - public override IResource CreateRelative(String relativePath) + public override IResource CreateRelative(string relativePath) { throw new NotImplementedException(); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResource.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResource.cs index 34fff2b6..7c0b259d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResource.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResource.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ namespace Telerik.JustMock.Core.Castle.Core.Resource /// Enable access to files on network shares /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unc")] - internal class UncResource : AbstractStreamResource + internal class UncResource : AbstractStreamResource { private string basePath; private string filePath; @@ -35,7 +35,7 @@ public UncResource(CustomUri resource) }; } - public UncResource(CustomUri resource, String basePath) + public UncResource(CustomUri resource, string basePath) { CreateStream = delegate { @@ -43,39 +43,39 @@ public UncResource(CustomUri resource, String basePath) }; } - public UncResource(String resourceName) : this(new CustomUri(resourceName)) + public UncResource(string resourceName) : this(new CustomUri(resourceName)) { } - public UncResource(String resourceName, String basePath) : this(new CustomUri(resourceName), basePath) + public UncResource(string resourceName, string basePath) : this(new CustomUri(resourceName), basePath) { } - public override String FileBasePath + public override string FileBasePath { get { return basePath; } } - public override IResource CreateRelative(String relativePath) + public override IResource CreateRelative(string relativePath) { return new UncResource(Path.Combine(basePath, relativePath)); } public override string ToString() { - return String.Format(CultureInfo.CurrentCulture, "UncResource: [{0}] [{1}]", filePath, basePath); + return string.Format(CultureInfo.CurrentCulture, "UncResource: [{0}] [{1}]", filePath, basePath); } - private Stream CreateStreamFromUri(CustomUri resource, String rootPath) + private Stream CreateStreamFromUri(CustomUri resource, string rootPath) { if (resource == null) - throw new ArgumentNullException("resource"); + throw new ArgumentNullException(nameof(resource)); if (!resource.IsUnc) - throw new ArgumentException("Resource must be an Unc", "resource"); + throw new ArgumentException("Resource must be an Unc", nameof(resource)); if (!resource.IsFile) - throw new ArgumentException("The specified resource is not a file", "resource"); + throw new ArgumentException("The specified resource is not a file", nameof(resource)); - String resourcePath = resource.Path; + string resourcePath = resource.Path; if (!File.Exists(resourcePath) && rootPath != null) { @@ -90,11 +90,11 @@ private Stream CreateStreamFromUri(CustomUri resource, String rootPath) return File.OpenRead(resourcePath); } - private static void CheckFileExists(String path) + private static void CheckFileExists(string path) { if (!File.Exists(path)) { - String message = String.Format(CultureInfo.InvariantCulture, "File {0} could not be found", path); + string message = string.Format(CultureInfo.InvariantCulture, "File {0} could not be found", path); throw new ResourceException(message); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResourceFactory.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResourceFactory.cs index b4a9d4b3..c4cf20f3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResourceFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Resource/UncResourceFactory.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ public IResource Create(CustomUri uri) return new UncResource(uri); } - public IResource Create(CustomUri uri, String basePath) + public IResource Create(CustomUri uri, string basePath) { return new UncResource(uri, basePath); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/DefaultSmtpSender.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/DefaultSmtpSender.cs index c5e85b07..79edb211 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/DefaultSmtpSender.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/DefaultSmtpSender.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2017 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -39,14 +39,13 @@ internal class DefaultSmtpSender : IEmailSender private int port = 25; private int? timeout; private bool useSsl; - private readonly NetworkCredential credentials = new NetworkCredential(); /// /// Initializes a new instance of the class based on the configuration provided in the application configuration file. /// /// /// This constructor is based on the default configuration in the application configuration file. - /// + /// public DefaultSmtpSender() { } /// @@ -60,7 +59,7 @@ public DefaultSmtpSender(string hostname) } /// - /// Gets or sets the port used to + /// Gets or sets the port used to /// access the SMTP server /// public int Port @@ -79,7 +78,7 @@ public string Hostname } /// - /// Gets or sets a value which is used to + /// Gets or sets a value which is used to /// configure if emails are going to be sent asynchronously or not. /// public bool AsyncSend @@ -89,7 +88,7 @@ public bool AsyncSend } /// - /// Gets or sets a value that specifies + /// Gets or sets a value that specifies /// the amount of time after which a synchronous Send call times out. /// public int Timeout @@ -99,7 +98,7 @@ public int Timeout } /// - /// Gets or sets a value indicating whether the email should be sent using + /// Gets or sets a value indicating whether the email should be sent using /// a secure communication channel. /// /// true if should use SSL; otherwise, false. @@ -110,42 +109,33 @@ public bool UseSsl } /// - /// Sends a message. + /// Sends a message. /// /// If any of the parameters is null /// From field /// To field /// e-mail's subject /// message's body -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif - public void Send(String from, String to, String subject, String messageText) + public void Send(string from, string to, string subject, string messageText) { - if (from == null) throw new ArgumentNullException("from"); - if (to == null) throw new ArgumentNullException("to"); - if (subject == null) throw new ArgumentNullException("subject"); - if (messageText == null) throw new ArgumentNullException("messageText"); + if (from == null) throw new ArgumentNullException(nameof(from)); + if (to == null) throw new ArgumentNullException(nameof(to)); + if (subject == null) throw new ArgumentNullException(nameof(subject)); + if (messageText == null) throw new ArgumentNullException(nameof(messageText)); Send(new MailMessage(from, to, subject, messageText)); } /// - /// Sends a message. + /// Sends a message. /// /// If the message is null /// Message instance -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public void Send(MailMessage message) { InternalSend(message); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private void InternalSend(MailMessage message) { if (message == null) throw new ArgumentNullException("message"); @@ -182,9 +172,6 @@ private void InternalSend(MailMessage message) } } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public void Send(IEnumerable messages) { foreach (MailMessage message in messages) @@ -197,31 +184,19 @@ public void Send(IEnumerable messages) /// Gets or sets the domain. /// /// The domain. - public String Domain - { - get { return credentials.Domain; } - set { credentials.Domain = value; } - } + public string Domain { get; set; } /// /// Gets or sets the name of the user. /// /// The name of the user. - public String UserName - { - get { return credentials.UserName; } - set { credentials.UserName = value; } - } + public string UserName { get; set; } /// /// Gets or sets the password. /// /// The password. - public String Password - { - get { return credentials.Password; } - set { credentials.Password = value; } - } + public string Password { get; set; } /// /// Configures the sender @@ -229,15 +204,13 @@ public String Password /// informed /// /// Message instance -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif protected virtual void Configure(SmtpClient smtpClient) { smtpClient.Credentials = null; - if (CanAccessCredentials() && HasCredentials) + if (HasCredentials) { + var credentials = new NetworkCredential(UserName, Password, Domain); smtpClient.Credentials = credentials; } @@ -260,12 +233,9 @@ protected virtual void Configure(SmtpClient smtpClient) /// private bool HasCredentials { - get { return !string.IsNullOrEmpty(credentials.UserName); } + get { return !string.IsNullOrEmpty(UserName); } } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif private SmtpClient CreateSmtpClient() { if (string.IsNullOrEmpty(hostname)) @@ -279,11 +249,6 @@ private SmtpClient CreateSmtpClient() Configure(smtpClient); return smtpClient; } - - private static bool CanAccessCredentials() - { - return new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).IsGranted(); - } } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/IEmailSender.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/IEmailSender.cs index 8d4d78b8..2c576672 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/IEmailSender.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Smtp/IEmailSender.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -47,4 +47,4 @@ internal interface IEmailSender } } -#endif \ No newline at end of file +#endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/StringObjectDictionaryAdapter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/StringObjectDictionaryAdapter.cs index 4d6125c2..394035f6 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/StringObjectDictionaryAdapter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.Core/StringObjectDictionaryAdapter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AbstractInvocation.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AbstractInvocation.cs index 3d34d01d..268dfe8b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AbstractInvocation.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AbstractInvocation.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,11 +17,9 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy using System; using System.Diagnostics; using System.Reflection; - using Telerik.JustMock.Diagnostics; -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public abstract class AbstractInvocation : IInvocation - { + public abstract class AbstractInvocation : IInvocation + { private readonly IInterceptor[] interceptors; private readonly object[] arguments; private int currentInterceptorIndex = -1; @@ -35,7 +33,7 @@ protected AbstractInvocation( MethodInfo proxiedMethod, object[] arguments) { - Debug.Assert(proxiedMethod != null); + Debug.Assert(proxiedMethod != null); proxyObject = proxy; this.interceptors = interceptors; this.proxiedMethod = proxiedMethod; @@ -117,21 +115,9 @@ public void Proceed() } else if (currentInterceptorIndex > interceptors.Length) { - string interceptorsCount; - if (interceptors.Length > 1) - { - interceptorsCount = " each one of " + interceptors.Length + " interceptors"; - } - else - { - interceptorsCount = " interceptor"; - } - - var message = "This is a DynamicProxy2 error: invocation.Proceed() has been called more times than expected." + - "This usually signifies a bug in the calling code. Make sure that" + interceptorsCount + - " selected for the method '" + Method + "'" + - "calls invocation.Proceed() at most once."; - throw new InvalidOperationException(message); + throw new InvalidOperationException( + "Cannot proceed past the end of the interception pipeline. " + + "This likely signifies a bug in the calling code."); } else { @@ -144,6 +130,11 @@ public void Proceed() } } + public IInvocationProceedInfo CaptureProceedInfo() + { + return new ProceedInfo(this); + } + protected abstract void InvokeMethodOnTarget(); protected void ThrowOnNoTarget() @@ -161,7 +152,7 @@ protected void ThrowOnNoTarget() string methodKindIs; string methodKindDescription; - if (Method.DeclaringType.GetTypeInfo().IsClass && Method.IsAbstract) + if (Method.DeclaringType.IsClass && Method.IsAbstract) { methodKindIs = "is abstract"; methodKindDescription = "an abstract method"; @@ -185,11 +176,36 @@ private MethodInfo EnsureClosedMethod(MethodInfo method) { if (method.ContainsGenericParameters) { - JMDebug.Assert(genericMethodArguments != null); + Debug.Assert(genericMethodArguments != null); return method.GetGenericMethodDefinition().MakeGenericMethod(genericMethodArguments); } return method; } + + private sealed class ProceedInfo : IInvocationProceedInfo + { + private readonly AbstractInvocation invocation; + private readonly int interceptorIndex; + + public ProceedInfo(AbstractInvocation invocation) + { + this.invocation = invocation; + this.interceptorIndex = invocation.currentInterceptorIndex; + } + + public void Invoke() + { + var previousInterceptorIndex = invocation.currentInterceptorIndex; + try + { + invocation.currentInterceptorIndex = interceptorIndex; + invocation.Proceed(); + } + finally + { + invocation.currentInterceptorIndex = previousInterceptorIndex; + } + } + } } -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AllMethodsHook.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AllMethodsHook.cs index c19058db..692fe0ad 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AllMethodsHook.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/AllMethodsHook.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -22,16 +22,14 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy [Serializable] #endif internal class AllMethodsHook : IProxyGenerationHook, IConstructorGenerationHook - { - public static readonly AllMethodsHook Instance = new AllMethodsHook(); + { + public static readonly AllMethodsHook Instance = new AllMethodsHook(); - protected static readonly ICollection SkippedTypes = new[] + protected static readonly ICollection SkippedTypes = new[] { typeof(object), -#if FEATURE_REMOTING typeof(MarshalByRefObject), typeof(ContextBoundObject) -#endif }; public virtual bool ShouldInterceptMethod(Type type, MethodInfo methodInfo) @@ -57,17 +55,16 @@ public override int GetHashCode() return GetType().GetHashCode(); } - public ProxyConstructorImplementation DefaultConstructorImplementation - { - get { return ProxyConstructorImplementation.SkipConstructor; } - } + public ProxyConstructorImplementation DefaultConstructorImplementation + { + get { return ProxyConstructorImplementation.SkipConstructor; } + } - - public ProxyConstructorImplementation GetConstructorImplementation(ConstructorInfo constructorInfo, ConstructorImplementationAnalysis analysis) - { - return analysis.IsBaseVisible - ? ProxyConstructorImplementation.CallBase - : ProxyConstructorImplementation.SkipConstructor; - } - } -} \ No newline at end of file + public ProxyConstructorImplementation GetConstructorImplementation(ConstructorInfo constructorInfo, ConstructorImplementationAnalysis analysis) + { + return analysis.IsBaseVisible + ? ProxyConstructorImplementation.CallBase + : ProxyConstructorImplementation.SkipConstructor; + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassMembersCollector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassMembersCollector.cs index 3c43b808..14aee672 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassMembersCollector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassMembersCollector.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,9 +18,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors using System.Reflection; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; - internal class ClassMembersCollector : MembersCollector + internal class ClassMembersCollector : MembersCollector { public ClassMembersCollector(Type targetType) : base(targetType) diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyInstanceContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxySerializableContributor.cs similarity index 56% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyInstanceContributor.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxySerializableContributor.cs index 25677aaa..d27f57f4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyInstanceContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxySerializableContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,66 +12,76 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if FEATURE_SERIALIZATION + namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors { using System; using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; using System.Reflection; -#if FEATURE_SERIALIZATION using System.Runtime.Serialization; -#endif - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; - using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; + using Castle.DynamicProxy.Generators; + using Castle.DynamicProxy.Generators.Emitters; + using Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Castle.DynamicProxy.Internal; + using Castle.DynamicProxy.Tokens; - internal class ClassProxyInstanceContributor : ProxyInstanceContributor + internal class ClassProxySerializableContributor : SerializableContributor { -#if FEATURE_SERIALIZATION - private readonly bool delegateToBaseGetObjectData; - private readonly bool implementISerializable; + private bool delegateToBaseGetObjectData; private ConstructorInfo serializationConstructor; private readonly IList serializedFields = new List(); -#endif - public ClassProxyInstanceContributor(Type targetType, IList methodsToSkip, Type[] interfaces, - string typeId) + public ClassProxySerializableContributor(Type targetType, Type[] interfaces, string typeId) : base(targetType, interfaces, typeId) { -#if FEATURE_SERIALIZATION - if (targetType.IsSerializable) - { - implementISerializable = true; - delegateToBaseGetObjectData = VerifyIfBaseImplementsGetObjectData(targetType, methodsToSkip); - } -#endif + Debug.Assert(targetType.IsSerializable, "This contributor is intended for serializable types only."); } - protected override Reference GetTargetReference(ClassEmitter emitter) + public override void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model) { - return SelfReference.Self; - } + delegateToBaseGetObjectData = VerifyIfBaseImplementsGetObjectData(targetType, model, out var getObjectData); - public override void Generate(ClassEmitter @class, ProxyGenerationOptions options) - { - var interceptors = @class.GetField("__interceptors"); -#if FEATURE_SERIALIZATION - if (implementISerializable) + // This contributor is going to add a `GetObjectData` method to the proxy type. + // If a method with the same name and signature exists in the proxied class type, + // and another contributor has decided to proxy it, we need to tell it not to. + // Otherwise, we'll end up with two implementations! + + if (getObjectData == null) { - ImplementGetObjectData(@class); - Constructor(@class); + // `VerifyIfBaseImplementsGetObjectData` only searches for `GetObjectData` + // in the implementation map for `ISerializable`. In the best case, it was + // already found there. If not, we need to look again, since *any* method + // with the same signature is a problem. + + var getObjectDataMethod = targetType.GetMethod( + "GetObjectData", + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, + null, + new[] { typeof(SerializationInfo), typeof(StreamingContext) }, + null); + + if (getObjectDataMethod != null) + { + getObjectData = model.FindMethod(getObjectDataMethod); + } } -#endif - ImplementProxyTargetAccessor(@class, interceptors); - foreach (var attribute in targetType.GetTypeInfo().GetNonInheritableAttributes()) + + if (getObjectData != null && getObjectData.Proxyable) { - @class.DefineCustomAttribute(attribute.Builder); + getObjectData.Ignore = true; } } -#if FEATURE_SERIALIZATION + public override void Generate(ClassEmitter @class) + { + ImplementGetObjectData(@class); + Constructor(@class); + } + protected override void AddAddValueInvocation(ArgumentReference serializationInfo, MethodEmitter getObjectData, FieldReference field) { @@ -79,69 +89,69 @@ protected override void AddAddValueInvocation(ArgumentReference serializationInf base.AddAddValueInvocation(serializationInfo, getObjectData, field); } - protected override void CustomizeGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo, + protected override void CustomizeGetObjectData(CodeBuilder codeBuilder, ArgumentReference serializationInfo, ArgumentReference streamingContext, ClassEmitter emitter) { - codebuilder.AddStatement(new ExpressionStatement( - new MethodInvocationExpression( - serializationInfo, - SerializationInfoMethods.AddValue_Bool, - new ConstReference("__delegateToBase").ToExpression(), - new ConstReference(delegateToBaseGetObjectData). - ToExpression()))); + codeBuilder.AddStatement( + new MethodInvocationExpression( + serializationInfo, + SerializationInfoMethods.AddValue_Bool, + new LiteralStringExpression("__delegateToBase"), + new LiteralBoolExpression(delegateToBaseGetObjectData))); if (delegateToBaseGetObjectData == false) { - EmitCustomGetObjectData(codebuilder, serializationInfo); + EmitCustomGetObjectData(codeBuilder, serializationInfo); return; } - EmitCallToBaseGetObjectData(codebuilder, serializationInfo, streamingContext); + EmitCallToBaseGetObjectData(codeBuilder, serializationInfo, streamingContext); } - private void EmitCustomGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo) + private void EmitCustomGetObjectData(CodeBuilder codeBuilder, ArgumentReference serializationInfo) { - var members = codebuilder.DeclareLocal(typeof(MemberInfo[])); - var data = codebuilder.DeclareLocal(typeof(object[])); + var members = codeBuilder.DeclareLocal(typeof(MemberInfo[])); + var data = codeBuilder.DeclareLocal(typeof(object[])); var getSerializableMembers = new MethodInvocationExpression( null, FormatterServicesMethods.GetSerializableMembers, new TypeTokenExpression(targetType)); - codebuilder.AddStatement(new AssignStatement(members, getSerializableMembers)); + codeBuilder.AddStatement(new AssignStatement(members, getSerializableMembers)); // Sort to keep order on both serialize and deserialize side the same, c.f DYNPROXY-ISSUE-127 var callSort = new MethodInvocationExpression( null, TypeUtilMethods.Sort, - members.ToExpression()); - codebuilder.AddStatement(new AssignStatement(members, callSort)); + members); + codeBuilder.AddStatement(new AssignStatement(members, callSort)); var getObjectData = new MethodInvocationExpression( null, FormatterServicesMethods.GetObjectData, - SelfReference.Self.ToExpression(), - members.ToExpression()); - codebuilder.AddStatement(new AssignStatement(data, getObjectData)); + SelfReference.Self, + members); + codeBuilder.AddStatement(new AssignStatement(data, getObjectData)); var addValue = new MethodInvocationExpression( serializationInfo, SerializationInfoMethods.AddValue_Object, - new ConstReference("__data").ToExpression(), - data.ToExpression()); - codebuilder.AddStatement(new ExpressionStatement(addValue)); + new LiteralStringExpression("__data"), + data); + codeBuilder.AddStatement(addValue); } - private void EmitCallToBaseGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo, + private void EmitCallToBaseGetObjectData(CodeBuilder codeBuilder, ArgumentReference serializationInfo, ArgumentReference streamingContext) { var baseGetObjectData = targetType.GetMethod("GetObjectData", new[] { typeof(SerializationInfo), typeof(StreamingContext) }); - codebuilder.AddStatement(new ExpressionStatement( - new MethodInvocationExpression(baseGetObjectData, - serializationInfo.ToExpression(), - streamingContext.ToExpression()))); + codeBuilder.AddStatement( + new MethodInvocationExpression( + baseGetObjectData, + serializationInfo, + streamingContext)); } private void Constructor(ClassEmitter emitter) @@ -162,14 +172,14 @@ private void GenerateSerializationConstructor(ClassEmitter emitter) ctor.CodeBuilder.AddStatement( new ConstructorInvocationStatement(serializationConstructor, - serializationInfo.ToExpression(), - streamingContext.ToExpression())); + serializationInfo, + streamingContext)); foreach (var field in serializedFields) { var getValue = new MethodInvocationExpression(serializationInfo, SerializationInfoMethods.GetValue, - new ConstReference(field.Reference.Name).ToExpression(), + new LiteralStringExpression(field.Reference.Name), new TypeTokenExpression(field.Reference.FieldType)); ctor.CodeBuilder.AddStatement(new AssignStatement( field, @@ -180,14 +190,16 @@ private void GenerateSerializationConstructor(ClassEmitter emitter) ctor.CodeBuilder.AddStatement(new ReturnStatement()); } - private bool VerifyIfBaseImplementsGetObjectData(Type baseType, IList methodsToSkip) + private bool VerifyIfBaseImplementsGetObjectData(Type baseType, MetaType model, out MetaMethod getObjectData) { + getObjectData = null; + if (!typeof(ISerializable).IsAssignableFrom(baseType)) { return false; } - if (IsDelegate(baseType)) + if (baseType.IsDelegateType()) { //working around bug in CLR which returns true for "does this type implement ISerializable" for delegates return false; @@ -203,14 +215,14 @@ private bool VerifyIfBaseImplementsGetObjectData(Type baseType, IList methodsToSkip; private readonly Type targetType; - public ClassProxyTargetContributor(Type targetType, IList methodsToSkip, INamingScope namingScope) + public ClassProxyTargetContributor(Type targetType, INamingScope namingScope) : base(namingScope) { this.targetType = targetType; - this.methodsToSkip = methodsToSkip; } - protected override IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook) + protected override IEnumerable GetCollectors() { - Debug.Assert(hook != null, "hook != null"); - var targetItem = new ClassMembersCollector(targetType) { Logger = Logger }; - targetItem.CollectMembersToProxy(hook); yield return targetItem; foreach (var @interface in interfaces) { var item = new InterfaceMembersOnClassCollector(@interface, true, - targetType.GetTypeInfo().GetRuntimeInterfaceMap(@interface)) { Logger = Logger }; - item.CollectMembersToProxy(hook); + targetType.GetInterfaceMap(@interface)) { Logger = Logger }; yield return item; } } protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { - if (methodsToSkip.Contains(method.Method)) + if (method.Ignore) { return null; } if (!method.Proxyable) { - return new MinimialisticMethodGenerator(method, - overrideMethod); + return new MinimalisticMethodGenerator(method, overrideMethod); } if (ExplicitlyImplementedInterfaceMethod(method)) { - return ExplicitlyImplementedInterfaceMethodGenerator(method, @class, options, overrideMethod); + return ExplicitlyImplementedInterfaceMethodGenerator(method, @class, overrideMethod); } - var invocation = GetInvocationType(method, @class, options); + var invocation = GetInvocationType(method, @class); GetTargetExpressionDelegate getTargetTypeExpression = (c, m) => new TypeTokenExpression(targetType); @@ -89,7 +81,7 @@ protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEm null); } - private Type BuildInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type BuildInvocationType(MetaMethod method, ClassEmitter @class) { var methodInfo = method.Method; if (!method.HasTarget) @@ -97,14 +89,14 @@ private Type BuildInvocationType(MetaMethod method, ClassEmitter @class, ProxyGe return new InheritanceInvocationTypeGenerator(targetType, method, null, null) - .Generate(@class, options, namingScope) + .Generate(@class, namingScope) .BuildType(); } var callback = CreateCallbackMethod(@class, methodInfo, method.MethodOnTarget); return new InheritanceInvocationTypeGenerator(callback.DeclaringType, method, callback, null) - .Generate(@class, options, namingScope) + .Generate(@class, namingScope) .BuildType(); } @@ -118,19 +110,13 @@ private MethodBuilder CreateCallbackMethod(ClassEmitter emitter, MethodInfo meth targetMethod = targetMethod.MakeGenericMethod(callBackMethod.GenericTypeParams.AsTypeArray()); } - var exps = new Expression[callBackMethod.Arguments.Length]; - for (var i = 0; i < callBackMethod.Arguments.Length; i++) - { - exps[i] = callBackMethod.Arguments[i].ToExpression(); - } - // invocation on base class callBackMethod.CodeBuilder.AddStatement( new ReturnStatement( new MethodInvocationExpression(SelfReference.Self, targetMethod, - exps))); + callBackMethod.Arguments))); return callBackMethod.MethodBuilder; } @@ -141,13 +127,12 @@ private bool ExplicitlyImplementedInterfaceMethod(MetaMethod method) } private MethodGenerator ExplicitlyImplementedInterfaceMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { - var @delegate = GetDelegateType(method, @class, options); + var @delegate = GetDelegateType(method, @class); var contributor = GetContributor(@delegate, method); var invocation = new InheritanceInvocationTypeGenerator(targetType, method, null, contributor) - .Generate(@class, options, namingScope) + .Generate(@class, namingScope) .BuildType(); return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), @@ -159,7 +144,7 @@ private MethodGenerator ExplicitlyImplementedInterfaceMethodGenerator(MetaMethod private IInvocationCreationContributor GetContributor(Type @delegate, MetaMethod method) { - if (@delegate.GetTypeInfo().IsGenericType == false) + if (@delegate.IsGenericType == false) { return new InvocationWithDelegateContributor(@delegate, targetType, method, namingScope); } @@ -168,36 +153,34 @@ private IInvocationCreationContributor GetContributor(Type @delegate, MetaMethod new FieldReference(InvocationMethods.ProxyObject)); } - private Type GetDelegateType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type GetDelegateType(MetaMethod method, ClassEmitter @class) { var scope = @class.ModuleScope; var key = new CacheKey( - typeof(Delegate).GetTypeInfo(), + typeof(Delegate), targetType, new[] { method.MethodOnTarget.ReturnType } .Concat(ArgumentsUtil.GetTypes(method.MethodOnTarget.GetParameters())). ToArray(), null); - var type = scope.GetFromCache(key); - if (type != null) - { - return type; - } - - type = new DelegateTypeGenerator(method, targetType) - .Generate(@class, options, namingScope) - .BuildType(); - - scope.RegisterInCache(key, type); - - return type; + return scope.TypeCache.GetOrAddWithoutTakingLock(key, _ => + new DelegateTypeGenerator(method, targetType) + .Generate(@class, namingScope) + .BuildType()); } - private Type GetInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type GetInvocationType(MetaMethod method, ClassEmitter @class) { + if (!method.HasTarget) + { + // We do not need to generate a custom invocation type because no custom implementation + // for `InvokeMethodOnTarget` will be needed (proceeding to target isn't possible here): + return typeof(InheritanceInvocationWithoutTarget); + } + // NOTE: No caching since invocation is tied to this specific proxy type via its invocation method - return BuildInvocationType(method, @class, options); + return BuildInvocationType(method, @class); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetInstanceContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetInstanceContributor.cs deleted file mode 100644 index 33ec6721..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetInstanceContributor.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors -{ - using System; - using System.Collections.Generic; - using System.Reflection; - - using Castle.DynamicProxy.Generators.Emitters; - using Castle.DynamicProxy.Generators.Emitters.SimpleAST; - - class ClassProxyWithTargetInstanceContributor : ClassProxyInstanceContributor - { - public ClassProxyWithTargetInstanceContributor(Type targetType, IList methodsToSkip, - Type[] interfaces, string typeId) - : base(targetType, methodsToSkip, interfaces, typeId) - { - } - - protected override Reference GetTargetReference(ClassEmitter emitter) - { - return emitter.GetField("__target"); - } - } -} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetTargetContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetTargetContributor.cs index ca45153f..59108731 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetTargetContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ClassProxyWithTargetTargetContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -25,74 +25,74 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; - internal class ClassProxyWithTargetTargetContributor : CompositeTypeContributor + internal class ClassProxyWithTargetTargetContributor : CompositeTypeContributor { - private readonly IList methodsToSkip; private readonly Type targetType; - public ClassProxyWithTargetTargetContributor(Type targetType, IList methodsToSkip, - INamingScope namingScope) + public ClassProxyWithTargetTargetContributor(Type targetType, INamingScope namingScope) : base(namingScope) { this.targetType = targetType; - this.methodsToSkip = methodsToSkip; } - protected override IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook) + protected override IEnumerable GetCollectors() { - Debug.Assert(hook != null, "hook != null"); - var targetItem = new WrappedClassMembersCollector(targetType) { Logger = Logger }; - targetItem.CollectMembersToProxy(hook); yield return targetItem; foreach (var @interface in interfaces) { var item = new InterfaceMembersOnClassCollector(@interface, true, - targetType.GetTypeInfo().GetRuntimeInterfaceMap(@interface)) { Logger = Logger }; - item.CollectMembersToProxy(hook); + targetType.GetInterfaceMap(@interface)) { Logger = Logger }; yield return item; } } protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { - if (methodsToSkip.Contains(method.Method)) + if (method.Ignore) { return null; } + var methodIsDirectlyAccessible = IsDirectlyAccessible(method); + if (!method.Proxyable) { - return new MinimialisticMethodGenerator(method, - overrideMethod); + if (methodIsDirectlyAccessible) + { + return new ForwardingMethodGenerator(method, overrideMethod, (c, m) => c.GetField("__target")); + } + else + { + return IndirectlyCalledMethodGenerator(method, @class, overrideMethod, skipInterceptors: true); + } } - if (IsDirectlyAccessible(method) == false) + if (!methodIsDirectlyAccessible) { - return IndirectlyCalledMethodGenerator(method, @class, options, overrideMethod); + return IndirectlyCalledMethodGenerator(method, @class, overrideMethod); } - var invocation = GetInvocationType(method, @class, options); + var invocation = GetInvocationType(method, @class); return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), invocation, - (c, m) => c.GetField("__target").ToExpression(), + (c, m) => c.GetField("__target"), overrideMethod, null); } - private Type BuildInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type BuildInvocationType(MetaMethod method, ClassEmitter @class) { if (!method.HasTarget) { return new InheritanceInvocationTypeGenerator(targetType, method, null, null) - .Generate(@class, options, namingScope) + .Generate(@class, namingScope) .BuildType(); } return new CompositionInvocationTypeGenerator(method.Method.DeclaringType, @@ -100,48 +100,39 @@ private Type BuildInvocationType(MetaMethod method, ClassEmitter @class, ProxyGe method.Method, false, null) - .Generate(@class, options, namingScope) + .Generate(@class, namingScope) .BuildType(); } private IInvocationCreationContributor GetContributor(Type @delegate, MetaMethod method) { - if (@delegate.GetTypeInfo().IsGenericType == false) + if (@delegate.IsGenericType == false) { return new InvocationWithDelegateContributor(@delegate, targetType, method, namingScope); } return new InvocationWithGenericDelegateContributor(@delegate, method, - new FieldReference(InvocationMethods.Target)); + new FieldReference(InvocationMethods.CompositionInvocationTarget)); } - private Type GetDelegateType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type GetDelegateType(MetaMethod method, ClassEmitter @class) { var scope = @class.ModuleScope; var key = new CacheKey( - typeof(Delegate).GetTypeInfo(), + typeof(Delegate), targetType, new[] { method.MethodOnTarget.ReturnType } .Concat(ArgumentsUtil.GetTypes(method.MethodOnTarget.GetParameters())). ToArray(), null); - var type = scope.GetFromCache(key); - if (type != null) - { - return type; - } - - type = new DelegateTypeGenerator(method, targetType) - .Generate(@class, options, namingScope) - .BuildType(); - - scope.RegisterInCache(key, type); - - return type; + return scope.TypeCache.GetOrAddWithoutTakingLock(key, _ => + new DelegateTypeGenerator(method, targetType) + .Generate(@class, namingScope) + .BuildType()); } - private Type GetInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type GetInvocationType(MetaMethod method, ClassEmitter @class) { var scope = @class.ModuleScope; var invocationInterfaces = new[] { typeof(IInvocation) }; @@ -150,31 +141,22 @@ private Type GetInvocationType(MetaMethod method, ClassEmitter @class, ProxyGene // no locking required as we're already within a lock - var invocation = scope.GetFromCache(key); - if (invocation != null) - { - return invocation; - } - invocation = BuildInvocationType(method, @class, options); - - scope.RegisterInCache(key, invocation); - - return invocation; + return scope.TypeCache.GetOrAddWithoutTakingLock(key, _ => BuildInvocationType(method, @class)); } private MethodGenerator IndirectlyCalledMethodGenerator(MetaMethod method, ClassEmitter proxy, - ProxyGenerationOptions options, - OverrideMethodDelegate overrideMethod) + OverrideMethodDelegate overrideMethod, + bool skipInterceptors = false) { - var @delegate = GetDelegateType(method, proxy, options); + var @delegate = GetDelegateType(method, proxy); var contributor = GetContributor(@delegate, method); var invocation = new CompositionInvocationTypeGenerator(targetType, method, null, false, contributor) - .Generate(proxy, options, namingScope) + .Generate(proxy, namingScope) .BuildType(); return new MethodWithInvocationGenerator(method, - proxy.GetField("__interceptors"), + skipInterceptors ? NullExpression.Instance as IExpression : proxy.GetField("__interceptors"), invocation, - (c, m) => c.GetField("__target").ToExpression(), + (c, m) => c.GetField("__target"), overrideMethod, contributor); } @@ -184,4 +166,4 @@ private bool IsDirectlyAccessible(MetaMethod method) return method.MethodOnTarget.IsPublic; } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/CompositeTypeContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/CompositeTypeContributor.cs index 35278833..7e6f1e19 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/CompositeTypeContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/CompositeTypeContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -31,9 +31,9 @@ internal abstract class CompositeTypeContributor : ITypeContributor protected readonly ICollection interfaces = new HashSet(); private ILogger logger = NullLogger.Instance; - private readonly ICollection properties = new TypeElementCollection(); - private readonly ICollection events = new TypeElementCollection(); - private readonly ICollection methods = new TypeElementCollection(); + private readonly List properties = new List(); + private readonly List events = new List(); + private readonly List methods = new List(); protected CompositeTypeContributor(INamingScope namingScope) { @@ -48,29 +48,20 @@ public ILogger Logger public void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model) { - foreach (var collector in CollectElementsToProxyInternal(hook)) + Debug.Assert(hook != null); + Debug.Assert(model != null); + + var sink = new MembersCollectorSink(model, this); + + foreach (var collector in GetCollectors()) { - foreach (var method in collector.Methods) - { - model.AddMethod(method); - methods.Add(method); - } - foreach (var @event in collector.Events) - { - model.AddEvent(@event); - events.Add(@event); - } - foreach (var property in collector.Properties) - { - model.AddProperty(property); - properties.Add(property); - } + collector.CollectMembersToProxy(hook, sink); } } - protected abstract IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook); + protected abstract IEnumerable GetCollectors(); - public virtual void Generate(ClassEmitter @class, ProxyGenerationOptions options) + public virtual void Generate(ClassEmitter @class) { foreach (var method in methods) { @@ -81,71 +72,113 @@ public virtual void Generate(ClassEmitter @class, ProxyGenerationOptions options ImplementMethod(method, @class, - options, @class.CreateMethod); } foreach (var property in properties) { - ImplementProperty(@class, property, options); + ImplementProperty(@class, property); } foreach (var @event in events) { - ImplementEvent(@class, @event, options); + ImplementEvent(@class, @event); } } public void AddInterfaceToProxy(Type @interface) { Debug.Assert(@interface != null, "@interface == null", "Shouldn't be adding empty interfaces..."); - Debug.Assert(@interface.GetTypeInfo().IsInterface, "@interface.IsInterface", "Should be adding interfaces only..."); + Debug.Assert(@interface.IsInterface || @interface.IsDelegateType(), "@interface.IsInterface || @interface.IsDelegateType()", "Should be adding interfaces or delegate types only..."); Debug.Assert(!interfaces.Contains(@interface), "!interfaces.ContainsKey(@interface)", "Shouldn't be adding same interface twice..."); interfaces.Add(@interface); } - private void ImplementEvent(ClassEmitter emitter, MetaEvent @event, ProxyGenerationOptions options) + private void ImplementEvent(ClassEmitter emitter, MetaEvent @event) { @event.BuildEventEmitter(emitter); - ImplementMethod(@event.Adder, emitter, options, @event.Emitter.CreateAddMethod); - ImplementMethod(@event.Remover, emitter, options, @event.Emitter.CreateRemoveMethod); + ImplementMethod(@event.Adder, emitter, @event.Emitter.CreateAddMethod); + ImplementMethod(@event.Remover, emitter, @event.Emitter.CreateRemoveMethod); } - private void ImplementProperty(ClassEmitter emitter, MetaProperty property, ProxyGenerationOptions options) + private void ImplementProperty(ClassEmitter emitter, MetaProperty property) { property.BuildPropertyEmitter(emitter); if (property.CanRead) { - ImplementMethod(property.Getter, emitter, options, property.Emitter.CreateGetMethod); + ImplementMethod(property.Getter, emitter, property.Emitter.CreateGetMethod); } if (property.CanWrite) { - ImplementMethod(property.Setter, emitter, options, property.Emitter.CreateSetMethod); + ImplementMethod(property.Setter, emitter, property.Emitter.CreateSetMethod); } } protected abstract MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod); - private void ImplementMethod(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options, + private void ImplementMethod(MetaMethod method, ClassEmitter @class, OverrideMethodDelegate overrideMethod) { { - var generator = GetMethodGenerator(method, @class, options, overrideMethod); + var generator = GetMethodGenerator(method, @class, overrideMethod); if (generator == null) { return; } - var proxyMethod = generator.Generate(@class, options, namingScope); + var proxyMethod = generator.Generate(@class, namingScope); foreach (var attribute in method.Method.GetNonInheritableAttributes()) { proxyMethod.DefineCustomAttribute(attribute.Builder); } } } + + private sealed class MembersCollectorSink : IMembersCollectorSink + { + private readonly MetaType model; + private readonly CompositeTypeContributor contributor; + + public MembersCollectorSink(MetaType model, CompositeTypeContributor contributor) + { + this.model = model; + this.contributor = contributor; + } + + // You may have noticed that most contributors do not query `MetaType` at all, + // but only their own collections. So perhaps you are wondering why collected + // type elements are added to `model` at all, and not just to `contributor`? + // + // TL;DR: This prevents member name collisions in the generated proxy type. + // + // `MetaType` uses `MetaTypeElementCollection`s internally, which switches members + // to explicit implementation whenever a name collision with a previously added + // member occurs. + // + // It would be pointless to do this at the level of the individual contributor, + // because name collisions could still occur across several contributors. This + // is why they all share the same `MetaType` instance. + + public void Add(MetaEvent @event) + { + model.AddEvent(@event); + contributor.events.Add(@event); + } + + public void Add(MetaMethod method) + { + model.AddMethod(method); + contributor.methods.Add(method); + } + + public void Add(MetaProperty property) + { + model.AddProperty(property); + contributor.properties.Add(property); + } + } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateProxyTargetContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateProxyTargetContributor.cs deleted file mode 100644 index c3d99f52..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateProxyTargetContributor.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - - internal class DelegateProxyTargetContributor : CompositeTypeContributor - { - private readonly Type targetType; - - public DelegateProxyTargetContributor(Type targetType, INamingScope namingScope) : base(namingScope) - { - this.targetType = targetType; - } - - protected override IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook) - { - Debug.Assert(hook != null, "hook != null"); - var targetItem = new DelegateMembersCollector(targetType) { Logger = Logger }; - targetItem.CollectMembersToProxy(hook); - yield return targetItem; - } - - protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, - OverrideMethodDelegate overrideMethod) - { - var invocation = GetInvocationType(method, @class, options); - return new MethodWithInvocationGenerator(method, - @class.GetField("__interceptors"), - invocation, - (c, m) => c.GetField("__target").ToExpression(), - overrideMethod, - null); - } - - private Type GetInvocationType(MetaMethod method, ClassEmitter emitter, ProxyGenerationOptions options) - { - var scope = emitter.ModuleScope; - var key = new CacheKey(method.Method, CompositionInvocationTypeGenerator.BaseType, null, null); - - // no locking required as we're already within a lock - var invocation = scope.GetFromCache(key); - if (invocation != null) - { - return invocation; - } - - invocation = new CompositionInvocationTypeGenerator(method.Method.DeclaringType, - method, - method.Method, - false, - null) - .Generate(emitter, options, namingScope) - .BuildType(); - - scope.RegisterInCache(key, invocation); - - return invocation; - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateMembersCollector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateTypeMembersCollector.cs similarity index 55% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateMembersCollector.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateTypeMembersCollector.cs index c0a89fea..25bcd99d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateMembersCollector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateTypeMembersCollector.cs @@ -1,40 +1,42 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// +// +// http://www.apache.org/licenses/LICENSE-2.0 +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors { using System; using System.Reflection; - using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; + using Castle.DynamicProxy.Generators; + using Castle.DynamicProxy.Internal; - internal class DelegateMembersCollector : MembersCollector + internal sealed class DelegateTypeMembersCollector : MembersCollector { - public DelegateMembersCollector(Type type) : base(type) + public DelegateTypeMembersCollector(Type delegateType) + : base(delegateType) { } protected override MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, bool isStandalone) { - var accepted = AcceptMethod(method, true, hook); - if (accepted == false) + if (method.Name == "Invoke" && method.DeclaringType.IsDelegateType()) + { + return new MetaMethod(method, method, isStandalone, true, false); + } + else { - //we don't need to do anything... return null; } - - return new MetaMethod(method, method, isStandalone, true, !method.IsAbstract); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/Delegates.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/Delegates.cs index e1d098f9..13a6d8ba 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/Delegates.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/Delegates.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -19,10 +19,10 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - internal delegate MethodEmitter OverrideMethodDelegate( + internal delegate MethodEmitter OverrideMethodDelegate( string name, MethodAttributes attributes, MethodInfo methodToOverride); - internal delegate Expression GetTargetExpressionDelegate(ClassEmitter @class, MethodInfo method); + internal delegate IExpression GetTargetExpressionDelegate(ClassEmitter @class, MethodInfo method); - internal delegate Reference GetTargetReferenceDelegate(ClassEmitter @class, MethodInfo method); + internal delegate Reference GetTargetReferenceDelegate(ClassEmitter @class, MethodInfo method); } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/FieldReferenceComparer.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/FieldReferenceComparer.cs index b6e28d76..70802c0f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/FieldReferenceComparer.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/FieldReferenceComparer.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2017 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ public int Compare(Type x, Type y) throw new ArgumentNullException(nameof(y)); } - return String.CompareOrdinal(x.FullName, y.FullName); + return string.CompareOrdinal(x.FullName, y.FullName); } } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IInvocationCreationContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/IInvocationCreationContributor.cs similarity index 77% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IInvocationCreationContributor.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/IInvocationCreationContributor.cs index 1a4f7a24..84dfb96a 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IInvocationCreationContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/IInvocationCreationContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors { using System.Reflection; @@ -25,9 +25,9 @@ internal interface IInvocationCreationContributor MethodInfo GetCallbackMethod(); - MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, Expression[] args, + MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, IExpression[] args, Reference targetField, MethodEmitter invokeMethodOnTarget); - Expression[] GetConstructorInvocationArguments(Expression[] arguments, ClassEmitter proxy); + IExpression[] GetConstructorInvocationArguments(IExpression[] arguments, ClassEmitter proxy); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/IMembersCollectorSink.cs similarity index 56% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorCollection.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/IMembersCollectorSink.cs index 2920cf59..1c857e75 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorCollection.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/IMembersCollectorSink.cs @@ -1,22 +1,25 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// +// +// http://www.apache.org/licenses/LICENSE-2.0 +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors { - using System.Collections.ObjectModel; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; - internal class ConstructorCollection : Collection + internal interface IMembersCollectorSink { + void Add(MetaEvent @event); + void Add(MetaMethod method); + void Add(MetaProperty property); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ITypeContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ITypeContributor.cs index fba3abae..d537fbb8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ITypeContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ITypeContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -24,6 +24,6 @@ internal interface ITypeContributor { void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model); - void Generate(ClassEmitter @class, ProxyGenerationOptions options); + void Generate(ClassEmitter @class); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersCollector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersCollector.cs index cad19a3e..1fbcd2a2 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersCollector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersCollector.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +33,13 @@ protected override MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGener return null; } - var proxyable = AcceptMethod(method, false, hook); + var proxyable = AcceptMethod(method, true, hook); + if (!proxyable && !method.IsAbstract) + { + // we don't need to do anything + return null; + } + return new MetaMethod(method, method, isStandalone, proxyable, false); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersOnClassCollector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersOnClassCollector.cs index 977cb7bb..930de172 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersOnClassCollector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceMembersOnClassCollector.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyInstanceContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyInstanceContributor.cs deleted file mode 100644 index e73513ae..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyInstanceContributor.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors -{ - using System; - - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; - - internal class InterfaceProxyInstanceContributor : ProxyInstanceContributor - { - protected override Reference GetTargetReference(ClassEmitter emitter) - { - return emitter.GetField("__target"); - } - - public InterfaceProxyInstanceContributor(Type targetType, string proxyGeneratorId, Type[] interfaces) - : base(targetType, interfaces, proxyGeneratorId) - { - } - -#if FEATURE_SERIALIZATION - protected override void CustomizeGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo, - ArgumentReference streamingContext, ClassEmitter emitter) - { - var targetField = emitter.GetField("__target"); - - codebuilder.AddStatement(new ExpressionStatement( - new MethodInvocationExpression(serializationInfo, SerializationInfoMethods.AddValue_Object, - new ConstReference("__targetFieldType").ToExpression(), - new ConstReference( - targetField.Reference.FieldType.AssemblyQualifiedName). - ToExpression()))); - - codebuilder.AddStatement(new ExpressionStatement( - new MethodInvocationExpression(serializationInfo, SerializationInfoMethods.AddValue_Object, - new ConstReference("__theInterface").ToExpression(), - new ConstReference(targetType.AssemblyQualifiedName). - ToExpression()))); - } -#endif - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxySerializableContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxySerializableContributor.cs new file mode 100644 index 00000000..9cea59ff --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxySerializableContributor.cs @@ -0,0 +1,54 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#if FEATURE_SERIALIZATION + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +{ + using System; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; + + internal class InterfaceProxySerializableContributor : SerializableContributor + { + public InterfaceProxySerializableContributor(Type targetType, string proxyGeneratorId, Type[] interfaces) + : base(targetType, interfaces, proxyGeneratorId) + { + } + + protected override void CustomizeGetObjectData(CodeBuilder codeBuilder, ArgumentReference serializationInfo, + ArgumentReference streamingContext, ClassEmitter emitter) + { + var targetField = emitter.GetField("__target"); + + codeBuilder.AddStatement( + new MethodInvocationExpression( + serializationInfo, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression("__targetFieldType"), + new LiteralStringExpression(targetField.Reference.FieldType.AssemblyQualifiedName))); + + codeBuilder.AddStatement( + new MethodInvocationExpression( + serializationInfo, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression("__theInterface"), + new LiteralStringExpression(targetType.AssemblyQualifiedName))); + } + } +} + +#endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyTargetContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyTargetContributor.cs index dbd7f51f..d412279f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyTargetContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyTargetContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -34,15 +34,12 @@ public InterfaceProxyTargetContributor(Type proxyTargetType, bool canChangeTarge this.canChangeTarget = canChangeTarget; } - protected override IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook) + protected override IEnumerable GetCollectors() { - Debug.Assert(hook != null, "hook != null"); - foreach (var @interface in interfaces) { var item = GetCollectorForInterface(@interface); item.Logger = Logger; - item.CollectMembersToProxy(hook); yield return item; } } @@ -54,7 +51,6 @@ protected virtual MembersCollector GetCollectorForInterface(Type @interface) } protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { if (!method.Proxyable) @@ -64,17 +60,17 @@ protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEm (c, m) => c.GetField("__target")); } - var invocation = GetInvocationType(method, @class, options); + var invocation = GetInvocationType(method, @class); return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), invocation, - (c, m) => c.GetField("__target").ToExpression(), + (c, m) => c.GetField("__target"), overrideMethod, null); } - private Type GetInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options) + private Type GetInvocationType(MetaMethod method, ClassEmitter @class) { var scope = @class.ModuleScope; @@ -92,22 +88,14 @@ private Type GetInvocationType(MetaMethod method, ClassEmitter @class, ProxyGene // no locking required as we're already within a lock - var invocation = scope.GetFromCache(key); - if (invocation != null) - { - return invocation; - } - - invocation = new CompositionInvocationTypeGenerator(method.Method.DeclaringType, - method, - method.Method, - canChangeTarget, - null) - .Generate(@class, options, namingScope).BuildType(); - - scope.RegisterInCache(key, invocation); - - return invocation; + return scope.TypeCache.GetOrAddWithoutTakingLock(key, _ => + new CompositionInvocationTypeGenerator(method.Method.DeclaringType, + method, + method.Method, + canChangeTarget, + null) + .Generate(@class, namingScope) + .BuildType()); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithOptionalTargetContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithOptionalTargetContributor.cs index 00952cad..260624ec 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithOptionalTargetContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithOptionalTargetContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -30,7 +30,6 @@ public InterfaceProxyWithOptionalTargetContributor(INamingScope namingScope, Get } protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { if (!method.Proxyable) @@ -38,7 +37,7 @@ protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEm return new OptionallyForwardingMethodGenerator(method, overrideMethod, getTargetReference); } - return base.GetMethodGenerator(method, @class, options, overrideMethod); + return base.GetMethodGenerator(method, @class, overrideMethod); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithTargetInterfaceTargetContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithTargetInterfaceTargetContributor.cs index 91e62a43..2c7c74ad 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithTargetInterfaceTargetContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithTargetInterfaceTargetContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithoutTargetContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithoutTargetContributor.cs index c4d94161..58a4492f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithoutTargetContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InterfaceProxyWithoutTargetContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -20,6 +20,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; internal class InterfaceProxyWithoutTargetContributor : CompositeTypeContributor { @@ -32,27 +33,24 @@ public InterfaceProxyWithoutTargetContributor(INamingScope namingScope, GetTarge getTargetExpression = getTarget; } - protected override IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook) + protected override IEnumerable GetCollectors() { - Debug.Assert(hook != null, "hook != null"); foreach (var @interface in interfaces) { var item = new InterfaceMembersCollector(@interface); - item.CollectMembersToProxy(hook); yield return item; } } protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { if (!method.Proxyable) { - return new MinimialisticMethodGenerator(method, overrideMethod); + return new MinimalisticMethodGenerator(method, overrideMethod); } - var invocation = GetInvocationType(method, @class, options); + var invocation = GetInvocationType(method, @class); return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), invocation, @@ -61,8 +59,17 @@ protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEm null); } - private Type GetInvocationType(MetaMethod method, ClassEmitter emitter, ProxyGenerationOptions options) + private Type GetInvocationType(MetaMethod method, ClassEmitter emitter) { + var methodInfo = method.Method; + + if (canChangeTarget == false && methodInfo.IsAbstract) + { + // We do not need to generate a custom invocation type because no custom implementation + // for `InvokeMethodOnTarget` will be needed (proceeding to target isn't possible here): + return typeof(InterfaceMethodWithoutTargetInvocation); + } + var scope = emitter.ModuleScope; Type[] invocationInterfaces; if (canChangeTarget) @@ -73,27 +80,18 @@ private Type GetInvocationType(MetaMethod method, ClassEmitter emitter, ProxyGen { invocationInterfaces = new[] { typeof(IInvocation) }; } - var key = new CacheKey(method.Method, CompositionInvocationTypeGenerator.BaseType, invocationInterfaces, null); + var key = new CacheKey(methodInfo, CompositionInvocationTypeGenerator.BaseType, invocationInterfaces, null); // no locking required as we're already within a lock - var invocation = scope.GetFromCache(key); - if (invocation != null) - { - return invocation; - } - - invocation = new CompositionInvocationTypeGenerator(method.Method.DeclaringType, - method, - method.Method, - canChangeTarget, - null) - .Generate(emitter, options, namingScope) - .BuildType(); - - scope.RegisterInCache(key, invocation); - - return invocation; + return scope.TypeCache.GetOrAddWithoutTakingLock(key, _ => + new CompositionInvocationTypeGenerator(methodInfo.DeclaringType, + method, + methodInfo, + canChangeTarget, + null) + .Generate(emitter, namingScope) + .BuildType()); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithDelegateContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithDelegateContributor.cs index 5e1805a7..52e9bdfb 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithDelegateContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithDelegateContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +33,7 @@ internal class InvocationWithDelegateContributor : IInvocationCreationContributo public InvocationWithDelegateContributor(Type delegateType, Type targetType, MetaMethod method, INamingScope namingScope) { - Debug.Assert(delegateType.GetTypeInfo().IsGenericType == false, "delegateType.IsGenericType == false"); + Debug.Assert(delegateType.IsGenericType == false, "delegateType.IsGenericType == false"); this.delegateType = delegateType; this.targetType = targetType; this.method = method; @@ -46,7 +46,7 @@ public ConstructorEmitter CreateConstructor(ArgumentReference[] baseCtorArgument var constructor = invocation.CreateConstructor(arguments); var delegateField = invocation.CreateField("delegate", delegateType); - constructor.CodeBuilder.AddStatement(new AssignStatement(delegateField, new ReferenceExpression(arguments[0]))); + constructor.CodeBuilder.AddStatement(new AssignStatement(delegateField, arguments[0])); return constructor; } @@ -55,7 +55,7 @@ public MethodInfo GetCallbackMethod() return delegateType.GetMethod("Invoke"); } - public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, Expression[] args, + public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, IExpression[] args, Reference targetField, MethodEmitter invokeMethodOnTarget) { @@ -65,10 +65,10 @@ public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitte return new MethodInvocationExpression(@delegate, GetCallbackMethod(), allArgs); } - public Expression[] GetConstructorInvocationArguments(Expression[] arguments, ClassEmitter proxy) + public IExpression[] GetConstructorInvocationArguments(IExpression[] arguments, ClassEmitter proxy) { - var allArguments = new Expression[arguments.Length + 1]; - allArguments[0] = new ReferenceExpression(BuildDelegateToken(proxy)); + var allArguments = new IExpression[arguments.Length + 1]; + allArguments[0] = BuildDelegateToken(proxy); Array.Copy(arguments, 0, allArguments, 1, arguments.Length); return allArguments; } @@ -88,11 +88,11 @@ private FieldReference BuildDelegateToken(ClassEmitter proxy) return callback; } - private Expression[] GetAllArgs(Expression[] args, Reference targetField) + private IExpression[] GetAllArgs(IExpression[] args, Reference targetField) { - var allArgs = new Expression[args.Length + 1]; + var allArgs = new IExpression[args.Length + 1]; args.CopyTo(allArgs, 1); - allArgs[0] = new ConvertExpression(targetType, targetField.ToExpression()); + allArgs[0] = new ConvertExpression(targetType, targetField); return allArgs; } @@ -104,4 +104,4 @@ private ArgumentReference[] GetArguments(ArgumentReference[] baseCtorArguments) return arguments; } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithGenericDelegateContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithGenericDelegateContributor.cs index 50f5b10b..47764d90 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithGenericDelegateContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/InvocationWithGenericDelegateContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +33,7 @@ internal class InvocationWithGenericDelegateContributor : IInvocationCreationCon public InvocationWithGenericDelegateContributor(Type delegateType, MetaMethod method, Reference targetReference) { - Debug.Assert(delegateType.GetTypeInfo().IsGenericType, "delegateType.IsGenericType"); + Debug.Assert(delegateType.IsGenericType, "delegateType.IsGenericType"); this.delegateType = delegateType; this.method = method; this.targetReference = targetReference; @@ -49,7 +49,7 @@ public MethodInfo GetCallbackMethod() return delegateType.GetMethod("Invoke"); } - public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, Expression[] args, + public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, IExpression[] args, Reference targetField, MethodEmitter invokeMethodOnTarget) { @@ -57,7 +57,7 @@ public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitte return new MethodInvocationExpression(@delegate, GetCallbackMethod(), args); } - public Expression[] GetConstructorInvocationArguments(Expression[] arguments, ClassEmitter proxy) + public IExpression[] GetConstructorInvocationArguments(IExpression[] arguments, ClassEmitter proxy) { return arguments; } @@ -68,13 +68,12 @@ private Reference GetDelegate(AbstractTypeEmitter invocation, MethodEmitter invo var closedDelegateType = delegateType.MakeGenericType(genericTypeParameters); var localReference = invokeMethodOnTarget.CodeBuilder.DeclareLocal(closedDelegateType); var closedMethodOnTarget = method.MethodOnTarget.MakeGenericMethod(genericTypeParameters); - var localTarget = new ReferenceExpression(targetReference); invokeMethodOnTarget.CodeBuilder.AddStatement( - SetDelegate(localReference, localTarget, closedDelegateType, closedMethodOnTarget)); + SetDelegate(localReference, targetReference, closedDelegateType, closedMethodOnTarget)); return localReference; } - private AssignStatement SetDelegate(LocalReference localDelegate, ReferenceExpression localTarget, + private AssignStatement SetDelegate(LocalReference localDelegate, Reference localTarget, Type closedDelegateType, MethodInfo closedMethodOnTarget) { var delegateCreateDelegate = new MethodInvocationExpression( @@ -86,4 +85,4 @@ private AssignStatement SetDelegate(LocalReference localDelegate, ReferenceExpre return new AssignStatement(localDelegate, new ConvertExpression(closedDelegateType, delegateCreateDelegate)); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MembersCollector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MembersCollector.cs index 5fac18a9..c77190ec 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MembersCollector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MembersCollector.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -28,11 +28,6 @@ internal abstract class MembersCollector private const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; private ILogger logger = NullLogger.Instance; - private ICollection checkedMethods = new HashSet(); - private readonly IDictionary properties = new Dictionary(); - private readonly IDictionary events = new Dictionary(); - private readonly IDictionary methods = new Dictionary(); - protected readonly Type type; protected MembersCollector(Type type) @@ -46,145 +41,116 @@ public ILogger Logger set { logger = value; } } - public IEnumerable Methods + public virtual void CollectMembersToProxy(IProxyGenerationHook hook, IMembersCollectorSink sink) { - get { return methods.Values; } - } - - public IEnumerable Properties - { - get { return properties.Values; } - } + var checkedMethods = new HashSet(); - public IEnumerable Events - { - get { return events.Values; } - } - - public virtual void CollectMembersToProxy(IProxyGenerationHook hook) - { - if (checkedMethods == null) // this method was already called! - { - throw new InvalidOperationException( - string.Format("Can't call 'CollectMembersToProxy' method twice. This usually signifies a bug in custom {0}.", - typeof(ITypeContributor))); - } - CollectProperties(hook); - CollectEvents(hook); + CollectProperties(); + CollectEvents(); // Methods go last, because properties and events have methods too (getters/setters add/remove) // and we don't want to get duplicates, so we collect property and event methods first // then we collect methods, and add only these that aren't there yet - CollectMethods(hook); + CollectMethods(); - checkedMethods = null; // this is ugly, should have a boolean flag for this or something - } - - private void CollectProperties(IProxyGenerationHook hook) - { - var propertiesFound = type.GetProperties(Flags); - foreach (var property in propertiesFound) + void CollectProperties() { - AddProperty(property, hook); - } - } - - private void CollectEvents(IProxyGenerationHook hook) - { - var eventsFound = type.GetEvents(Flags); - foreach (var @event in eventsFound) - { - AddEvent(@event, hook); + var propertiesFound = type.GetProperties(Flags); + foreach (var property in propertiesFound) + { + AddProperty(property); + } } - } - private void CollectMethods(IProxyGenerationHook hook) - { - var methodsFound = MethodFinder.GetAllInstanceMethods(type, Flags); - foreach (var method in methodsFound) + void CollectEvents() { - AddMethod(method, hook, true); + var eventsFound = type.GetEvents(Flags); + foreach (var @event in eventsFound) + { + AddEvent(@event); + } } - } - private void AddProperty(PropertyInfo property, IProxyGenerationHook hook) - { - MetaMethod getter = null; - MetaMethod setter = null; - - if (property.CanRead) + void CollectMethods() { - var getMethod = property.GetGetMethod(true); - getter = AddMethod(getMethod, hook, false); + var methodsFound = MethodFinder.GetAllInstanceMethods(type, Flags); + foreach (var method in methodsFound) + { + AddMethod(method, true); + } } - if (property.CanWrite) + void AddProperty(PropertyInfo property) { - var setMethod = property.GetSetMethod(true); - setter = AddMethod(setMethod, hook, false); - } + MetaMethod getter = null; + MetaMethod setter = null; - if (setter == null && getter == null) - { - return; - } + if (property.CanRead) + { + var getMethod = property.GetGetMethod(true); + getter = AddMethod(getMethod, false); + } - var nonInheritableAttributes = property.GetNonInheritableAttributes(); - var arguments = property.GetIndexParameters(); + if (property.CanWrite) + { + var setMethod = property.GetSetMethod(true); + setter = AddMethod(setMethod, false); + } - properties[property] = new MetaProperty(property.Name, - property.PropertyType, - property.DeclaringType, - getter, - setter, - nonInheritableAttributes.Select(a => a.Builder), - arguments.Select(a => a.ParameterType).ToArray()); - } + if (setter == null && getter == null) + { + return; + } - private void AddEvent(EventInfo @event, IProxyGenerationHook hook) - { - var addMethod = @event.GetAddMethod(true); - var removeMethod = @event.GetRemoveMethod(true); - MetaMethod adder = null; - MetaMethod remover = null; + var nonInheritableAttributes = property.GetNonInheritableAttributes(); + var arguments = property.GetIndexParameters(); - if (addMethod != null) - { - adder = AddMethod(addMethod, hook, false); + sink.Add(new MetaProperty(property, + getter, + setter, + nonInheritableAttributes.Select(a => a.Builder), + arguments.Select(a => a.ParameterType).ToArray())); } - if (removeMethod != null) + void AddEvent(EventInfo @event) { - remover = AddMethod(removeMethod, hook, false); - } + var addMethod = @event.GetAddMethod(true); + var removeMethod = @event.GetRemoveMethod(true); + MetaMethod adder = null; + MetaMethod remover = null; - if (adder == null && remover == null) - { - return; - } + if (addMethod != null) + { + adder = AddMethod(addMethod, false); + } - events[@event] = new MetaEvent(@event.Name, - @event.DeclaringType, @event.EventHandlerType, adder, remover, EventAttributes.None); - } + if (removeMethod != null) + { + remover = AddMethod(removeMethod, false); + } - private MetaMethod AddMethod(MethodInfo method, IProxyGenerationHook hook, bool isStandalone) - { - if (checkedMethods.Contains(method)) - { - return null; - } - checkedMethods.Add(method); + if (adder == null && remover == null) + { + return; + } - if (methods.ContainsKey(method)) - { - return null; + sink.Add(new MetaEvent(@event, adder, remover, EventAttributes.None)); } - var methodToGenerate = GetMethodToGenerate(method, hook, isStandalone); - if (methodToGenerate != null) + + MetaMethod AddMethod(MethodInfo method, bool isStandalone) { - methods[method] = methodToGenerate; - } + if (checkedMethods.Add(method) == false) + { + return null; + } - return methodToGenerate; + var methodToGenerate = GetMethodToGenerate(method, hook, isStandalone); + if (methodToGenerate != null) + { + sink.Add(methodToGenerate); + } + + return methodToGenerate; + } } protected abstract MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, bool isStandalone); @@ -193,11 +159,19 @@ private MetaMethod AddMethod(MethodInfo method, IProxyGenerationHook hook, bool /// Performs some basic screening and invokes the /// to select methods. /// - /// - /// - /// - /// protected bool AcceptMethod(MethodInfo method, bool onlyVirtuals, IProxyGenerationHook hook) + { + return AcceptMethodPreScreen(method, onlyVirtuals, hook) && hook.ShouldInterceptMethod(type, method); + } + + /// + /// Performs some basic screening to filter out non-interceptable methods. + /// + /// + /// The will get invoked for non-interceptable method notification only; + /// it does not get asked whether or not to intercept the . + /// + protected bool AcceptMethodPreScreen(MethodInfo method, bool onlyVirtuals, IProxyGenerationHook hook) { if (IsInternalAndNotVisibleToDynamicProxy(method)) { @@ -207,10 +181,7 @@ protected bool AcceptMethod(MethodInfo method, bool onlyVirtuals, IProxyGenerati var isOverridable = method.IsVirtual && !method.IsFinal; if (onlyVirtuals && !isOverridable) { - if ( -#if FEATURE_REMOTING - method.DeclaringType != typeof(MarshalByRefObject) && -#endif + if (method.DeclaringType != typeof(MarshalByRefObject) && method.IsGetType() == false && method.IsMemberwiseClone() == false) { @@ -230,29 +201,28 @@ protected bool AcceptMethod(MethodInfo method, bool onlyVirtuals, IProxyGenerati } //can only proxy methods that are public or protected (or internals that have already been checked above) - if ((method.IsPublic || method.IsFamily || method.IsAssembly || method.IsFamilyOrAssembly) == false) + if ((method.IsPublic || method.IsFamily || method.IsAssembly || method.IsFamilyOrAssembly || method.IsFamilyAndAssembly) == false) { return false; } -#if FEATURE_REMOTING if (method.DeclaringType == typeof(MarshalByRefObject)) { return false; } -#endif + if (method.IsFinalizer()) { return false; } - return hook.ShouldInterceptMethod(type, method); + return true; } private static bool IsInternalAndNotVisibleToDynamicProxy(MethodInfo method) { return ProxyUtil.IsInternal(method) && - ProxyUtil.AreInternalsVisibleToDynamicProxy(method.DeclaringType.GetTypeInfo().Assembly) == false; + ProxyUtil.AreInternalsVisibleToDynamicProxy(method.DeclaringType.Assembly) == false; } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MixinContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MixinContributor.cs index 29a29f6e..520fa6a0 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MixinContributor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MixinContributor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -22,6 +22,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; internal class MixinContributor : CompositeTypeContributor { @@ -45,7 +46,7 @@ public IEnumerable Fields public void AddEmptyInterface(Type @interface) { Debug.Assert(@interface != null, "@interface == null", "Shouldn't be adding empty interfaces..."); - Debug.Assert(@interface.GetTypeInfo().IsInterface, "@interface.IsInterface", "Should be adding interfaces only..."); + Debug.Assert(@interface.IsInterface, "@interface.IsInterface", "Should be adding interfaces only..."); Debug.Assert(!interfaces.Contains(@interface), "!interfaces.Contains(@interface)", "Shouldn't be adding same interface twice..."); Debug.Assert(!empty.Contains(@interface), "!empty.Contains(@interface)", @@ -53,7 +54,7 @@ public void AddEmptyInterface(Type @interface) empty.Add(@interface); } - public override void Generate(ClassEmitter @class, ProxyGenerationOptions options) + public override void Generate(ClassEmitter @class) { foreach (var @interface in interfaces) { @@ -65,21 +66,28 @@ public override void Generate(ClassEmitter @class, ProxyGenerationOptions option fields[emptyInterface] = BuildTargetField(@class, emptyInterface); } - base.Generate(@class, options); + base.Generate(@class); } - protected override IEnumerable CollectElementsToProxyInternal(IProxyGenerationHook hook) + protected override IEnumerable GetCollectors() { foreach (var @interface in interfaces) { - var item = new InterfaceMembersCollector(@interface); - item.CollectMembersToProxy(hook); + MembersCollector item; + if (@interface.IsInterface) + { + item = new InterfaceMembersCollector(@interface); + } + else + { + Debug.Assert(@interface.IsDelegateType()); + item = new DelegateTypeMembersCollector(@interface); + } yield return item; } } protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, - ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod) { if (!method.Proxyable) @@ -89,7 +97,7 @@ protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEm (c, i) => fields[i.DeclaringType]); } - var invocation = GetInvocationType(method, @class, options); + var invocation = GetInvocationType(method, @class); return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), invocation, @@ -102,12 +110,12 @@ private GetTargetExpressionDelegate BuildGetTargetExpression() { if (!canChangeTarget) { - return (c, m) => fields[m.DeclaringType].ToExpression(); + return (c, m) => fields[m.DeclaringType]; } return (c, m) => new NullCoalescingOperatorExpression( - new AsTypeReference(c.GetField("__target"), m.DeclaringType).ToExpression(), - fields[m.DeclaringType].ToExpression()); + new AsTypeReference(c.GetField("__target"), m.DeclaringType), + fields[m.DeclaringType]); } private FieldReference BuildTargetField(ClassEmitter @class, Type type) @@ -116,7 +124,7 @@ private FieldReference BuildTargetField(ClassEmitter @class, Type type) return @class.CreateField(namingScope.GetUniqueName(name), type); } - private Type GetInvocationType(MetaMethod method, ClassEmitter emitter, ProxyGenerationOptions options) + private Type GetInvocationType(MetaMethod method, ClassEmitter emitter) { var scope = emitter.ModuleScope; Type[] invocationInterfaces; @@ -132,23 +140,14 @@ private Type GetInvocationType(MetaMethod method, ClassEmitter emitter, ProxyGen // no locking required as we're already within a lock - var invocation = scope.GetFromCache(key); - if (invocation != null) - { - return invocation; - } - - invocation = new CompositionInvocationTypeGenerator(method.Method.DeclaringType, - method, - method.Method, - canChangeTarget, - null) - .Generate(emitter, options, namingScope) - .BuildType(); - - scope.RegisterInCache(key, invocation); - - return invocation; + return scope.TypeCache.GetOrAddWithoutTakingLock(key, _ => + new CompositionInvocationTypeGenerator(method.Method.DeclaringType, + method, + method.Method, + canChangeTarget, + null) + .Generate(emitter, namingScope) + .BuildType()); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/NonInheritableAttributesContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/NonInheritableAttributesContributor.cs new file mode 100644 index 00000000..50c58f15 --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/NonInheritableAttributesContributor.cs @@ -0,0 +1,47 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +{ + using System; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + + /// + /// Reproduces the proxied type's non-inheritable custom attributes on the proxy type. + /// + internal sealed class NonInheritableAttributesContributor : ITypeContributor + { + private readonly Type targetType; + + public NonInheritableAttributesContributor(Type targetType) + { + this.targetType = targetType; + } + + public void Generate(ClassEmitter emitter) + { + foreach (var attribute in targetType.GetNonInheritableAttributes()) + { + emitter.DefineCustomAttribute(attribute.Builder); + } + } + + public void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model) + { + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyInstanceContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyInstanceContributor.cs deleted file mode 100644 index ff6471eb..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyInstanceContributor.cs +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors -{ - using System; - using System.Reflection; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization; -#endif - - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; -#if FEATURE_SERIALIZATION - using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; -#endif - using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; - - internal abstract class ProxyInstanceContributor : ITypeContributor - { - protected readonly Type targetType; - private readonly string proxyTypeId; - private readonly Type[] interfaces; - - protected ProxyInstanceContributor(Type targetType, Type[] interfaces, string proxyTypeId) - { - this.targetType = targetType; - this.proxyTypeId = proxyTypeId; - this.interfaces = interfaces ?? Type.EmptyTypes; - } - - protected abstract Reference GetTargetReference(ClassEmitter emitter); - - private Expression GetTargetReferenceExpression(ClassEmitter emitter) - { - return GetTargetReference(emitter).ToExpression(); - } - - public virtual void Generate(ClassEmitter @class, ProxyGenerationOptions options) - { - var interceptors = @class.GetField("__interceptors"); -#if FEATURE_SERIALIZATION - ImplementGetObjectData(@class); -#endif - ImplementProxyTargetAccessor(@class, interceptors); - foreach (var attribute in targetType.GetTypeInfo().GetNonInheritableAttributes()) - { - @class.DefineCustomAttribute(attribute.Builder); - } - } - - protected void ImplementProxyTargetAccessor(ClassEmitter emitter, FieldReference interceptorsField) - { - var dynProxyGetTarget = emitter.CreateMethod("DynProxyGetTarget", typeof(object)); - - dynProxyGetTarget.CodeBuilder.AddStatement( - new ReturnStatement(new ConvertExpression(typeof(object), targetType, GetTargetReferenceExpression(emitter)))); - - var dynProxySetTarget = emitter.CreateMethod("DynProxySetTarget", typeof(void), typeof(object)); - - // we can only change the target of the interface proxy - var targetField = GetTargetReference(emitter) as FieldReference; - if (targetField != null) - { - dynProxySetTarget.CodeBuilder.AddStatement( - new AssignStatement(targetField, - new ConvertExpression(targetField.Fieldbuilder.FieldType, dynProxySetTarget.Arguments[0].ToExpression()))); - } - else - { - dynProxySetTarget.CodeBuilder.AddStatement( - new ThrowStatement(typeof(InvalidOperationException), "Cannot change the target of the class proxy.")); - } - - dynProxySetTarget.CodeBuilder.AddStatement(new ReturnStatement()); - - var getInterceptors = emitter.CreateMethod("GetInterceptors", typeof(IInterceptor[])); - - getInterceptors.CodeBuilder.AddStatement( - new ReturnStatement(interceptorsField)); - } - -#if FEATURE_SERIALIZATION - protected void ImplementGetObjectData(ClassEmitter emitter) - { - var getObjectData = emitter.CreateMethod("GetObjectData", typeof(void), - new[] { typeof(SerializationInfo), typeof(StreamingContext) }); - var info = getObjectData.Arguments[0]; - - var typeLocal = getObjectData.CodeBuilder.DeclareLocal(typeof(Type)); - - getObjectData.CodeBuilder.AddStatement( - new AssignStatement( - typeLocal, - new MethodInvocationExpression( - null, - TypeMethods.StaticGetType, - new ConstReference(typeof(ProxyObjectReference).AssemblyQualifiedName).ToExpression(), - new ConstReference(1).ToExpression(), - new ConstReference(0).ToExpression()))); - - getObjectData.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression( - info, - SerializationInfoMethods.SetType, - typeLocal.ToExpression()))); - - foreach (var field in emitter.GetAllFields()) - { - if (field.Reference.IsStatic) - { - continue; - } - if (field.Reference.IsNotSerialized) - { - continue; - } - AddAddValueInvocation(info, getObjectData, field); - } - - var interfacesLocal = getObjectData.CodeBuilder.DeclareLocal(typeof(string[])); - - getObjectData.CodeBuilder.AddStatement( - new AssignStatement( - interfacesLocal, - new NewArrayExpression(interfaces.Length, typeof(string)))); - - for (var i = 0; i < interfaces.Length; i++) - { - getObjectData.CodeBuilder.AddStatement( - new AssignArrayStatement( - interfacesLocal, - i, - new ConstReference(interfaces[i].AssemblyQualifiedName).ToExpression())); - } - - getObjectData.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression( - info, - SerializationInfoMethods.AddValue_Object, - new ConstReference("__interfaces").ToExpression(), - interfacesLocal.ToExpression()))); - - getObjectData.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression( - info, - SerializationInfoMethods.AddValue_Object, - new ConstReference("__baseType").ToExpression(), - new ConstReference(emitter.BaseType.AssemblyQualifiedName).ToExpression()))); - - getObjectData.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression( - info, - SerializationInfoMethods.AddValue_Object, - new ConstReference("__proxyGenerationOptions").ToExpression(), - emitter.GetField("proxyGenerationOptions").ToExpression()))); - - getObjectData.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression(info, - SerializationInfoMethods.AddValue_Object, - new ConstReference("__proxyTypeId").ToExpression(), - new ConstReference(proxyTypeId).ToExpression()))); - - CustomizeGetObjectData(getObjectData.CodeBuilder, info, getObjectData.Arguments[1], emitter); - - getObjectData.CodeBuilder.AddStatement(new ReturnStatement()); - } - - protected virtual void AddAddValueInvocation(ArgumentReference serializationInfo, MethodEmitter getObjectData, - FieldReference field) - { - getObjectData.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression( - serializationInfo, - SerializationInfoMethods.AddValue_Object, - new ConstReference(field.Reference.Name).ToExpression(), - field.ToExpression()))); - return; - } - - protected abstract void CustomizeGetObjectData(AbstractCodeBuilder builder, ArgumentReference serializationInfo, - ArgumentReference streamingContext, ClassEmitter emitter); -#endif - - public void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model) - { - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyTargetAccessorContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyTargetAccessorContributor.cs new file mode 100644 index 00000000..ec1828b5 --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ProxyTargetAccessorContributor.cs @@ -0,0 +1,74 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +{ + using System; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + + /// + /// Adds an implementation for to the proxy type. + /// + internal sealed class ProxyTargetAccessorContributor : ITypeContributor + { + private readonly Func getTargetReference; + private readonly Type targetType; + + public ProxyTargetAccessorContributor(Func getTargetReference, Type targetType) + { + this.getTargetReference = getTargetReference; + this.targetType = targetType; + } + + public void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model) + { + } + + public void Generate(ClassEmitter emitter) + { + var interceptorsField = emitter.GetField("__interceptors"); + var targetReference = getTargetReference(); + + var dynProxyGetTarget = emitter.CreateMethod(nameof(IProxyTargetAccessor.DynProxyGetTarget), typeof(object)); + + dynProxyGetTarget.CodeBuilder.AddStatement( + new ReturnStatement(new ConvertExpression(typeof(object), targetType, targetReference))); + + var dynProxySetTarget = emitter.CreateMethod(nameof(IProxyTargetAccessor.DynProxySetTarget), typeof(void), typeof(object)); + + // we can only change the target of the interface proxy + if (targetReference is FieldReference targetField) + { + dynProxySetTarget.CodeBuilder.AddStatement( + new AssignStatement(targetField, + new ConvertExpression(targetField.FieldBuilder.FieldType, dynProxySetTarget.Arguments[0]))); + } + else + { + dynProxySetTarget.CodeBuilder.AddStatement( + new ThrowStatement(typeof(InvalidOperationException), "Cannot change the target of the class proxy.")); + } + + dynProxySetTarget.CodeBuilder.AddStatement(new ReturnStatement()); + + var getInterceptors = emitter.CreateMethod(nameof(IProxyTargetAccessor.GetInterceptors), typeof(IInterceptor[])); + + getInterceptors.CodeBuilder.AddStatement( + new ReturnStatement(interceptorsField)); + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/SerializableContributor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/SerializableContributor.cs new file mode 100644 index 00000000..e16b975d --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/SerializableContributor.cs @@ -0,0 +1,153 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#if FEATURE_SERIALIZATION + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +{ + using System; + using System.Runtime.Serialization; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; + using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; + + internal abstract class SerializableContributor : ITypeContributor + { + protected readonly Type targetType; + private readonly string proxyTypeId; + private readonly Type[] interfaces; + + protected SerializableContributor(Type targetType, Type[] interfaces, string proxyTypeId) + { + this.targetType = targetType; + this.proxyTypeId = proxyTypeId; + this.interfaces = interfaces ?? Type.EmptyTypes; + } + + public virtual void Generate(ClassEmitter @class) + { + ImplementGetObjectData(@class); + } + + protected void ImplementGetObjectData(ClassEmitter emitter) + { + var getObjectData = emitter.CreateMethod("GetObjectData", typeof(void), + new[] { typeof(SerializationInfo), typeof(StreamingContext) }); + var info = getObjectData.Arguments[0]; + + var typeLocal = getObjectData.CodeBuilder.DeclareLocal(typeof(Type)); + + getObjectData.CodeBuilder.AddStatement( + new AssignStatement( + typeLocal, + new MethodInvocationExpression( + null, + TypeMethods.StaticGetType, + new LiteralStringExpression(typeof(ProxyObjectReference).AssemblyQualifiedName), + new LiteralBoolExpression(true), + new LiteralBoolExpression(false)))); + + getObjectData.CodeBuilder.AddStatement( + new MethodInvocationExpression( + info, + SerializationInfoMethods.SetType, + typeLocal)); + + foreach (var field in emitter.GetAllFields()) + { + if (field.Reference.IsStatic) + { + continue; + } + if (field.Reference.IsNotSerialized) + { + continue; + } + AddAddValueInvocation(info, getObjectData, field); + } + + var interfacesLocal = getObjectData.CodeBuilder.DeclareLocal(typeof(string[])); + + getObjectData.CodeBuilder.AddStatement( + new AssignStatement( + interfacesLocal, + new NewArrayExpression(interfaces.Length, typeof(string)))); + + for (var i = 0; i < interfaces.Length; i++) + { + getObjectData.CodeBuilder.AddStatement( + new AssignArrayStatement( + interfacesLocal, + i, + new LiteralStringExpression(interfaces[i].AssemblyQualifiedName))); + } + + getObjectData.CodeBuilder.AddStatement( + new MethodInvocationExpression( + info, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression("__interfaces"), + interfacesLocal)); + + getObjectData.CodeBuilder.AddStatement( + new MethodInvocationExpression( + info, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression("__baseType"), + new LiteralStringExpression(emitter.BaseType.AssemblyQualifiedName))); + + getObjectData.CodeBuilder.AddStatement( + new MethodInvocationExpression( + info, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression("__proxyGenerationOptions"), + emitter.GetField("proxyGenerationOptions"))); + + getObjectData.CodeBuilder.AddStatement( + new MethodInvocationExpression( + info, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression("__proxyTypeId"), + new LiteralStringExpression(proxyTypeId))); + + CustomizeGetObjectData(getObjectData.CodeBuilder, info, getObjectData.Arguments[1], emitter); + + getObjectData.CodeBuilder.AddStatement(new ReturnStatement()); + } + + protected virtual void AddAddValueInvocation(ArgumentReference serializationInfo, MethodEmitter getObjectData, + FieldReference field) + { + getObjectData.CodeBuilder.AddStatement( + new MethodInvocationExpression( + serializationInfo, + SerializationInfoMethods.AddValue_Object, + new LiteralStringExpression(field.Reference.Name), + field)); + return; + } + + protected abstract void CustomizeGetObjectData(CodeBuilder builder, ArgumentReference serializationInfo, + ArgumentReference streamingContext, ClassEmitter emitter); + + public virtual void CollectElementsToProxy(IProxyGenerationHook hook, MetaType model) + { + } + } +} + +#endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/WrappedClassMembersCollector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/WrappedClassMembersCollector.cs index dc18beec..3b39af86 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/WrappedClassMembersCollector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/WrappedClassMembersCollector.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -28,9 +28,9 @@ public WrappedClassMembersCollector(Type type) : base(type) { } - public override void CollectMembersToProxy(IProxyGenerationHook hook) + public override void CollectMembersToProxy(IProxyGenerationHook hook, IMembersCollectorSink sink) { - base.CollectMembersToProxy(hook); + base.CollectMembersToProxy(hook, sink); CollectFields(hook); // TODO: perhaps we should also look for nested classes... } @@ -42,13 +42,15 @@ protected override MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGener return null; } - var accepted = AcceptMethod(method, true, hook); - if (!accepted && !method.IsAbstract) + var interceptable = AcceptMethodPreScreen(method, true, hook); + if (!interceptable) { //we don't need to do anything... return null; } + var accepted = hook.ShouldInterceptMethod(type, method); + return new MetaMethod(method, method, isStandalone, accepted, hasTarget: true); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs index f061f2ef..907d6641 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; + using System.Runtime.CompilerServices; /// /// Encapsulates the information needed to build an attribute. @@ -43,10 +44,10 @@ internal class CustomAttributeInfo : IEquatable private readonly IDictionary properties; private readonly IDictionary fields; - public CustomAttributeInfo(CustomAttributeBuilder builder) - { - this.builder = builder; - } + public CustomAttributeInfo(CustomAttributeBuilder builder) + { + this.builder = builder; + } public CustomAttributeInfo( ConstructorInfo constructor, @@ -174,14 +175,26 @@ private static Expression UnwrapBody(Expression body) private static object GetAttributeArgumentValue(Expression arg, bool allowArray) { - var constant = arg as ConstantExpression; - if (constant == null) + switch (arg.NodeType) { - if (allowArray) - { - var newArrayExpr = arg as NewArrayExpression; - if (newArrayExpr != null) + case ExpressionType.Constant: + return ((ConstantExpression)arg).Value; + case ExpressionType.MemberAccess: + var memberExpr = (MemberExpression) arg; + if (memberExpr.Member is FieldInfo field) { + if (memberExpr.Expression is ConstantExpression constant && + IsCompilerGenerated(constant.Type) && + constant.Value != null) + { + return field.GetValue(constant.Value); + } + } + break; + case ExpressionType.NewArrayInit: + if (allowArray) + { + var newArrayExpr = (NewArrayExpression) arg; var array = Array.CreateInstance(newArrayExpr.Type.GetElementType(), newArrayExpr.Expressions.Count); int index = 0; foreach (var expr in newArrayExpr.Expressions) @@ -192,10 +205,15 @@ private static object GetAttributeArgumentValue(Expression arg, bool allowArray) } return array; } - } - throw new ArgumentException("Only constant and single-dimensional array expressions are supported"); + break; } - return constant.Value; + + throw new ArgumentException("Only constant, local variables, method parameters and single-dimensional array expressions are supported"); + } + + private static bool IsCompilerGenerated(Type type) + { + return type.IsDefined(typeof(CompilerGeneratedAttribute)); } internal CustomAttributeBuilder Builder @@ -324,7 +342,7 @@ int IEqualityComparer.GetHashCode(object obj) private static IEnumerable AsObjectEnumerable(object array) { // Covariance doesn't work for value types - if (array.GetType().GetElementType().GetTypeInfo().IsValueType) + if (array.GetType().GetElementType().IsValueType) return ((Array)array).Cast(); return (IEnumerable)array; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs index 635f83db..ba966954 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2014 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -61,83 +61,102 @@ public ModuleScope ModuleScope public Type CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) { - AssertValidType(classToProxy); - AssertValidTypes(additionalInterfacesToProxy); + AssertValidType(classToProxy, nameof(classToProxy)); + AssertValidTypes(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); + AssertValidMixins(options, nameof(options)); - var generator = new ClassProxyGenerator(scope, classToProxy) { Logger = logger }; - return generator.GenerateCode(additionalInterfacesToProxy, options); + var generator = new ClassProxyGenerator(scope, classToProxy, additionalInterfacesToProxy, options) { Logger = logger }; + return generator.GetProxyType(); } public Type CreateClassProxyTypeWithTarget(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) { - AssertValidType(classToProxy); - AssertValidTypes(additionalInterfacesToProxy); + AssertValidType(classToProxy, nameof(classToProxy)); + AssertValidTypes(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); + AssertValidMixins(options, nameof(options)); + var generator = new ClassProxyWithTargetGenerator(scope, classToProxy, additionalInterfacesToProxy, options) { Logger = logger }; - return generator.GetGeneratedType(); + return generator.GetProxyType(); } public Type CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Type targetType, ProxyGenerationOptions options) { - AssertValidType(interfaceToProxy); - AssertValidTypes(additionalInterfacesToProxy); + AssertValidType(interfaceToProxy, nameof(interfaceToProxy)); + AssertValidTypes(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); + AssertValidMixins(options, nameof(options)); - var generator = new InterfaceProxyWithTargetGenerator(scope, interfaceToProxy) { Logger = logger }; - return generator.GenerateCode(targetType, additionalInterfacesToProxy, options); + var generator = new InterfaceProxyWithTargetGenerator(scope, interfaceToProxy, additionalInterfacesToProxy, targetType, options) { Logger = logger }; + return generator.GetProxyType(); } public Type CreateInterfaceProxyTypeWithTargetInterface(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) { - AssertValidType(interfaceToProxy); - AssertValidTypes(additionalInterfacesToProxy); + AssertValidType(interfaceToProxy, nameof(interfaceToProxy)); + AssertValidTypes(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); + AssertValidMixins(options, nameof(options)); - var generator = new InterfaceProxyWithTargetInterfaceGenerator(scope, interfaceToProxy) { Logger = logger }; - return generator.GenerateCode(interfaceToProxy, additionalInterfacesToProxy, options); + var generator = new InterfaceProxyWithTargetInterfaceGenerator(scope, interfaceToProxy, additionalInterfacesToProxy, interfaceToProxy, options) { Logger = logger }; + return generator.GetProxyType(); } public Type CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) { - AssertValidType(interfaceToProxy); - AssertValidTypes(additionalInterfacesToProxy); + AssertValidType(interfaceToProxy, nameof(interfaceToProxy)); + AssertValidTypes(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); + AssertValidMixins(options, nameof(options)); + + var generator = new InterfaceProxyWithoutTargetGenerator(scope, interfaceToProxy, additionalInterfacesToProxy, typeof(object), options) { Logger = logger }; + return generator.GetProxyType(); + } - var generator = new InterfaceProxyWithoutTargetGenerator(scope, interfaceToProxy) { Logger = logger }; - return generator.GenerateCode(typeof(object), additionalInterfacesToProxy, options); + private void AssertValidMixins(ProxyGenerationOptions options, string paramName) + { + try + { + options.Initialize(); + } + catch (InvalidOperationException ex) + { + throw new ArgumentException(ex.Message, paramName, ex.InnerException); // convert to more suitable exception type + } } - private void AssertValidType(Type target) + private void AssertValidType(Type target, string paramName) { - AssertValidTypeForTarget(target, target); + AssertValidTypeForTarget(target, target, paramName); } - private void AssertValidTypeForTarget(Type type, Type target) + private void AssertValidTypeForTarget(Type type, Type target, string paramName) { - if (type.GetTypeInfo().IsGenericTypeDefinition) + if (type.IsGenericTypeDefinition) { - throw new GeneratorException(string.Format("Can not create proxy for type {0} because type {1} is an open generic type.", - target.GetBestName(), type.GetBestName())); + throw new ArgumentException( + $"Can not create proxy for type {target.GetBestName()} because type {type.GetBestName()} is an open generic type.", + paramName); } if (ProxyUtil.IsAccessibleType(type) == false) { - throw new GeneratorException(ExceptionMessageBuilder.CreateMessageForInaccessibleType(type, target)); + throw new ArgumentException(ExceptionMessageBuilder.CreateMessageForInaccessibleType(type, target), paramName); } foreach (var typeArgument in type.GetGenericArguments()) { - AssertValidTypeForTarget(typeArgument, target); + AssertValidTypeForTarget(typeArgument, target, paramName); } } - private void AssertValidTypes(IEnumerable targetTypes) + private void AssertValidTypes(IEnumerable targetTypes, string paramName) { if (targetTypes != null) { foreach (var t in targetTypes) { - AssertValidType(t); + AssertValidType(t, paramName); } } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DynProxy.snk b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DynProxy.snk deleted file mode 100644 index 7fb7fb9c29f935e4f8b665fce0e6b5a5d0dc7abe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50098SN6N!`y_v|{B3|*${tK)e-1+wxBo$ELr?HV4TXtu=Ph`Bf z;t~^p{T-b~tu2z$(N+ZsIV8;L_e@A(@AfLcX}KvL(4#=%6TT7Vr_&KWl1NPV1YF1Y zXIl}-&;bA}S z`vR*!S=B0zjS~GWpEY5W8G1XDFWWa~fTN052p8x4d)I|wPWisqz;q)ieM#HB>$T`t zJcdo$Is0;~;HrG?CMPWPsuDx3W~#~A2i#oT02|?OL1w*?kA%H#>q9O0a`yr!R+&!L z+T&VK@cnn3+y`X6!r!mbwc$hcNVCL|gz|(^u4`U%#8yx}OXy)@Lfg9?eCP!r6&~w| zJrCB706)1jDcRzGbu-KpY!S{%2x)2;2O*epnF@Z^7MQFukDVNmfY~qwl=fcTMV#b& zJn0;i`Yh-rpk!e@JLr4zbO1vFZt4K?&)7Z0lve3JLn}JT%>SXy5MpaqWToSW-Sy2U zZ%l_1hL0$Lg4|E|1h{Ik3NOs^nuCd?4)&@!`XGxIzq!uXO+#QuV15H8S^5LLhR5nF zG8g*&$x^Q}fk3~#n?}_ r.FullName == Assembly.GetExecutingAssembly().FullName); -#else - // .NET Core does not provide an API to do this, so we just fall back to the solution that will definitely work. - // After all it is just an exception message. - return false; -#endif } } @@ -73,7 +67,7 @@ bool ReferencesCastleCore(Assembly ia) /// the type that couldn't be proxied public static string CreateMessageForInaccessibleType(Type inaccessibleType, Type typeToProxy) { - var targetAssembly = typeToProxy.GetTypeInfo().Assembly; + var targetAssembly = typeToProxy.Assembly; string inaccessibleTypeDescription = inaccessibleType == typeToProxy ? "it" diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributeDisassembler.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributeDisassembler.cs deleted file mode 100644 index 9cfbdd8b..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributeDisassembler.cs +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Reflection; - using System.Reflection.Emit; - - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; - - internal class AttributeDisassembler : IAttributeDisassembler - { - public CustomAttributeBuilder Disassemble(Attribute attribute) - { - var type = attribute.GetType(); - - try - { - ConstructorInfo ctor; - var ctorArgs = GetConstructorAndArgs(type, attribute, out ctor); - var replicated = (Attribute)Activator.CreateInstance(type, ctorArgs); - PropertyInfo[] properties; - var propertyValues = GetPropertyValues(type, out properties, attribute, replicated); - FieldInfo[] fields; - var fieldValues = GetFieldValues(type, out fields, attribute, replicated); - return new CustomAttributeBuilder(ctor, ctorArgs, properties, propertyValues, fields, fieldValues); - } - catch (Exception ex) - { - // there is no real way to log a warning here... - return HandleError(type, ex); - } - } - - /// - /// Handles error during disassembly process - /// - /// Type of the attribute being disassembled - /// Exception thrown during the process - /// usually null, or (re)throws the exception - protected virtual CustomAttributeBuilder HandleError(Type attributeType, Exception exception) - { - // ouch... - var message = "DynamicProxy was unable to disassemble attribute " + attributeType.Name + - " using default AttributeDisassembler. " + - string.Format("To handle the disassembly process properly implement the {0} interface, ", - typeof(IAttributeDisassembler)) + - "and register your disassembler to handle this type of attributes using " + - typeof(AttributeUtil).Name + ".AddDisassembler<" + attributeType.Name + ">(yourDisassembler) method"; - throw new ProxyGenerationException(message, exception); - } - - private static object[] GetConstructorAndArgs(Type attributeType, Attribute attribute, out ConstructorInfo ctor) - { - ctor = attributeType.GetConstructors()[0]; - - var constructorParams = ctor.GetParameters(); - if (constructorParams.Length == 0) - { - return new object[0]; - } - - return InitializeConstructorArgs(attributeType, attribute, constructorParams); - } - - private static object[] GetPropertyValues(Type attType, out PropertyInfo[] properties, Attribute original, - Attribute replicated) - { - var propertyCandidates = GetPropertyCandidates(attType); - - var selectedValues = new List(propertyCandidates.Count); - var selectedProperties = new List(propertyCandidates.Count); - foreach (var property in propertyCandidates) - { - var originalValue = property.GetValue(original, null); - var replicatedValue = property.GetValue(replicated, null); - if (AreAttributeElementsEqual(originalValue, replicatedValue)) - { - //this property has default value so we skip it - continue; - } - - selectedProperties.Add(property); - selectedValues.Add(originalValue); - } - - properties = selectedProperties.ToArray(); - return selectedValues.ToArray(); - } - - private static object[] GetFieldValues(Type attType, out FieldInfo[] fields, Attribute original, Attribute replicated) - { - var fieldsCandidates = attType.GetFields(BindingFlags.Public | BindingFlags.Instance); - - var selectedValues = new List(fieldsCandidates.Length); - var selectedFields = new List(fieldsCandidates.Length); - foreach (var field in fieldsCandidates) - { - var originalValue = field.GetValue(original); - var replicatedValue = field.GetValue(replicated); - if (AreAttributeElementsEqual(originalValue, replicatedValue)) - { - //this field has default value so we skip it - continue; - } - - selectedFields.Add(field); - selectedValues.Add(originalValue); - } - - fields = selectedFields.ToArray(); - return selectedValues.ToArray(); - } - - /// - /// Here we try to match a constructor argument to its value. - /// Since we can't get the values from the assembly, we use some heuristics to get it. - /// a/ we first try to match all the properties on the attributes by name (case insensitive) to the argument - /// b/ if we fail we try to match them by property type, with some smarts about convertions (i,e: can use Guid for string). - /// - private static object[] InitializeConstructorArgs(Type attributeType, Attribute attribute, ParameterInfo[] parameters) - { - - var args = new object[parameters.Length]; - for (var i = 0; i < args.Length; i++) - { - args[i] = GetArgumentValue(attributeType, attribute, parameters[i]); - } - return args; - } - - private static object GetArgumentValue(Type attributeType, Attribute attribute, ParameterInfo parameter) - { - var properties = attributeType.GetProperties(); - //first try to find a property with - foreach (var property in properties) - { - if (property.CanRead == false && property.GetIndexParameters().Length != 0) - { - continue; - } - - if (String.Compare(property.Name, parameter.Name, StringComparison.CurrentCultureIgnoreCase) == 0) - { - return ConvertValue(property.GetValue(attribute, null), parameter.ParameterType); - } - } - - PropertyInfo bestMatch = null; - //now we try to find it by type - foreach (var property in properties) - { - if (property.CanRead == false && property.GetIndexParameters().Length != 0) - { - continue; - } - bestMatch = ReplaceIfBetterMatch(parameter, property, bestMatch); - } - if (bestMatch != null) - { - return ConvertValue(bestMatch.GetValue(attribute, null), parameter.ParameterType); - } - return GetDefaultValueFor(parameter); - } - - /// - /// We have the following rules here. - /// Try to find a matching type, failing that, if the parameter is string, get the first property (under the assumption that - /// we can convert it. - /// - private static PropertyInfo ReplaceIfBetterMatch(ParameterInfo parameterInfo, PropertyInfo propertyInfo, - PropertyInfo bestMatch) - { - var notBestMatch = bestMatch == null || bestMatch.PropertyType != parameterInfo.ParameterType; - if (propertyInfo.PropertyType == parameterInfo.ParameterType && notBestMatch) - { - return propertyInfo; - } - if (parameterInfo.ParameterType == typeof(string) && notBestMatch) - { - return propertyInfo; - } - return bestMatch; - } - - /// - /// Attributes can only accept simple types, so we return null for null, - /// if the value is passed as string we call to string (should help with converting), - /// otherwise, we use the value as is (enums, integer, etc). - /// - private static object ConvertValue(object obj, Type paramType) - { - if (obj == null) - { - return null; - } - if (paramType == typeof(String)) - { - return obj.ToString(); - } - return obj; - } - - private static object GetDefaultValueFor(ParameterInfo parameter) - { - var type = parameter.ParameterType; - if (type == typeof(bool)) - { - return false; - } - if (type.IsEnum) - { - return Enum.ToObject(type, 0); - } - if (type == typeof(char)) - { - return Char.MinValue; - } - if (type.IsPrimitive) - { - return 0; - } - if(type.IsArray && parameter.IsDefined(typeof(ParamArrayAttribute), true)) - { - return Array.CreateInstance(type.GetElementType(), 0); - } - - return null; - } - - private static List GetPropertyCandidates(Type attributeType) - { - var propertyCandidates = new List(); - - foreach (var pi in attributeType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) - { - if (pi.CanRead && pi.CanWrite) - { - propertyCandidates.Add(pi); - } - } - - return propertyCandidates; - } - - private static bool AreAttributeElementsEqual(object first, object second) - { - //we can have either System.Type, string or numeric type - if (first == null) - { - return second == null; - } - - //let's try string - var firstString = first as string; - if (firstString != null) - { - return AreStringsEqual(firstString, second as string); - } - - //by now we should only be left with numeric types - return first.Equals(second); - } - - private static bool AreStringsEqual(string first, string second) - { - Debug.Assert(first != null, "first != null"); - return first.Equals(second, StringComparison.Ordinal); - } - - public bool Equals(AttributeDisassembler other) - { - return !ReferenceEquals(null, other); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) - { - return false; - } - if (ReferenceEquals(this, obj)) - { - return true; - } - if (obj.GetType() != typeof(AttributeDisassembler)) - { - return false; - } - return Equals((AttributeDisassembler)obj); - } - - public override int GetHashCode() - { - return GetType().GetHashCode(); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributesToAvoidReplicating.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributesToAvoidReplicating.cs index 98ef9d5a..46615846 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributesToAvoidReplicating.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/AttributesToAvoidReplicating.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,29 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; - using Telerik.JustMock.Core; - /// - /// A list of attributes that must not be replicated when building a proxy. JustMock - /// tries to copy all attributes from the types and methods being proxied, but that is - /// not always a good idea for every type of attribute. Add additional attributes - /// to this list that prevent the proxy from working correctly. - /// - /// - /// .Add(typeof(ServiceContractAttribute)); - /// -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public static class AttributesToAvoidReplicating + internal static class AttributesToAvoidReplicating { private static readonly object lockObject = new object(); - private static readonly IList attributes; + private static IList attributes; static AttributesToAvoidReplicating() { @@ -42,46 +31,40 @@ static AttributesToAvoidReplicating() { typeof(System.Runtime.InteropServices.ComImportAttribute), typeof(System.Runtime.InteropServices.MarshalAsAttribute), -#if !DOTNET35 typeof(System.Runtime.InteropServices.TypeIdentifierAttribute), -#endif -#if FEATURE_SECURITY_PERMISSIONS +#pragma warning disable SYSLIB0003 typeof(System.Security.Permissions.SecurityAttribute), -#endif +#pragma warning restore SYSLIB0003 }; } + internal static void Add(Type attribute) + { + lock (lockObject) + { + attributes.Add(attribute); + } + } - public static void Add(Type attribute) - - { - ProfilerInterceptor.GuardInternal(() => - { - if (attributes.Contains(attribute) == false) - { - attributes.Add(attribute); - } - }); - } - - /// - /// Add an attribute type that must not be replicated when building a proxy. - /// - /// - public static void Add() + internal static void Add() { - ProfilerInterceptor.GuardInternal(() => Add(typeof(T))); - } + Add(typeof(T)); + } - internal static bool Contains(Type type) + internal static bool Contains(Type attribute) { - return attributes.Any(attr => attr.IsAssignableFrom(type)); - } + lock (lockObject) + { + return attributes.Any(attr => attr.IsAssignableFrom(attribute)); + } + } internal static bool ShouldAvoid(Type attribute) { - return attributes.Any(attr => attr.GetTypeInfo().IsAssignableFrom(attribute.GetTypeInfo())); + lock (lockObject) + { + return attributes.Any(attr => attr.IsAssignableFrom(attribute)); + } } } -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseClassProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseClassProxyGenerator.cs new file mode 100644 index 00000000..a722583e --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseClassProxyGenerator.cs @@ -0,0 +1,219 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + + internal abstract class BaseClassProxyGenerator : BaseProxyGenerator + { + protected BaseClassProxyGenerator(ModuleScope scope, Type targetType, Type[] interfaces, ProxyGenerationOptions options) + : base(scope, targetType, interfaces, options) + { + EnsureDoesNotImplementIProxyTargetAccessor(targetType, nameof(targetType)); + } + + protected abstract FieldReference TargetField { get; } + +#if FEATURE_SERIALIZATION + protected abstract SerializableContributor GetSerializableContributor(); +#endif + + protected abstract CompositeTypeContributor GetProxyTargetContributor(INamingScope namingScope); + + protected abstract ProxyTargetAccessorContributor GetProxyTargetAccessorContributor(); + + protected sealed override Type GenerateType(string name, INamingScope namingScope) + { + IEnumerable contributors; + var allInterfaces = GetTypeImplementerMapping(out contributors, namingScope); + + var model = new MetaType(); + // Collect methods + foreach (var contributor in contributors) + { + contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); + } + ProxyGenerationOptions.Hook.MethodsInspected(); + + var emitter = BuildClassEmitter(name, targetType, allInterfaces); + + CreateFields(emitter); + CreateTypeAttributes(emitter); + + // Constructor + var cctor = GenerateStaticConstructor(emitter); + + var constructorArguments = new List(); + + if (TargetField != null) + { + constructorArguments.Add(TargetField); + } + + foreach (var contributor in contributors) + { + contributor.Generate(emitter); + + // TODO: redo it + if (contributor is MixinContributor mixinContributor) + { + constructorArguments.AddRange(mixinContributor.Fields); + } + } + + // constructor arguments + var interceptorsField = emitter.GetField("__interceptors"); + constructorArguments.Add(interceptorsField); + var selector = emitter.GetField("__selector"); + if (selector != null) + { + constructorArguments.Add(selector); + } + + GenerateConstructors(emitter, targetType, constructorArguments.ToArray()); + GenerateParameterlessConstructor(emitter, targetType, interceptorsField); + + // Complete type initializer code body + CompleteInitCacheMethod(cctor.CodeBuilder); + + // non-inheritable attributes from proxied type + var nonInheritableAttributesContributor = new NonInheritableAttributesContributor(targetType); + nonInheritableAttributesContributor.Generate(emitter); + + // Crosses fingers and build type + + var proxyType = emitter.BuildType(); + InitializeStaticFields(proxyType); + return proxyType; + } + + private IEnumerable GetTypeImplementerMapping(out IEnumerable contributors, INamingScope namingScope) + { + var contributorsList = new List(capacity: 5); + var targetInterfaces = targetType.GetAllInterfaces(); + var typeImplementerMapping = new Dictionary(); + + // Order of interface precedence: + + // 1. first target + // target is not an interface so we do nothing + var targetContributor = GetProxyTargetContributor(namingScope); + contributorsList.Add(targetContributor); + + // 2. then mixins + if (ProxyGenerationOptions.HasMixins) + { + var mixinContributor = new MixinContributor(namingScope, false) { Logger = Logger }; + contributorsList.Add(mixinContributor); + + foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces) + { + if (targetInterfaces.Contains(mixinInterface)) + { + // OK, so the target implements this interface. We now do one of two things: + if (interfaces.Contains(mixinInterface) && + typeImplementerMapping.ContainsKey(mixinInterface) == false) + { + AddMappingNoCheck(mixinInterface, targetContributor, typeImplementerMapping); + targetContributor.AddInterfaceToProxy(mixinInterface); + } + // we do not intercept the interface + mixinContributor.AddEmptyInterface(mixinInterface); + } + else + { + if (!typeImplementerMapping.ContainsKey(mixinInterface)) + { + mixinContributor.AddInterfaceToProxy(mixinInterface); + AddMappingNoCheck(mixinInterface, mixinContributor, typeImplementerMapping); + } + } + } + } + + // 3. then additional interfaces + if (interfaces.Length > 0) + { + var additionalInterfacesContributor = new InterfaceProxyWithoutTargetContributor(namingScope, (c, m) => NullExpression.Instance) { Logger = Logger }; + contributorsList.Add(additionalInterfacesContributor); + + foreach (var @interface in interfaces) + { + if (targetInterfaces.Contains(@interface)) + { + if (typeImplementerMapping.ContainsKey(@interface)) + { + continue; + } + + // we intercept the interface, and forward calls to the target type + AddMappingNoCheck(@interface, targetContributor, typeImplementerMapping); + targetContributor.AddInterfaceToProxy(@interface); + } + else if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface) == false) + { + additionalInterfacesContributor.AddInterfaceToProxy(@interface); + AddMapping(@interface, additionalInterfacesContributor, typeImplementerMapping); + } + } + } + + // 4. plus special interfaces + +#if FEATURE_SERIALIZATION + if (targetType.IsSerializable) + { + var serializableContributor = GetSerializableContributor(); + contributorsList.Add(serializableContributor); + AddMappingForISerializable(typeImplementerMapping, serializableContributor); + } +#endif + + var proxyTargetAccessorContributor = GetProxyTargetAccessorContributor(); + contributorsList.Add(proxyTargetAccessorContributor); + try + { + AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyTargetAccessorContributor, typeImplementerMapping); + } + catch (ArgumentException) + { + HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces); + } + + contributors = contributorsList; + return typeImplementerMapping.Keys; + } + + private void EnsureDoesNotImplementIProxyTargetAccessor(Type type, string name) + { + if (!typeof(IProxyTargetAccessor).IsAssignableFrom(type)) + { + return; + } + var message = + string.Format( + "Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?", + typeof(IProxyTargetAccessor)); + throw new ArgumentException(message, name); + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseInterfaceProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseInterfaceProxyGenerator.cs new file mode 100644 index 00000000..28b5e498 --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseInterfaceProxyGenerator.cs @@ -0,0 +1,296 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; +#if FEATURE_SERIALIZATION + using System.Xml.Serialization; +#endif + + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + + internal abstract class BaseInterfaceProxyGenerator : BaseProxyGenerator + { + protected readonly Type proxyTargetType; + + protected FieldReference targetField; + + protected BaseInterfaceProxyGenerator(ModuleScope scope, Type targetType, Type[] interfaces, + Type proxyTargetType, ProxyGenerationOptions options) + : base(scope, targetType, interfaces, options) + { + CheckNotGenericTypeDefinition(proxyTargetType, nameof(proxyTargetType)); + EnsureValidBaseType(ProxyGenerationOptions.BaseTypeForInterfaceProxy); + + this.proxyTargetType = proxyTargetType; + } + + protected abstract bool AllowChangeTarget { get; } + + protected abstract string GeneratorType { get; } + + protected abstract CompositeTypeContributor GetProxyTargetContributor(Type proxyTargetType, INamingScope namingScope); + + protected abstract ProxyTargetAccessorContributor GetProxyTargetAccessorContributor(); + + protected abstract void AddMappingForAdditionalInterfaces(CompositeTypeContributor contributor, Type[] proxiedInterfaces, + IDictionary typeImplementerMapping, + ICollection targetInterfaces); + + protected virtual ITypeContributor AddMappingForTargetType(IDictionary typeImplementerMapping, + Type proxyTargetType, ICollection targetInterfaces, + INamingScope namingScope) + { + var contributor = GetProxyTargetContributor(proxyTargetType, namingScope); + var proxiedInterfaces = targetType.GetAllInterfaces(); + foreach (var @interface in proxiedInterfaces) + { + contributor.AddInterfaceToProxy(@interface); + AddMappingNoCheck(@interface, contributor, typeImplementerMapping); + } + + AddMappingForAdditionalInterfaces(contributor, proxiedInterfaces, typeImplementerMapping, targetInterfaces); + return contributor; + } + +#if FEATURE_SERIALIZATION + protected override void CreateTypeAttributes(ClassEmitter emitter) + { + base.CreateTypeAttributes(emitter); + emitter.DefineCustomAttribute(); + } +#endif + + protected override CacheKey GetCacheKey() + { + return new CacheKey(proxyTargetType, targetType, interfaces, ProxyGenerationOptions); + } + + protected override Type GenerateType(string typeName, INamingScope namingScope) + { + IEnumerable contributors; + var allInterfaces = GetTypeImplementerMapping(proxyTargetType, out contributors, namingScope); + + var model = new MetaType(); + // Collect methods + foreach (var contributor in contributors) + { + contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); + } + + ProxyGenerationOptions.Hook.MethodsInspected(); + + ClassEmitter emitter; + FieldReference interceptorsField; + var baseType = Init(typeName, out emitter, proxyTargetType, out interceptorsField, allInterfaces); + + // Constructor + + var cctor = GenerateStaticConstructor(emitter); + var ctorArguments = new List(); + + foreach (var contributor in contributors) + { + contributor.Generate(emitter); + + // TODO: redo it + if (contributor is MixinContributor) + { + ctorArguments.AddRange((contributor as MixinContributor).Fields); + } + } + + ctorArguments.Add(interceptorsField); + ctorArguments.Add(targetField); + var selector = emitter.GetField("__selector"); + if (selector != null) + { + ctorArguments.Add(selector); + } + + GenerateConstructors(emitter, baseType, ctorArguments.ToArray()); + + // Complete type initializer code body + CompleteInitCacheMethod(cctor.CodeBuilder); + + // non-inheritable attributes from proxied type + var nonInheritableAttributesContributor = new NonInheritableAttributesContributor(targetType); + nonInheritableAttributesContributor.Generate(emitter); + + // Crosses fingers and build type + var generatedType = emitter.BuildType(); + + InitializeStaticFields(generatedType); + return generatedType; + } + + protected virtual InterfaceProxyWithoutTargetContributor GetContributorForAdditionalInterfaces( + INamingScope namingScope) + { + return new InterfaceProxyWithoutTargetContributor(namingScope, (c, m) => NullExpression.Instance) { Logger = Logger }; + } + + protected virtual IEnumerable GetTypeImplementerMapping(Type proxyTargetType, + out IEnumerable contributors, + INamingScope namingScope) + { + var contributorsList = new List(capacity: 5); + var targetInterfaces = proxyTargetType.GetAllInterfaces(); + var typeImplementerMapping = new Dictionary(); + + // Order of interface precedence: + // 1. first target + var targetContributor = AddMappingForTargetType(typeImplementerMapping, proxyTargetType, targetInterfaces, namingScope); + contributorsList.Add(targetContributor); + + // 2. then mixins + if (ProxyGenerationOptions.HasMixins) + { + var mixinContributor = new MixinContributor(namingScope, AllowChangeTarget) { Logger = Logger }; + contributorsList.Add(mixinContributor); + + foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces) + { + if (targetInterfaces.Contains(mixinInterface)) + { + // OK, so the target implements this interface. We now do one of two things: + if (interfaces.Contains(mixinInterface)) + { + // we intercept the interface, and forward calls to the target type + AddMapping(mixinInterface, targetContributor, typeImplementerMapping); + } + // we do not intercept the interface + mixinContributor.AddEmptyInterface(mixinInterface); + } + else + { + if (!typeImplementerMapping.ContainsKey(mixinInterface)) + { + mixinContributor.AddInterfaceToProxy(mixinInterface); + typeImplementerMapping.Add(mixinInterface, mixinContributor); + } + } + } + } + + // 3. then additional interfaces + if (interfaces.Length > 0) + { + var additionalInterfacesContributor = GetContributorForAdditionalInterfaces(namingScope); + contributorsList.Add(additionalInterfacesContributor); + + foreach (var @interface in interfaces) + { + if (typeImplementerMapping.ContainsKey(@interface)) + { + continue; + } + if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface)) + { + continue; + } + + additionalInterfacesContributor.AddInterfaceToProxy(@interface); + AddMappingNoCheck(@interface, additionalInterfacesContributor, typeImplementerMapping); + } + } + + // 4. plus special interfaces + +#if FEATURE_SERIALIZATION + var serializableContributor = new InterfaceProxySerializableContributor(targetType, GeneratorType, interfaces); + contributorsList.Add(serializableContributor); + AddMappingForISerializable(typeImplementerMapping, serializableContributor); +#endif + + var proxyTargetAccessorContributor = GetProxyTargetAccessorContributor(); + contributorsList.Add(proxyTargetAccessorContributor); + try + { + AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyTargetAccessorContributor, typeImplementerMapping); + } + catch (ArgumentException) + { + HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces); + } + + contributors = contributorsList; + return typeImplementerMapping.Keys; + } + + protected virtual Type Init(string typeName, out ClassEmitter emitter, Type proxyTargetType, + out FieldReference interceptorsField, IEnumerable allInterfaces) + { + var baseType = ProxyGenerationOptions.BaseTypeForInterfaceProxy; + + emitter = BuildClassEmitter(typeName, baseType, allInterfaces); + + CreateFields(emitter, proxyTargetType); + CreateTypeAttributes(emitter); + + interceptorsField = emitter.GetField("__interceptors"); + return baseType; + } + + private void CreateFields(ClassEmitter emitter, Type proxyTargetType) + { + base.CreateFields(emitter); + targetField = emitter.CreateField("__target", proxyTargetType); +#if FEATURE_SERIALIZATION + emitter.DefineCustomAttributeFor(targetField); +#endif + } + + private void EnsureValidBaseType(Type type) + { + if (type == null) + { + throw new ArgumentException( + "Base type for proxy is null reference. Please set it to System.Object or some other valid type."); + } + + if (!type.IsClass) + { + ThrowInvalidBaseType(type, "it is not a class type"); + } + + if (type.IsSealed) + { + ThrowInvalidBaseType(type, "it is sealed"); + } + + var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + null, Type.EmptyTypes, null); + + if (constructor == null || constructor.IsPrivate) + { + ThrowInvalidBaseType(type, "it does not have accessible parameterless constructor"); + } + } + + private void ThrowInvalidBaseType(Type type, string doesNotHaveAccessibleParameterlessConstructor) + { + var format = + "Type {0} is not valid base type for interface proxy, because {1}. Only a non-sealed class with non-private default constructor can be used as base type for interface proxy. Please use some other valid type."; + throw new ArgumentException(string.Format(format, type, doesNotHaveAccessibleParameterlessConstructor)); + } + } +} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseProxyGenerator.cs index e0d29140..4ed0b549 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseProxyGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/BaseProxyGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -27,32 +27,31 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using Telerik.JustMock.Core.Castle.Core.Logging; using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; - using Telerik.JustMock.Core.Castle.Core.Internal; -#if NETCORE - using Debug = Telerik.JustMock.Diagnostics.JMDebug; -#else -using Debug = System.Diagnostics.Debug; -#endif - - /// - /// Base class that exposes the common functionalities - /// to proxy generation. - /// - internal abstract class BaseProxyGenerator + /// + /// Base class that exposes the common functionalities + /// to proxy generation. + /// + internal abstract class BaseProxyGenerator { protected readonly Type targetType; + protected readonly Type[] interfaces; private readonly ModuleScope scope; private ILogger logger = NullLogger.Instance; private ProxyGenerationOptions proxyGenerationOptions; - protected BaseProxyGenerator(ModuleScope scope, Type targetType) + protected BaseProxyGenerator(ModuleScope scope, Type targetType, Type[] interfaces, ProxyGenerationOptions proxyGenerationOptions) { + CheckNotGenericTypeDefinition(targetType, nameof(targetType)); + CheckNotGenericTypeDefinitions(interfaces, nameof(interfaces)); + this.scope = scope; this.targetType = targetType; + this.interfaces = TypeUtil.GetAllInterfaces(interfaces); + this.proxyGenerationOptions = proxyGenerationOptions; + this.proxyGenerationOptions.Initialize(); } public ILogger Logger @@ -63,22 +62,7 @@ public ILogger Logger protected ProxyGenerationOptions ProxyGenerationOptions { - get - { - if (proxyGenerationOptions == null) - { - throw new InvalidOperationException("ProxyGenerationOptions must be set before being retrieved."); - } - return proxyGenerationOptions; - } - set - { - if (proxyGenerationOptions != null) - { - throw new InvalidOperationException("ProxyGenerationOptions can only be set once."); - } - proxyGenerationOptions = value; - } + get { return proxyGenerationOptions; } } protected ModuleScope Scope @@ -86,11 +70,38 @@ protected ModuleScope Scope get { return scope; } } + public Type GetProxyType() + { + bool notFoundInTypeCache = false; + + var proxyType = Scope.TypeCache.GetOrAdd(GetCacheKey(), cacheKey => + { + notFoundInTypeCache = true; + Logger.DebugFormat("No cached proxy type was found for target type {0}.", targetType.FullName); + + EnsureOptionsOverrideEqualsAndGetHashCode(); + + var name = Scope.NamingScope.GetUniqueName("Castle.Proxies." + targetType.Name + "Proxy"); + return GenerateType(name, Scope.NamingScope.SafeSubScope()); + }); + + if (!notFoundInTypeCache) + { + Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", proxyType.FullName, targetType.FullName); + } + + return proxyType; + } + + protected abstract CacheKey GetCacheKey(); + + protected abstract Type GenerateType(string name, INamingScope namingScope); + protected void AddMapping(Type @interface, ITypeContributor implementer, IDictionary mapping) { Debug.Assert(implementer != null, "implementer != null"); Debug.Assert(@interface != null, "@interface != null"); - Debug.Assert(@interface.GetTypeInfo().IsInterface, "@interface.IsInterface"); + Debug.Assert(@interface.IsInterface, "@interface.IsInterface"); if (!mapping.ContainsKey(@interface)) { @@ -109,31 +120,23 @@ protected void AddMappingForISerializable(IDictionary ty /// /// It is safe to add mapping (no mapping for the interface exists) /// - /// - /// - /// protected void AddMappingNoCheck(Type @interface, ITypeContributor implementer, IDictionary mapping) { mapping.Add(@interface, implementer); } - protected void AddToCache(CacheKey key, Type type) - { - scope.RegisterInCache(key, type); - } - protected virtual ClassEmitter BuildClassEmitter(string typeName, Type parentType, IEnumerable interfaces) { - CheckNotGenericTypeDefinition(parentType, "parentType"); - CheckNotGenericTypeDefinitions(interfaces, "interfaces"); + CheckNotGenericTypeDefinition(parentType, nameof(parentType)); + CheckNotGenericTypeDefinitions(interfaces, nameof(interfaces)); return new ClassEmitter(Scope, typeName, parentType, interfaces); } protected void CheckNotGenericTypeDefinition(Type type, string argumentName) { - if (type != null && type.GetTypeInfo().IsGenericTypeDefinition) + if (type != null && type.IsGenericTypeDefinition) { throw new ArgumentException("Type cannot be a generic type definition. Type: " + type.FullName, argumentName); } @@ -151,7 +154,7 @@ protected void CheckNotGenericTypeDefinitions(IEnumerable types, string ar } } - protected void CompleteInitCacheMethod(ConstructorCodeBuilder constCodeBuilder) + protected void CompleteInitCacheMethod(CodeBuilder constCodeBuilder) { constCodeBuilder.AddStatement(new ReturnStatement()); } @@ -189,22 +192,22 @@ protected void CreateSelectorField(ClassEmitter emitter) protected virtual void CreateTypeAttributes(ClassEmitter emitter) { - emitter.AddCustomAttributes(ProxyGenerationOptions); + emitter.AddCustomAttributes(ProxyGenerationOptions.AdditionalAttributes); #if FEATURE_SERIALIZATION emitter.DefineCustomAttribute(new object[] { targetType }); #endif } - protected void EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions options) + protected void EnsureOptionsOverrideEqualsAndGetHashCode() { if (Logger.IsWarnEnabled) { // Check the proxy generation hook - if (!OverridesEqualsAndGetHashCode(options.Hook.GetType())) + if (!OverridesEqualsAndGetHashCode(ProxyGenerationOptions.Hook.GetType())) { Logger.WarnFormat("The IProxyGenerationHook type {0} does not override both Equals and GetHashCode. " + "If these are not correctly overridden caching will fail to work causing performance problems.", - options.Hook.GetType().FullName); + ProxyGenerationOptions.Hook.GetType().FullName); } // Interceptor selectors no longer need to override Equals and GetHashCode @@ -213,17 +216,17 @@ protected void EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseConstructor, params FieldReference[] fields) - { - GenerateConstructor(emitter, baseConstructor, ProxyConstructorImplementation.CallBase, fields); - } + { + GenerateConstructor(emitter, baseConstructor, ProxyConstructorImplementation.CallBase, fields); + } - protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseConstructor, - ProxyConstructorImplementation impl, params FieldReference[] fields) - { - if (impl == ProxyConstructorImplementation.SkipConstructor) - return; + protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseConstructor, + ProxyConstructorImplementation impl, params FieldReference[] fields) + { + if (impl == ProxyConstructorImplementation.SkipConstructor) + return; - ArgumentReference[] args; + ArgumentReference[] args; ParameterInfo[] baseConstructorParams = null; if (baseConstructor != null) @@ -239,8 +242,8 @@ protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseCon for (var i = offset; i < offset + baseConstructorParams.Length; i++) { var paramInfo = baseConstructorParams[i - offset]; - args[i] = new ArgumentReference(paramInfo.ParameterType, paramInfo.DefaultValue); - } + args[i] = new ArgumentReference(paramInfo.ParameterType, paramInfo.DefaultValue); + } } else { @@ -255,38 +258,38 @@ protected void GenerateConstructor(ClassEmitter emitter, ConstructorInfo baseCon var constructor = emitter.CreateConstructor(args); if (baseConstructorParams != null && baseConstructorParams.Length != 0) { - var last = baseConstructorParams.Last(); - if (last.ParameterType.IsArray && last.IsDefined(typeof(ParamArrayAttribute))) - { - var parameter = constructor.ConstructorBuilder.DefineParameter(args.Length, ParameterAttributes.None, last.Name); - var builder = AttributeUtil.CreateBuilder(); - parameter.SetCustomAttribute(builder); - } - } + var last = baseConstructorParams.Last(); + if (last.ParameterType.IsArray && last.IsDefined(typeof(ParamArrayAttribute))) + { + var parameter = constructor.ConstructorBuilder.DefineParameter(args.Length, ParameterAttributes.None, last.Name); + var builder = AttributeUtil.CreateBuilder(); + parameter.SetCustomAttribute(builder); + } + } for (var i = 0; i < fields.Length; i++) { - constructor.CodeBuilder.AddStatement(new AssignStatement(fields[i], args[i].ToExpression())); + constructor.CodeBuilder.AddStatement(new AssignStatement(fields[i], args[i])); } - // Invoke base constructor - - if (impl == ProxyConstructorImplementation.CallBase) - { - if (baseConstructor != null) - { - Debug.Assert(baseConstructorParams != null); - - var slice = new ArgumentReference[baseConstructorParams.Length]; - Array.Copy(args, fields.Length, slice, 0, baseConstructorParams.Length); + // Invoke base constructor - constructor.CodeBuilder.InvokeBaseConstructor(baseConstructor, slice); - } - else - { - constructor.CodeBuilder.InvokeBaseConstructor(); - } - } + if (impl == ProxyConstructorImplementation.CallBase) + { + if (baseConstructor != null) + { + Debug.Assert(baseConstructorParams != null); + + var slice = new ArgumentReference[baseConstructorParams.Length]; + Array.Copy(args, fields.Length, slice, 0, baseConstructorParams.Length); + + constructor.CodeBuilder.AddStatement(new ConstructorInvocationStatement(baseConstructor, slice)); + } + else + { + constructor.CodeBuilder.AddStatement(new ConstructorInvocationStatement(emitter.BaseType)); + } + } constructor.CodeBuilder.AddStatement(new ReturnStatement()); } @@ -296,25 +299,25 @@ protected void GenerateConstructors(ClassEmitter emitter, Type baseType, params var constructors = baseType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - var ctorGenerationHook = (ProxyGenerationOptions.Hook as IConstructorGenerationHook) ?? AllMethodsHook.Instance; - bool defaultCtorConsidered = false; - foreach (var constructor in constructors) - { - if (constructor.GetParameters().Length == 0) - defaultCtorConsidered = true; + var ctorGenerationHook = (ProxyGenerationOptions.Hook as IConstructorGenerationHook) ?? AllMethodsHook.Instance; + bool defaultCtorConsidered = false; + foreach (var constructor in constructors) + { + if (constructor.GetParameters().Length == 0) + defaultCtorConsidered = true; - bool ctorVisible = IsConstructorVisible(constructor); - var analysis = new ConstructorImplementationAnalysis(ctorVisible); - var impl = ctorGenerationHook.GetConstructorImplementation(constructor, analysis); + bool ctorVisible = IsConstructorVisible(constructor); + var analysis = new ConstructorImplementationAnalysis(ctorVisible); + var impl = ctorGenerationHook.GetConstructorImplementation(constructor, analysis); - GenerateConstructor(emitter, constructor, impl, fields); - } + GenerateConstructor(emitter, constructor, impl, fields); + } - if (!defaultCtorConsidered) - { - GenerateConstructor(emitter, null, ctorGenerationHook.DefaultConstructorImplementation, fields); - } - } + if (!defaultCtorConsidered) + { + GenerateConstructor(emitter, null, ctorGenerationHook.DefaultConstructorImplementation, fields); + } + } /// /// Generates a parameters constructor that initializes the proxy @@ -347,11 +350,11 @@ protected void GenerateParameterlessConstructor(ClassEmitter emitter, Type baseC constructor.CodeBuilder.AddStatement(new AssignStatement(interceptorField, new NewArrayExpression(1, typeof(IInterceptor)))); constructor.CodeBuilder.AddStatement( - new AssignArrayStatement(interceptorField, 0, new NewInstanceExpression(typeof(StandardInterceptor), new Type[0]))); + new AssignArrayStatement(interceptorField, 0, new NewInstanceExpression(typeof(StandardInterceptor)))); // Invoke base constructor - constructor.CodeBuilder.InvokeBaseConstructor(defaultConstructor); + constructor.CodeBuilder.AddStatement(new ConstructorInvocationStatement(defaultConstructor)); constructor.CodeBuilder.AddStatement(new ReturnStatement()); } @@ -361,13 +364,7 @@ protected ConstructorEmitter GenerateStaticConstructor(ClassEmitter emitter) return emitter.CreateTypeConstructor(); } - protected Type GetFromCache(CacheKey key) - { - return scope.GetFromCache(key); - } - - protected void HandleExplicitlyPassedProxyTargetAccessor(ICollection targetInterfaces, - ICollection additionalInterfaces) + protected void HandleExplicitlyPassedProxyTargetAccessor(ICollection targetInterfaces) { var interfaceName = typeof(IProxyTargetAccessor).ToString(); //ok, let's determine who tried to sneak the IProxyTargetAccessor in... @@ -378,6 +375,7 @@ protected void HandleExplicitlyPassedProxyTargetAccessor(ICollection targe string.Format( "Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?", interfaceName); + throw new InvalidOperationException("This is a DynamicProxy2 error: " + message); } else if (ProxyGenerationOptions.MixinData.ContainsMixin(typeof(IProxyTargetAccessor))) { @@ -386,21 +384,23 @@ protected void HandleExplicitlyPassedProxyTargetAccessor(ICollection targe string.Format( "Mixin type {0} implements {1} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to mix in an existing proxy?", mixinType.Name, interfaceName); + throw new InvalidOperationException("This is a DynamicProxy2 error: " + message); } - else if (additionalInterfaces.Contains(typeof(IProxyTargetAccessor))) + else if (interfaces.Contains(typeof(IProxyTargetAccessor))) { message = string.Format( "You passed {0} as one of additional interfaces to proxy which is a DynamicProxy infrastructure interface and is implemented by every proxy anyway. Please remove it from the list of additional interfaces to proxy.", interfaceName); + throw new InvalidOperationException("This is a DynamicProxy2 error: " + message); } else { // this can technically never happen message = string.Format("It looks like we have a bug with regards to how we handle {0}. Please report it.", interfaceName); + throw new DynamicProxyException(message); } - throw new ProxyGenerationException("This is a DynamicProxy2 error: " + message); } protected void InitializeStaticFields(Type builtType) @@ -408,43 +408,6 @@ protected void InitializeStaticFields(Type builtType) builtType.SetStaticField("proxyGenerationOptions", BindingFlags.NonPublic, ProxyGenerationOptions); } - protected Type ObtainProxyType(CacheKey cacheKey, Func factory) - { - Type cacheType; - using (var locker = Scope.Lock.ForReading()) - { - cacheType = GetFromCache(cacheKey); - if (cacheType != null) - { - Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", cacheType.FullName, targetType.FullName); - return cacheType; - } - } - - // This is to avoid generating duplicate types under heavy multithreaded load. - using (var locker = Scope.Lock.ForWriting()) - { - // Only one thread at a time may enter a write lock. - // See if an earlier lock holder populated the cache. - cacheType = GetFromCache(cacheKey); - if (cacheType != null) - { - Logger.DebugFormat("Found cached proxy type {0} for target type {1}.", cacheType.FullName, targetType.FullName); - return cacheType; - } - - // Log details about the cache miss - Logger.DebugFormat("No cached proxy type was found for target type {0}.", targetType.FullName); - EnsureOptionsOverrideEqualsAndGetHashCode(ProxyGenerationOptions); - - var name = Scope.NamingScope.GetUniqueName("Castle.Proxies." + targetType.Name + "Proxy"); - var proxyType = factory.Invoke(name, Scope.NamingScope.SafeSubScope()); - - AddToCache(cacheKey, proxyType); - return proxyType; - } - } - private bool IsConstructorVisible(ConstructorInfo constructor) { return constructor.IsPublic || @@ -470,4 +433,4 @@ private bool OverridesEqualsAndGetHashCode(Type type) return true; } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CacheKey.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CacheKey.cs index a58a78a7..9977ddbb 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CacheKey.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CacheKey.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -49,7 +49,7 @@ public CacheKey(MemberInfo target, Type type, Type[] interfaces, ProxyGeneration /// The interfaces. /// The options. public CacheKey(Type target, Type[] interfaces, ProxyGenerationOptions options) - : this(target.GetTypeInfo(), null, interfaces, options) + : this(target, null, interfaces, options) { } @@ -58,15 +58,15 @@ public override int GetHashCode() var result = target.GetHashCode(); foreach (var inter in interfaces) { - result += 29 + inter.GetHashCode(); + result = 29 * result + inter.GetHashCode(); } if (options != null) { - result = 29*result + options.GetHashCode(); + result = 29 * result + options.GetHashCode(); } if (type != null) { - result = 29*result + type.GetHashCode(); + result = 29 * result + type.GetHashCode(); } return result; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyGenerator.cs index 462023de..b61a97dc 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,194 +16,43 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Collections.Generic; - using System.Linq; using System.Reflection; using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; - internal class ClassProxyGenerator : BaseProxyGenerator + internal sealed class ClassProxyGenerator : BaseClassProxyGenerator { - public ClassProxyGenerator(ModuleScope scope, Type targetType) : base(scope, targetType) + public ClassProxyGenerator(ModuleScope scope, Type targetType, Type[] interfaces, ProxyGenerationOptions options) + : base(scope, targetType, interfaces, options) { - CheckNotGenericTypeDefinition(targetType, "targetType"); - EnsureDoesNotImplementIProxyTargetAccessor(targetType, "targetType"); } - public Type GenerateCode(Type[] interfaces, ProxyGenerationOptions options) - { - // make sure ProxyGenerationOptions is initialized - options.Initialize(); - - interfaces = TypeUtil.GetAllInterfaces(interfaces); - CheckNotGenericTypeDefinitions(interfaces, "interfaces"); - ProxyGenerationOptions = options; - var cacheKey = new CacheKey(targetType, interfaces, options); - return ObtainProxyType(cacheKey, (n, s) => GenerateType(n, interfaces, s)); - } + protected override FieldReference TargetField => null; - protected virtual Type GenerateType(string name, Type[] interfaces, INamingScope namingScope) + protected override CacheKey GetCacheKey() { - IEnumerable contributors; - var implementedInterfaces = GetTypeImplementerMapping(interfaces, out contributors, namingScope); - - var model = new MetaType(); - // Collect methods - foreach (var contributor in contributors) - { - contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); - } - ProxyGenerationOptions.Hook.MethodsInspected(); - - var emitter = BuildClassEmitter(name, targetType, implementedInterfaces); - - CreateFields(emitter); - CreateTypeAttributes(emitter); - - // Constructor - var cctor = GenerateStaticConstructor(emitter); - - var constructorArguments = new List(); - foreach (var contributor in contributors) - { - contributor.Generate(emitter, ProxyGenerationOptions); - - // TODO: redo it - var mixinContributor = contributor as MixinContributor; - if (mixinContributor != null) - { - constructorArguments.AddRange(mixinContributor.Fields); - } - } - - // constructor arguments - var interceptorsField = emitter.GetField("__interceptors"); - constructorArguments.Add(interceptorsField); - var selector = emitter.GetField("__selector"); - if (selector != null) - { - constructorArguments.Add(selector); - } - - GenerateConstructors(emitter, targetType, constructorArguments.ToArray()); - GenerateParameterlessConstructor(emitter, targetType, interceptorsField); - - // Complete type initializer code body - CompleteInitCacheMethod(cctor.CodeBuilder); - - // Crosses fingers and build type - Type proxyType = emitter.BuildType(); - - InitializeStaticFields(proxyType); - return proxyType; + return new CacheKey(targetType, interfaces, ProxyGenerationOptions); } - protected virtual IEnumerable GetTypeImplementerMapping(Type[] interfaces, - out IEnumerable contributors, - INamingScope namingScope) - { - var methodsToSkip = new List(); - var proxyInstance = new ClassProxyInstanceContributor(targetType, methodsToSkip, interfaces, ProxyTypeConstants.Class); - // TODO: the trick with methodsToSkip is not very nice... - var proxyTarget = new ClassProxyTargetContributor(targetType, methodsToSkip, namingScope) { Logger = Logger }; - IDictionary typeImplementerMapping = new Dictionary(); - - // Order of interface precedence: - // 1. first target - // target is not an interface so we do nothing - - var targetInterfaces = targetType.GetAllInterfaces(); - var additionalInterfaces = TypeUtil.GetAllInterfaces(interfaces); - // 2. then mixins - var mixins = new MixinContributor(namingScope, false) { Logger = Logger }; - if (ProxyGenerationOptions.HasMixins) - { - foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces) - { - if (targetInterfaces.Contains(mixinInterface)) - { - // OK, so the target implements this interface. We now do one of two things: - if (additionalInterfaces.Contains(mixinInterface) && typeImplementerMapping.ContainsKey(mixinInterface) == false) - { - AddMappingNoCheck(mixinInterface, proxyTarget, typeImplementerMapping); - proxyTarget.AddInterfaceToProxy(mixinInterface); - } - // we do not intercept the interface - mixins.AddEmptyInterface(mixinInterface); - } - else - { - if (!typeImplementerMapping.ContainsKey(mixinInterface)) - { - mixins.AddInterfaceToProxy(mixinInterface); - AddMappingNoCheck(mixinInterface, mixins, typeImplementerMapping); - } - } - } - } - var additionalInterfacesContributor = new InterfaceProxyWithoutTargetContributor(namingScope, - (c, m) => NullExpression.Instance) - { Logger = Logger }; - // 3. then additional interfaces - foreach (var @interface in additionalInterfaces) - { - if (targetInterfaces.Contains(@interface)) - { - if (typeImplementerMapping.ContainsKey(@interface)) - { - continue; - } - - // we intercept the interface, and forward calls to the target type - AddMappingNoCheck(@interface, proxyTarget, typeImplementerMapping); - proxyTarget.AddInterfaceToProxy(@interface); - } - else if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface) == false) - { - additionalInterfacesContributor.AddInterfaceToProxy(@interface); - AddMapping(@interface, additionalInterfacesContributor, typeImplementerMapping); - } - } - // 4. plus special interfaces #if FEATURE_SERIALIZATION - if (targetType.IsSerializable) - { - AddMappingForISerializable(typeImplementerMapping, proxyInstance); - } + protected override SerializableContributor GetSerializableContributor() + { + return new ClassProxySerializableContributor(targetType, interfaces, ProxyTypeConstants.Class); + } #endif - try - { - AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyInstance, typeImplementerMapping); - } - catch (ArgumentException) - { - HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces, additionalInterfaces); - } - contributors = new List - { - proxyTarget, - mixins, - additionalInterfacesContributor, - proxyInstance - }; - return typeImplementerMapping.Keys; + protected override CompositeTypeContributor GetProxyTargetContributor(INamingScope namingScope) + { + return new ClassProxyTargetContributor(targetType, namingScope) { Logger = Logger }; } - private void EnsureDoesNotImplementIProxyTargetAccessor(Type type, string name) + protected override ProxyTargetAccessorContributor GetProxyTargetAccessorContributor() { - if (!typeof(IProxyTargetAccessor).IsAssignableFrom(type)) - { - return; - } - var message = - string.Format( - "Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?", - typeof(IProxyTargetAccessor)); - throw new ArgumentException(message, name); + return new ProxyTargetAccessorContributor( + getTargetReference: () => SelfReference.Self, + targetType); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyWithTargetGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyWithTargetGenerator.cs index 0984f686..5c78eaf4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyWithTargetGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ClassProxyWithTargetGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Collections.Generic; - using System.Linq; using System.Reflection; + #if FEATURE_SERIALIZATION using System.Xml.Serialization; #endif @@ -25,202 +25,56 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; - internal class ClassProxyWithTargetGenerator : BaseProxyGenerator + internal sealed class ClassProxyWithTargetGenerator : BaseClassProxyGenerator { - private readonly Type[] additionalInterfacesToProxy; + private FieldReference targetField; - public ClassProxyWithTargetGenerator(ModuleScope scope, Type classToProxy, Type[] additionalInterfacesToProxy, + public ClassProxyWithTargetGenerator(ModuleScope scope, Type targetType, Type[] interfaces, ProxyGenerationOptions options) - : base(scope, classToProxy) + : base(scope, targetType, interfaces, options) { - CheckNotGenericTypeDefinition(targetType, "targetType"); - EnsureDoesNotImplementIProxyTargetAccessor(targetType, "targetType"); - CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy"); - - options.Initialize(); - ProxyGenerationOptions = options; - this.additionalInterfacesToProxy = TypeUtil.GetAllInterfaces(additionalInterfacesToProxy); } - public Type GetGeneratedType() + protected override FieldReference TargetField => targetField; + + protected override CacheKey GetCacheKey() { - var cacheKey = new CacheKey(targetType.GetTypeInfo(), targetType, additionalInterfacesToProxy, ProxyGenerationOptions); - return ObtainProxyType(cacheKey, GenerateType); + return new CacheKey(targetType, targetType, interfaces, ProxyGenerationOptions); } - protected virtual IEnumerable GetTypeImplementerMapping(out IEnumerable contributors, - INamingScope namingScope) + protected override void CreateFields(ClassEmitter emitter) { - var methodsToSkip = new List(); - var proxyInstance = new ClassProxyWithTargetInstanceContributor(targetType, methodsToSkip, additionalInterfacesToProxy, - ProxyTypeConstants.ClassWithTarget); - // TODO: the trick with methodsToSkip is not very nice... - var proxyTarget = new ClassProxyWithTargetTargetContributor(targetType, methodsToSkip, namingScope) - { Logger = Logger }; - IDictionary typeImplementerMapping = new Dictionary(); - - // Order of interface precedence: - // 1. first target - // target is not an interface so we do nothing - - var targetInterfaces = targetType.GetAllInterfaces(); - // 2. then mixins - var mixins = new MixinContributor(namingScope, false) { Logger = Logger }; - if (ProxyGenerationOptions.HasMixins) - { - foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces) - { - if (targetInterfaces.Contains(mixinInterface)) - { - // OK, so the target implements this interface. We now do one of two things: - if (additionalInterfacesToProxy.Contains(mixinInterface) && - typeImplementerMapping.ContainsKey(mixinInterface) == false) - { - AddMappingNoCheck(mixinInterface, proxyTarget, typeImplementerMapping); - proxyTarget.AddInterfaceToProxy(mixinInterface); - } - // we do not intercept the interface - mixins.AddEmptyInterface(mixinInterface); - } - else - { - if (!typeImplementerMapping.ContainsKey(mixinInterface)) - { - mixins.AddInterfaceToProxy(mixinInterface); - AddMappingNoCheck(mixinInterface, mixins, typeImplementerMapping); - } - } - } - } - var additionalInterfacesContributor = new InterfaceProxyWithoutTargetContributor(namingScope, - (c, m) => NullExpression.Instance) - { Logger = Logger }; - // 3. then additional interfaces - foreach (var @interface in additionalInterfacesToProxy) - { - if (targetInterfaces.Contains(@interface)) - { - if (typeImplementerMapping.ContainsKey(@interface)) - { - continue; - } + base.CreateFields(emitter); + CreateTargetField(emitter); + } - // we intercept the interface, and forward calls to the target type - AddMappingNoCheck(@interface, proxyTarget, typeImplementerMapping); - proxyTarget.AddInterfaceToProxy(@interface); - } - else if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface) == false) - { - additionalInterfacesContributor.AddInterfaceToProxy(@interface); - AddMapping(@interface, additionalInterfacesContributor, typeImplementerMapping); - } - } - // 4. plus special interfaces #if FEATURE_SERIALIZATION - if (targetType.IsSerializable) - { - AddMappingForISerializable(typeImplementerMapping, proxyInstance); - } -#endif - try - { - AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyInstance, typeImplementerMapping); - } - catch (ArgumentException) - { - HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces, additionalInterfacesToProxy); - } - - contributors = new List - { - proxyTarget, - mixins, - additionalInterfacesContributor, - proxyInstance - }; - return typeImplementerMapping.Keys; + protected override SerializableContributor GetSerializableContributor() + { + return new ClassProxySerializableContributor(targetType, interfaces, ProxyTypeConstants.ClassWithTarget); } +#endif - private FieldReference CreateTargetField(ClassEmitter emitter) + protected override CompositeTypeContributor GetProxyTargetContributor(INamingScope namingScope) { - var targetField = emitter.CreateField("__target", targetType); -#if FEATURE_SERIALIZATION - emitter.DefineCustomAttributeFor(targetField); -#endif - return targetField; + return new ClassProxyWithTargetTargetContributor(targetType, namingScope) { Logger = Logger }; } - private void EnsureDoesNotImplementIProxyTargetAccessor(Type type, string name) + protected override ProxyTargetAccessorContributor GetProxyTargetAccessorContributor() { - if (!typeof(IProxyTargetAccessor).IsAssignableFrom(type)) - { - return; - } - var message = - string.Format( - "Target type for the proxy implements {0} which is a DynamicProxy infrastructure interface and you should never implement it yourself. Are you trying to proxy an existing proxy?", - typeof(IProxyTargetAccessor)); - throw new ArgumentException(message, name); + return new ProxyTargetAccessorContributor( + getTargetReference: () => targetField, + targetType); } - private Type GenerateType(string name, INamingScope namingScope) + private void CreateTargetField(ClassEmitter emitter) { - IEnumerable contributors; - var implementedInterfaces = GetTypeImplementerMapping(out contributors, namingScope); - - var model = new MetaType(); - // Collect methods - foreach (var contributor in contributors) - { - contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); - } - ProxyGenerationOptions.Hook.MethodsInspected(); - - var emitter = BuildClassEmitter(name, targetType, implementedInterfaces); - - CreateFields(emitter); - CreateTypeAttributes(emitter); - - // Constructor - var cctor = GenerateStaticConstructor(emitter); - - var targetField = CreateTargetField(emitter); - var constructorArguments = new List { targetField }; - - foreach (var contributor in contributors) - { - contributor.Generate(emitter, ProxyGenerationOptions); - - // TODO: redo it - if (contributor is MixinContributor) - { - constructorArguments.AddRange((contributor as MixinContributor).Fields); - } - } - - // constructor arguments - var interceptorsField = emitter.GetField("__interceptors"); - constructorArguments.Add(interceptorsField); - var selector = emitter.GetField("__selector"); - if (selector != null) - { - constructorArguments.Add(selector); - } - - GenerateConstructors(emitter, targetType, constructorArguments.ToArray()); - GenerateParameterlessConstructor(emitter, targetType, interceptorsField); - - // Complete type initializer code body - CompleteInitCacheMethod(cctor.CodeBuilder); - - // Crosses fingers and build type - - var proxyType = emitter.BuildType(); - InitializeStaticFields(proxyType); - return proxyType; + targetField = emitter.CreateField("__target", targetType); +#if FEATURE_SERIALIZATION + emitter.DefineCustomAttributeFor(targetField); +#endif } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CompositionInvocationTypeGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CompositionInvocationTypeGenerator.cs index deae716a..61fc3154 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CompositionInvocationTypeGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/CompositionInvocationTypeGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,6 +17,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using System; using System.Reflection; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; @@ -33,7 +34,6 @@ public CompositionInvocationTypeGenerator(Type target, MetaMethod method, Method } protected override ArgumentReference[] GetBaseCtorArguments(Type targetFieldType, - ProxyGenerationOptions proxyGenerationOptions, out ConstructorInfo baseConstructor) { baseConstructor = InvocationMethods.CompositionInvocationConstructor; @@ -54,15 +54,17 @@ protected override Type GetBaseType() protected override FieldReference GetTargetReference() { - return new FieldReference(InvocationMethods.Target); + return new FieldReference(InvocationMethods.CompositionInvocationTarget); } protected override void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters, MethodEmitter invokeMethodOnTarget, Reference targetField) { invokeMethodOnTarget.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression(SelfReference.Self, InvocationMethods.EnsureValidTarget))); + new MethodInvocationExpression( + SelfReference.Self, + InvocationMethods.CompositionInvocationEnsureValidTarget)); + base.ImplementInvokeMethodOnTarget(invocation, parameters, invokeMethodOnTarget, targetField); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerationHook.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerationHook.cs deleted file mode 100644 index 443596bf..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerationHook.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators -{ - using System; - using System.Reflection; - - internal class DelegateProxyGenerationHook : IProxyGenerationHook - { - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) - { - return false; - } - return obj.GetType() == typeof(DelegateProxyGenerationHook); - } - - public override int GetHashCode() - { - return GetType().GetHashCode(); - } - - public void MethodsInspected() - { - } - - public void NonProxyableMemberNotification(Type type, MemberInfo memberInfo) - { - } - - public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo) - { - return methodInfo.Name.Equals("Invoke"); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerator.cs deleted file mode 100644 index d8801821..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateProxyGenerator.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators -{ - using System; - using System.Collections.Generic; - using System.Reflection; -#if FEATURE_SERIALIZATION - using System.Xml.Serialization; -#endif - - using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; - - internal class DelegateProxyGenerator : BaseProxyGenerator - { - public DelegateProxyGenerator(ModuleScope scope, Type delegateType) : base(scope, delegateType) - { - ProxyGenerationOptions = new ProxyGenerationOptions(new DelegateProxyGenerationHook()); - ProxyGenerationOptions.Initialize(); - } - - public Type GetProxyType() - { - var cacheKey = new CacheKey(targetType, null, null); - return ObtainProxyType(cacheKey, GenerateType); - } - - protected virtual IEnumerable GetTypeImplementerMapping(out IEnumerable contributors, - INamingScope namingScope) - { - var methodsToSkip = new List(); - var proxyInstance = new ClassProxyInstanceContributor(targetType, methodsToSkip, Type.EmptyTypes, - ProxyTypeConstants.ClassWithTarget); - var proxyTarget = new DelegateProxyTargetContributor(targetType, namingScope) { Logger = Logger }; - IDictionary typeImplementerMapping = new Dictionary(); - - // Order of interface precedence: - // 1. first target, target is not an interface so we do nothing - // 2. then mixins - we support none so we do nothing - // 3. then additional interfaces - we support none so we do nothing - // 4. plus special interfaces -#if FEATURE_SERIALIZATION - if (targetType.IsSerializable) - { - AddMappingForISerializable(typeImplementerMapping, proxyInstance); - } -#endif - AddMappingNoCheck(typeof(IProxyTargetAccessor), proxyInstance, typeImplementerMapping); - - contributors = new List - { - proxyTarget, - proxyInstance - }; - return typeImplementerMapping.Keys; - } - - private FieldReference CreateTargetField(ClassEmitter emitter) - { - var targetField = emitter.CreateField("__target", targetType); -#if FEATURE_SERIALIZATION - emitter.DefineCustomAttributeFor(targetField); -#endif - return targetField; - } - - private Type GenerateType(string name, INamingScope namingScope) - { - IEnumerable contributors; - var implementedInterfaces = GetTypeImplementerMapping(out contributors, namingScope); - - var model = new MetaType(); - // Collect methods - foreach (var contributor in contributors) - { - contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); - } - ProxyGenerationOptions.Hook.MethodsInspected(); - - var emitter = BuildClassEmitter(name, typeof(object), implementedInterfaces); - - CreateFields(emitter); - CreateTypeAttributes(emitter); - - // Constructor - var cctor = GenerateStaticConstructor(emitter); - - var targetField = CreateTargetField(emitter); - var constructorArguments = new List { targetField }; - - foreach (var contributor in contributors) - { - contributor.Generate(emitter, ProxyGenerationOptions); - } - - // constructor arguments - var interceptorsField = emitter.GetField("__interceptors"); - constructorArguments.Add(interceptorsField); - var selector = emitter.GetField("__selector"); - if (selector != null) - { - constructorArguments.Add(selector); - } - - GenerateConstructor(emitter, null, constructorArguments.ToArray()); - GenerateParameterlessConstructor(emitter, targetType, interceptorsField); - - // Complete type initializer code body - CompleteInitCacheMethod(cctor.CodeBuilder); - - // Crosses fingers and build type - - var proxyType = emitter.BuildType(); - InitializeStaticFields(proxyType); - return proxyType; - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateTypeGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateTypeGenerator.cs similarity index 90% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateTypeGenerator.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateTypeGenerator.cs index 77fcbdda..3ffc375b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/DelegateTypeGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/DelegateTypeGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,12 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Reflection; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; @@ -39,7 +38,7 @@ public DelegateTypeGenerator(MetaMethod method, Type targetType) this.targetType = targetType; } - public AbstractTypeEmitter Generate(ClassEmitter @class, ProxyGenerationOptions options, INamingScope namingScope) + public AbstractTypeEmitter Generate(ClassEmitter @class, INamingScope namingScope) { var emitter = GetEmitter(@class, namingScope); BuildConstructor(emitter); @@ -79,7 +78,8 @@ private AbstractTypeEmitter GetEmitter(ClassEmitter @class, INamingScope namingS uniqueName, typeof(MulticastDelegate), Type.EmptyTypes, - DelegateFlags); + DelegateFlags, + forceUnsigned: @class.InStrongNamedModule == false); @delegate.CopyGenericParametersFromMethod(method.Method); return @delegate; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/AbstractTypeEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/AbstractTypeEmitter.cs index d8c6f332..16398073 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/AbstractTypeEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/AbstractTypeEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -28,30 +28,28 @@ internal abstract class AbstractTypeEmitter private const MethodAttributes defaultAttributes = MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public; - private readonly ConstructorCollection constructors; - private readonly EventCollection events; + private readonly List constructors; + private readonly List events; private readonly IDictionary fields = new Dictionary(StringComparer.OrdinalIgnoreCase); - private readonly MethodCollection methods; + private readonly List methods; - private readonly Dictionary name2GenericType; - private readonly NestedClassCollection nested; - private readonly PropertiesCollection properties; - private readonly TypeBuilder typebuilder; + private readonly List nested; + private readonly List properties; + private readonly TypeBuilder typeBuilder; private GenericTypeParameterBuilder[] genericTypeParams; protected AbstractTypeEmitter(TypeBuilder typeBuilder) { - typebuilder = typeBuilder; - nested = new NestedClassCollection(); - methods = new MethodCollection(); - constructors = new ConstructorCollection(); - properties = new PropertiesCollection(); - events = new EventCollection(); - name2GenericType = new Dictionary(); + this.typeBuilder = typeBuilder; + nested = new List(); + methods = new List(); + constructors = new List(); + properties = new List(); + events = new List(); } public Type BaseType @@ -68,39 +66,34 @@ public Type BaseType public TypeConstructorEmitter ClassConstructor { get; private set; } - public ConstructorCollection Constructors - { - get { return constructors; } - } - public GenericTypeParameterBuilder[] GenericTypeParams { get { return genericTypeParams; } } - public NestedClassCollection Nested - { - get { return nested; } - } - public TypeBuilder TypeBuilder { - get { return typebuilder; } + get { return typeBuilder; } } - public void AddCustomAttributes(ProxyGenerationOptions proxyGenerationOptions) + public void AddCustomAttributes(IEnumerable additionalAttributes) { - foreach (var attribute in proxyGenerationOptions.AdditionalAttributes) + foreach (var attribute in additionalAttributes) { - typebuilder.SetCustomAttribute(attribute.Builder); + typeBuilder.SetCustomAttribute(attribute.Builder); } } + public void AddNestedClass(NestedClassEmitter nestedClass) + { + nested.Add(nestedClass); + } + public virtual Type BuildType() { EnsureBuildersAreInAValidState(); - var type = CreateType(typebuilder); + var type = CreateType(typeBuilder); foreach (var builder in nested) { @@ -115,10 +108,10 @@ public void CopyGenericParametersFromMethod(MethodInfo methodToCopyGenericsFrom) // big sanity check if (genericTypeParams != null) { - throw new ProxyGenerationException("CopyGenericParametersFromMethod: cannot invoke me twice"); + throw new InvalidOperationException("Cannot invoke me twice"); } - SetGenericTypeParameters(GenericUtil.CopyGenericArguments(methodToCopyGenericsFrom, typebuilder, name2GenericType)); + SetGenericTypeParameters(GenericUtil.CopyGenericArguments(methodToCopyGenericsFrom, typeBuilder)); } public ConstructorEmitter CreateConstructor(params ArgumentReference[] arguments) @@ -169,7 +162,7 @@ public FieldReference CreateField(string name, Type fieldType, bool serializable public FieldReference CreateField(string name, Type fieldType, FieldAttributes atts) { - var fieldBuilder = typebuilder.DefineField(name, fieldType, atts); + var fieldBuilder = typeBuilder.DefineField(name, fieldType, atts); var reference = new FieldReference(fieldBuilder); fields[name] = reference; return reference; @@ -227,31 +220,31 @@ public ConstructorEmitter CreateTypeConstructor() public void DefineCustomAttribute(CustomAttributeBuilder attribute) { - typebuilder.SetCustomAttribute(attribute); + typeBuilder.SetCustomAttribute(attribute); } public void DefineCustomAttribute(object[] constructorArguments) where TAttribute : Attribute { var customAttributeInfo = AttributeUtil.CreateInfo(typeof(TAttribute), constructorArguments); - typebuilder.SetCustomAttribute(customAttributeInfo.Builder); + typeBuilder.SetCustomAttribute(customAttributeInfo.Builder); } public void DefineCustomAttribute() where TAttribute : Attribute, new() { var customAttributeInfo = AttributeUtil.CreateInfo(); - typebuilder.SetCustomAttribute(customAttributeInfo.Builder); + typeBuilder.SetCustomAttribute(customAttributeInfo.Builder); } public void DefineCustomAttributeFor(FieldReference field) where TAttribute : Attribute, new() { var customAttributeInfo = AttributeUtil.CreateInfo(); - var fieldbuilder = field.Fieldbuilder; - if (fieldbuilder == null) + var fieldBuilder = field.FieldBuilder; + if (fieldBuilder == null) { throw new ArgumentException( - "Invalid field reference.This reference does not point to field on type being generated", "field"); + "Invalid field reference.This reference does not point to field on type being generated", nameof(field)); } - fieldbuilder.SetCustomAttribute(customAttributeInfo.Builder); + fieldBuilder.SetCustomAttribute(customAttributeInfo.Builder); } public IEnumerable GetAllFields() @@ -271,42 +264,72 @@ public FieldReference GetField(string name) return value; } - public Type GetGenericArgument(String genericArgumentName) + public Type GetClosedParameterType(Type parameter) { - if (name2GenericType.ContainsKey(genericArgumentName)) - return name2GenericType[genericArgumentName].AsType(); + if (parameter.IsGenericType) + { + // ECMA-335 section II.9.4: "The CLI does not support partial instantiation + // of generic types. And generic types shall not appear uninstantiated any- + // where in metadata signature blobs." (And parameters are defined there!) + Debug.Assert(parameter.IsGenericTypeDefinition == false); - return null; - } + var arguments = parameter.GetGenericArguments(); + if (CloseGenericParametersIfAny(arguments)) + { + return parameter.GetGenericTypeDefinition().MakeGenericType(arguments); + } + } - public Type[] GetGenericArgumentsFor(Type genericType) - { - var types = new List(); + if (parameter.IsGenericParameter) + { + return GetGenericArgument(parameter.GenericParameterPosition); + } - foreach (var genType in genericType.GetGenericArguments()) + if (parameter.IsArray) { - if (genType.GetTypeInfo().IsGenericParameter) - { - types.Add(name2GenericType[genType.Name].AsType()); - } - else + var elementType = GetClosedParameterType(parameter.GetElementType()); + int rank = parameter.GetArrayRank(); + return rank == 1 + ? elementType.MakeArrayType() + : elementType.MakeArrayType(rank); + } + + if (parameter.IsByRef) + { + var elementType = GetClosedParameterType(parameter.GetElementType()); + return elementType.MakeByRefType(); + } + + return parameter; + + bool CloseGenericParametersIfAny(Type[] arguments) + { + var hasAnyGenericParameters = false; + for (var i = 0; i < arguments.Length; i++) { - types.Add(genType); + var newType = GetClosedParameterType(arguments[i]); + if (newType != null && !ReferenceEquals(newType, arguments[i])) + { + arguments[i] = newType; + hasAnyGenericParameters = true; + } } + return hasAnyGenericParameters; } + } - return types.ToArray(); + public Type GetGenericArgument(int position) + { + Debug.Assert(0 <= position && position < genericTypeParams.Length); + + return genericTypeParams[position]; } public Type[] GetGenericArgumentsFor(MethodInfo genericMethod) { - var types = new List(); - foreach (var genType in genericMethod.GetGenericArguments()) - { - types.Add(name2GenericType[genType.Name].AsType()); - } + Debug.Assert(genericMethod.GetGenericArguments().Length == genericTypeParams.Length); - return types.ToArray(); + return genericTypeParams; } public void SetGenericTypeParameters(GenericTypeParameterBuilder[] genericTypeParameterBuilders) @@ -316,45 +339,12 @@ public void SetGenericTypeParameters(GenericTypeParameterBuilder[] genericTypePa protected Type CreateType(TypeBuilder type) { - try - { -#if FEATURE_LEGACY_REFLECTION_API - return type.CreateType(); -#else - return type.CreateTypeInfo().AsType(); -#endif - } - catch (BadImageFormatException ex) - { - if (Debugger.IsAttached == false) - { - throw; - } - - if (ex.Message.Contains(@"HRESULT: 0x8007000B") == false) - { - throw; - } - - if (type.IsGenericTypeDefinition == false) - { - throw; - } - - var message = - "This is a DynamicProxy2 error: It looks like you encountered a bug in Visual Studio debugger, " + - "which causes this exception when proxying types with generic methods having constraints on their generic arguments." + - "This code will work just fine without the debugger attached. " + - "If you wish to use debugger you may have to switch to Visual Studio 2010 where this bug was fixed."; - var exception = new ProxyGenerationException(message); - exception.Data.Add("ProxyType", type.ToString()); - throw exception; - } + return type.CreateTypeInfo(); } protected virtual void EnsureBuildersAreInAValidState() { - if (!typebuilder.IsInterface && constructors.Count == 0) + if (!typeBuilder.IsInterface && constructors.Count == 0) { CreateDefaultConstructor(); } @@ -381,4 +371,4 @@ protected virtual void EnsureBuildersAreInAValidState() } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ArgumentsUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ArgumentsUtil.cs index 7e45f723..5a53efc8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ArgumentsUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ArgumentsUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,27 +15,14 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters { using System; - using System.ComponentModel; - using System.Linq; - using System.Reflection; + using System.Linq; + using System.Reflection; using System.Reflection.Emit; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + using Castle.DynamicProxy.Generators.Emitters.SimpleAST; internal abstract class ArgumentsUtil { - public static Expression[] ConvertArgumentReferenceToExpression(ArgumentReference[] args) - { - var expressions = new Expression[args.Length]; - - for (var i = 0; i < args.Length; ++i) - { - expressions[i] = args[i].ToExpression(); - } - - return expressions; - } - public static ArgumentReference[] ConvertToArgumentReference(Type[] args) { var arguments = new ArgumentReference[args.Length]; @@ -60,13 +47,13 @@ public static ArgumentReference[] ConvertToArgumentReference(ParameterInfo[] arg return arguments; } - public static ReferenceExpression[] ConvertToArgumentReferenceExpression(ParameterInfo[] args) + public static IExpression[] ConvertToArgumentReferenceExpression(ParameterInfo[] args) { - var arguments = new ReferenceExpression[args.Length]; + var arguments = new IExpression[args.Length]; for (var i = 0; i < args.Length; ++i) { - arguments[i] = new ReferenceExpression(new ArgumentReference(args[i].ParameterType, i + 1, args[i].Attributes)); + arguments[i] = new ArgumentReference(args[i].ParameterType, i + 1, args[i].Attributes); } return arguments; @@ -116,30 +103,16 @@ public static void InitializeArgumentsByPosition(ArgumentReference[] args, bool } } - [Obsolete] - [EditorBrowsable(EditorBrowsableState.Never)] - public static bool IsAnyByRef(ParameterInfo[] parameters) + public static MethodInfo PointerFromIntPtr() { - for (var i = 0; i < parameters.Length; i++) - { - if (parameters[i].ParameterType.GetTypeInfo().IsByRef) - { - return true; - } - } - return false; + return typeof(IntPtr).GetMethods(BindingFlags.Public | BindingFlags.Static) + .First(m => m.Name == "op_Explicit" && m.ReturnType.IsPointer); } - public static MethodInfo PointerFromIntPtr() - { - return typeof(IntPtr).GetMethods(BindingFlags.Public | BindingFlags.Static) - .First(m => m.Name == "op_Explicit" && m.ReturnType.IsPointer); - } - - public static MethodInfo IntPtrFromPointer() - { - return typeof(IntPtr).GetMethods(BindingFlags.Public | BindingFlags.Static) - .First(m => m.Name == "op_Explicit" && m.GetParameters()[0].ParameterType.IsPointer); - } - } -} \ No newline at end of file + public static MethodInfo IntPtrFromPointer() + { + return typeof(IntPtr).GetMethods(BindingFlags.Public | BindingFlags.Static) + .First(m => m.Name == "op_Explicit" && m.GetParameters()[0].ParameterType.IsPointer); + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ClassEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ClassEmitter.cs index f0b48670..b17aeeca 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ClassEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ClassEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,12 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + internal class ClassEmitter : AbstractTypeEmitter { internal const TypeAttributes DefaultAttributes = @@ -26,21 +29,15 @@ internal class ClassEmitter : AbstractTypeEmitter private readonly ModuleScope moduleScope; - public ClassEmitter(ModuleScope modulescope, String name, Type baseType, IEnumerable interfaces) - : this(modulescope, name, baseType, interfaces, DefaultAttributes, ShouldForceUnsigned()) - { - } - - public ClassEmitter(ModuleScope modulescope, String name, Type baseType, IEnumerable interfaces, - TypeAttributes flags) - : this(modulescope, name, baseType, interfaces, flags, ShouldForceUnsigned()) + public ClassEmitter(ModuleScope moduleScope, string name, Type baseType, IEnumerable interfaces) + : this(moduleScope, name, baseType, interfaces, DefaultAttributes, forceUnsigned: false) { } - public ClassEmitter(ModuleScope modulescope, String name, Type baseType, IEnumerable interfaces, + public ClassEmitter(ModuleScope moduleScope, string name, Type baseType, IEnumerable interfaces, TypeAttributes flags, bool forceUnsigned) - : this(CreateTypeBuilder(modulescope, name, baseType, interfaces, flags, forceUnsigned)) + : this(CreateTypeBuilder(moduleScope, name, baseType, interfaces, flags, forceUnsigned)) { interfaces = InitializeGenericArgumentsFromBases(ref baseType, interfaces); @@ -48,12 +45,19 @@ public ClassEmitter(ModuleScope modulescope, String name, Type baseType, IEnumer { foreach (var inter in interfaces) { - TypeBuilder.AddInterfaceImplementation(inter); + if (inter.IsInterface) + { + TypeBuilder.AddInterfaceImplementation(inter); + } + else + { + Debug.Assert(inter.IsDelegateType()); + } } } TypeBuilder.SetParent(baseType); - moduleScope = modulescope; + this.moduleScope = moduleScope; } public ClassEmitter(TypeBuilder typeBuilder) @@ -74,7 +78,7 @@ internal bool InStrongNamedModule protected virtual IEnumerable InitializeGenericArgumentsFromBases(ref Type baseType, IEnumerable interfaces) { - if (baseType != null && baseType.GetTypeInfo().IsGenericTypeDefinition) + if (baseType != null && baseType.IsGenericTypeDefinition) { throw new NotSupportedException("ClassEmitter does not support open generic base types. Type: " + baseType.FullName); } @@ -86,7 +90,7 @@ protected virtual IEnumerable InitializeGenericArgumentsFromBases(ref Type foreach (var inter in interfaces) { - if (inter.GetTypeInfo().IsGenericTypeDefinition) + if (inter.IsGenericTypeDefinition) { throw new NotSupportedException("ClassEmitter does not support open generic interfaces. Type: " + inter.FullName); } @@ -94,17 +98,12 @@ protected virtual IEnumerable InitializeGenericArgumentsFromBases(ref Type return interfaces; } - private static TypeBuilder CreateTypeBuilder(ModuleScope modulescope, string name, Type baseType, + private static TypeBuilder CreateTypeBuilder(ModuleScope moduleScope, string name, Type baseType, IEnumerable interfaces, TypeAttributes flags, bool forceUnsigned) { var isAssemblySigned = !forceUnsigned && !StrongNameUtil.IsAnyTypeFromUnsignedAssembly(baseType, interfaces); - return modulescope.DefineType(isAssemblySigned, name, flags); - } - - private static bool ShouldForceUnsigned() - { - return StrongNameUtil.CanStrongNameAssembly == false; + return moduleScope.DefineType(isAssemblySigned, name, flags); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilder.cs new file mode 100644 index 00000000..1e7ae38c --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilder.cs @@ -0,0 +1,68 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters +{ + using System; + using System.Collections.Generic; + using System.Reflection.Emit; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; + + internal sealed class CodeBuilder + { + private readonly List locals; + private readonly List statements; + private bool isEmpty; + + public CodeBuilder() + { + statements = new List(); + locals = new List(); + isEmpty = true; + } + + internal bool IsEmpty + { + get { return isEmpty; } + } + + public CodeBuilder AddStatement(IStatement statement) + { + isEmpty = false; + statements.Add(statement); + return this; + } + + public LocalReference DeclareLocal(Type type) + { + var local = new LocalReference(type); + locals.Add(local); + return local; + } + + internal void Generate(ILGenerator il) + { + foreach (var local in locals) + { + local.Generate(il); + } + + foreach (var statement in statements) + { + statement.Emit(il); + } + } + } +} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/AbstractCodeBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/AbstractCodeBuilder.cs deleted file mode 100644 index 46615915..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/AbstractCodeBuilder.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders -{ - using System; - using System.Collections.Generic; - using System.Reflection.Emit; - - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - - internal abstract class AbstractCodeBuilder - { - private readonly ILGenerator generator; - private readonly List ilmarkers; - private readonly List stmts; - private bool isEmpty; - - protected AbstractCodeBuilder(ILGenerator generator) - { - this.generator = generator; - stmts = new List(); - ilmarkers = new List(); - isEmpty = true; - } - - //NOTE: should we make this obsolete if no one is using it? - public /*protected internal*/ ILGenerator Generator - { - get { return generator; } - } - - internal bool IsEmpty - { - get { return isEmpty; } - } - - public AbstractCodeBuilder AddExpression(Expression expression) - { - return AddStatement(new ExpressionStatement(expression)); - } - - public AbstractCodeBuilder AddStatement(Statement stmt) - { - SetNonEmpty(); - stmts.Add(stmt); - return this; - } - - public LocalReference DeclareLocal(Type type) - { - var local = new LocalReference(type); - ilmarkers.Add(local); - return local; - } - - public /*protected internal*/ void SetNonEmpty() - { - isEmpty = false; - } - - internal void Generate(IMemberEmitter member, ILGenerator il) - { - foreach (var local in ilmarkers) - { - local.Generate(il); - } - - foreach (var stmt in stmts) - { - stmt.Emit(member, il); - } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/ConstructorCodeBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/ConstructorCodeBuilder.cs deleted file mode 100644 index a69ecc4d..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/ConstructorCodeBuilder.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders -{ - using System; - using System.Reflection; - using System.Reflection.Emit; - - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - - internal class ConstructorCodeBuilder : AbstractCodeBuilder - { - private readonly Type baseType; - - public ConstructorCodeBuilder(Type baseType, ILGenerator generator) : base(generator) - { - this.baseType = baseType; - } - - public void InvokeBaseConstructor() - { - var type = baseType; - if (type.GetTypeInfo().ContainsGenericParameters) - { - type = type.GetGenericTypeDefinition(); - // need to get generic type definition, otherwise the GetConstructor method might throw NotSupportedException - } - - var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - var baseDefaultCtor = type.GetConstructor(flags, null, new Type[0], null); - - InvokeBaseConstructor(baseDefaultCtor); - } - - public void InvokeBaseConstructor(ConstructorInfo constructor) - { - AddStatement(new ConstructorInvocationStatement(constructor)); - } - - public void InvokeBaseConstructor(ConstructorInfo constructor, params ArgumentReference[] arguments) - { - AddStatement( - new ConstructorInvocationStatement(constructor, - ArgumentsUtil.ConvertArgumentReferenceToExpression(arguments))); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/MethodCodeBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/MethodCodeBuilder.cs deleted file mode 100644 index 21e1c5ee..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/CodeBuilders/MethodCodeBuilder.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders -{ - using System.Reflection.Emit; - - internal class MethodCodeBuilder : AbstractCodeBuilder - { - public MethodCodeBuilder(ILGenerator generator) : base(generator) - { - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorEmitter.cs index 763a515e..afbce7aa 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/ConstructorEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,53 +18,46 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters using System.Reflection; using System.Reflection.Emit; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; internal class ConstructorEmitter : IMemberEmitter { private readonly ConstructorBuilder builder; - private readonly AbstractTypeEmitter maintype; + private readonly CodeBuilder codeBuilder; + private readonly AbstractTypeEmitter mainType; - private ConstructorCodeBuilder constructorCodeBuilder; - - protected internal ConstructorEmitter(AbstractTypeEmitter maintype, ConstructorBuilder builder) + protected internal ConstructorEmitter(AbstractTypeEmitter mainType, ConstructorBuilder builder) { - this.maintype = maintype; + this.mainType = mainType; this.builder = builder; + codeBuilder = new CodeBuilder(); } - internal ConstructorEmitter(AbstractTypeEmitter maintype, params ArgumentReference[] arguments) + internal ConstructorEmitter(AbstractTypeEmitter mainType, params ArgumentReference[] arguments) { - this.maintype = maintype; + this.mainType = mainType; var args = ArgumentsUtil.InitializeAndConvert(arguments); - builder = maintype.TypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, args); - // if we don't copy the parameter attributes, the default binder will fail - // when trying to resolve constructors from the passed argument values. - for (int i = 0; i < args.Length; ++i) - { - var arg = arguments[i]; - var paramBuilder = builder.DefineParameter(i + 1, arg.ParameterAttributes, ""); - if (arg.DefaultValue != DBNull.Value) - paramBuilder.SetConstant(arg.DefaultValue); - } - } - - public virtual ConstructorCodeBuilder CodeBuilder - { - get + builder = mainType.TypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, args); + codeBuilder = new CodeBuilder(); + + // if we don't copy the parameter attributes, the default binder will fail + // when trying to resolve constructors from the passed argument values. + for (int i = 0; i < args.Length; ++i) { - if (constructorCodeBuilder == null) - { - constructorCodeBuilder = new ConstructorCodeBuilder( - maintype.BaseType, builder.GetILGenerator()); - } - return constructorCodeBuilder; + var arg = arguments[i]; + var paramBuilder = builder.DefineParameter(i + 1, arg.ParameterAttributes, "param" + i); + if (arg.DefaultValue != DBNull.Value) + paramBuilder.SetConstant(arg.DefaultValue); } } + public CodeBuilder CodeBuilder + { + get { return codeBuilder; } + } + public ConstructorBuilder ConstructorBuilder { get { return builder; } @@ -84,11 +77,7 @@ private bool ImplementedByRuntime { get { -#if FEATURE_LEGACY_REFLECTION_API - var attributes = builder.GetMethodImplementationFlags(); -#else var attributes = builder.MethodImplementationFlags; -#endif return (attributes & MethodImplAttributes.Runtime) != 0; } } @@ -97,7 +86,7 @@ public virtual void EnsureValidCodeBlock() { if (ImplementedByRuntime == false && CodeBuilder.IsEmpty) { - CodeBuilder.InvokeBaseConstructor(); + CodeBuilder.AddStatement(new ConstructorInvocationStatement(mainType.BaseType)); CodeBuilder.AddStatement(new ReturnStatement()); } } @@ -109,7 +98,7 @@ public virtual void Generate() return; } - CodeBuilder.Generate(this, builder.GetILGenerator()); + CodeBuilder.Generate(builder.GetILGenerator()); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventEmitter.cs index d6cc0bd1..39e35459 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -30,11 +30,11 @@ public EventEmitter(AbstractTypeEmitter typeEmitter, string name, EventAttribute { if (name == null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } this.typeEmitter = typeEmitter; this.type = type; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/GenericUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/GenericUtil.cs index 468633fc..a06859a8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/GenericUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/GenericUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,7 +15,6 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters { using System; - using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; @@ -23,108 +22,29 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters using Telerik.JustMock.Core.Castle.Core.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; - internal delegate GenericTypeParameterBuilder[] ApplyGenArgs(String[] argumentNames); + internal delegate GenericTypeParameterBuilder[] ApplyGenArgs(string[] argumentNames); internal class GenericUtil { public static GenericTypeParameterBuilder[] CopyGenericArguments( MethodInfo methodToCopyGenericsFrom, - TypeBuilder builder, - Dictionary name2GenericType) + TypeBuilder builder) { - return - CopyGenericArguments(methodToCopyGenericsFrom, name2GenericType, - builder.DefineGenericParameters); + return CopyGenericArguments(methodToCopyGenericsFrom, builder.DefineGenericParameters); } public static GenericTypeParameterBuilder[] CopyGenericArguments( MethodInfo methodToCopyGenericsFrom, - MethodBuilder builder, - Dictionary name2GenericType) + MethodBuilder builder) { - return - CopyGenericArguments(methodToCopyGenericsFrom, name2GenericType, - builder.DefineGenericParameters); - } - - public static Type ExtractCorrectType(Type paramType, Dictionary name2GenericType) - { - if (paramType.GetTypeInfo().IsArray) - { - var rank = paramType.GetArrayRank(); - - var underlyingType = paramType.GetElementType(); - - if (underlyingType.GetTypeInfo().IsGenericParameter) - { - GenericTypeParameterBuilder genericType; - if (name2GenericType.TryGetValue(underlyingType.Name, out genericType) == false) - { - return paramType; - } - - if (rank == 1) - { - return genericType.MakeArrayType(); - } - return genericType.MakeArrayType(rank); - } - if (rank == 1) - { - return underlyingType.MakeArrayType(); - } - return underlyingType.MakeArrayType(rank); - } - - if (paramType.GetTypeInfo().IsGenericParameter) - { - GenericTypeParameterBuilder value; - if (name2GenericType.TryGetValue(paramType.Name, out value)) - { - return value.AsType(); - } - } - - return paramType; - } - - public static Type[] ExtractParametersTypes( - ParameterInfo[] baseMethodParameters, - Dictionary name2GenericType) - { - var newParameters = new Type[baseMethodParameters.Length]; - - for (var i = 0; i < baseMethodParameters.Length; i++) - { - var param = baseMethodParameters[i]; - var paramType = param.ParameterType; - - newParameters[i] = ExtractCorrectType(paramType, name2GenericType); - } - - return newParameters; - } - - public static Dictionary GetGenericArgumentsMap(AbstractTypeEmitter parentEmitter) - { - if (parentEmitter.GenericTypeParams == null || parentEmitter.GenericTypeParams.Length == 0) - { - return new Dictionary(0); - } - - var name2GenericType = new Dictionary(parentEmitter.GenericTypeParams.Length); - foreach (var genType in parentEmitter.GenericTypeParams) - { - name2GenericType.Add(genType.Name, genType); - } - return name2GenericType; + return CopyGenericArguments(methodToCopyGenericsFrom, builder.DefineGenericParameters); } private static Type AdjustConstraintToNewGenericParameters( Type constraint, MethodInfo methodToCopyGenericsFrom, Type[] originalGenericParameters, GenericTypeParameterBuilder[] newGenericParameters) { - if (constraint.GetTypeInfo().IsGenericType) + if (constraint.IsGenericType) { var genericArgumentsOfConstraint = constraint.GetGenericArguments(); @@ -136,21 +56,21 @@ private static Type AdjustConstraintToNewGenericParameters( } return constraint.GetGenericTypeDefinition().MakeGenericType(genericArgumentsOfConstraint); } - else if (constraint.GetTypeInfo().IsGenericParameter) + else if (constraint.IsGenericParameter) { // Determine the source of the parameter - if (constraint.GetTypeInfo().DeclaringMethod != null) + if (constraint.DeclaringMethod != null) { // constraint comes from the method var index = Array.IndexOf(originalGenericParameters, constraint); Trace.Assert(index != -1, "When a generic method parameter has a constraint on another method parameter, both parameters must be declared on the same method."); - return newGenericParameters[index].AsType(); + return newGenericParameters[index]; } else // parameter from surrounding type { - Trace.Assert(constraint.DeclaringType.GetTypeInfo().IsGenericTypeDefinition); - Trace.Assert(methodToCopyGenericsFrom.DeclaringType.GetTypeInfo().IsGenericType + Trace.Assert(constraint.DeclaringType.IsGenericTypeDefinition); + Trace.Assert(methodToCopyGenericsFrom.DeclaringType.IsGenericType && constraint.DeclaringType == methodToCopyGenericsFrom.DeclaringType.GetGenericTypeDefinition(), "When a generic method parameter has a constraint on a generic type parameter, the generic type must be the declaring typer of the method."); @@ -184,7 +104,6 @@ private static Type[] AdjustGenericConstraints(MethodInfo methodToCopyGenericsFr private static GenericTypeParameterBuilder[] CopyGenericArguments( MethodInfo methodToCopyGenericsFrom, - Dictionary name2GenericType, ApplyGenArgs genericParameterGenerator) { var originalGenericArguments = methodToCopyGenericsFrom.GetGenericArguments(); @@ -200,9 +119,9 @@ private static GenericTypeParameterBuilder[] CopyGenericArguments( { try { - var attributes = originalGenericArguments[i].GetTypeInfo().GenericParameterAttributes; + var attributes = originalGenericArguments[i].GenericParameterAttributes; newGenericParameters[i].SetGenericParameterAttributes(attributes); - var constraints = AdjustGenericConstraints(methodToCopyGenericsFrom, newGenericParameters, originalGenericArguments, originalGenericArguments[i].GetTypeInfo().GetGenericParameterConstraints()); + var constraints = AdjustGenericConstraints(methodToCopyGenericsFrom, newGenericParameters, originalGenericArguments, originalGenericArguments[i].GetGenericParameterConstraints()); newGenericParameters[i].SetInterfaceConstraints(constraints); CopyNonInheritableAttributes(newGenericParameters[i], originalGenericArguments[i]); @@ -213,8 +132,6 @@ private static GenericTypeParameterBuilder[] CopyGenericArguments( newGenericParameters[i].SetGenericParameterAttributes(GenericParameterAttributes.None); } - - name2GenericType[argumentNames[i]] = newGenericParameters[i]; } return newGenericParameters; @@ -223,7 +140,7 @@ private static GenericTypeParameterBuilder[] CopyGenericArguments( private static void CopyNonInheritableAttributes(GenericTypeParameterBuilder newGenericParameter, Type originalGenericArgument) { - foreach (var attribute in originalGenericArgument.GetTypeInfo().GetNonInheritableAttributes()) + foreach (var attribute in originalGenericArgument.GetNonInheritableAttributes()) { newGenericParameter.SetCustomAttribute(attribute.Builder); } @@ -231,7 +148,7 @@ private static void CopyNonInheritableAttributes(GenericTypeParameterBuilder new private static string[] GetArgumentNames(Type[] originalGenericArguments) { - var argumentNames = new String[originalGenericArguments.Length]; + var argumentNames = new string[originalGenericArguments.Length]; for (var i = 0; i < argumentNames.Length; i++) { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/IMemberEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/IMemberEmitter.cs index e6e11532..e39c722d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/IMemberEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/IMemberEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdcOpCodesDictionary.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdcOpCodesDictionary.cs index 2eefaedd..061a6eea 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdcOpCodesDictionary.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdcOpCodesDictionary.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -19,7 +19,6 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters using System.Reflection.Emit; /// - /// s /// Provides appropriate Ldc.X opcode for the type of primitive value to be loaded. /// internal sealed class LdcOpCodesDictionary : Dictionary @@ -49,9 +48,9 @@ private LdcOpCodesDictionary() { get { - if (ContainsKey(type)) + if (TryGetValue(type, out var opCode)) { - return base[type]; + return opCode; } return EmptyOpCode; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdindOpCodesDictionary.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdindOpCodesDictionary.cs index b8e54446..4a29f3d7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdindOpCodesDictionary.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/LdindOpCodesDictionary.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -49,9 +49,9 @@ private LdindOpCodesDictionary() { get { - if (ContainsKey(type)) + if (TryGetValue(type, out var opCode)) { - return base[type]; + return opCode; } return EmptyOpCode; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodEmitter.cs index 1867112b..e70947ee 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,13 +15,13 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters { using System; + using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; @@ -29,23 +29,23 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters internal class MethodEmitter : IMemberEmitter { private readonly MethodBuilder builder; + private readonly CodeBuilder codeBuilder; private readonly GenericTypeParameterBuilder[] genericTypeParams; private ArgumentReference[] arguments; - private MethodCodeBuilder codebuilder; - protected internal MethodEmitter(MethodBuilder builder) { this.builder = builder; + codeBuilder = new CodeBuilder(); } - internal MethodEmitter(AbstractTypeEmitter owner, String name, MethodAttributes attributes) + internal MethodEmitter(AbstractTypeEmitter owner, string name, MethodAttributes attributes) : this(owner.TypeBuilder.DefineMethod(name, attributes)) { } - internal MethodEmitter(AbstractTypeEmitter owner, String name, + internal MethodEmitter(AbstractTypeEmitter owner, string name, MethodAttributes attributes, Type returnType, params Type[] argumentTypes) : this(owner, name, attributes) @@ -54,17 +54,19 @@ internal MethodEmitter(AbstractTypeEmitter owner, String name, SetReturnType(returnType); } - internal MethodEmitter(AbstractTypeEmitter owner, String name, + internal MethodEmitter(AbstractTypeEmitter owner, string name, MethodAttributes attributes, MethodInfo methodToUseAsATemplate) : this(owner, name, attributes) { - var name2GenericType = GenericUtil.GetGenericArgumentsMap(owner); + // All code paths leading up to this constructor can be traced back to + // proxy type generation code. At present, proxy types are never generic. + Debug.Assert(owner.GenericTypeParams == null || owner.GenericTypeParams.Length == 0); - var returnType = GenericUtil.ExtractCorrectType(methodToUseAsATemplate.ReturnType, name2GenericType); + var returnType = methodToUseAsATemplate.ReturnType; var baseMethodParameters = methodToUseAsATemplate.GetParameters(); - var parameters = GenericUtil.ExtractParametersTypes(baseMethodParameters, name2GenericType); + var parameters = ArgumentsUtil.GetTypes(baseMethodParameters); - genericTypeParams = GenericUtil.CopyGenericArguments(methodToUseAsATemplate, builder, name2GenericType); + genericTypeParams = GenericUtil.CopyGenericArguments(methodToUseAsATemplate, builder); SetParameters(parameters); SetReturnType(returnType); SetSignature(returnType, methodToUseAsATemplate.ReturnParameter, parameters, baseMethodParameters); @@ -76,16 +78,9 @@ public ArgumentReference[] Arguments get { return arguments; } } - public virtual MethodCodeBuilder CodeBuilder + public CodeBuilder CodeBuilder { - get - { - if (codebuilder == null) - { - codebuilder = new MethodCodeBuilder(builder.GetILGenerator()); - } - return codebuilder; - } + get { return codeBuilder; } } public GenericTypeParameterBuilder[] GenericTypeParams @@ -112,11 +107,7 @@ private bool ImplementedByRuntime { get { -#if FEATURE_LEGACY_REFLECTION_API - var attributes = builder.GetMethodImplementationFlags(); -#else var attributes = builder.MethodImplementationFlags; -#endif return (attributes & MethodImplAttributes.Runtime) != 0; } } @@ -137,8 +128,14 @@ public virtual void EnsureValidCodeBlock() { if (ImplementedByRuntime == false && CodeBuilder.IsEmpty) { - CodeBuilder.AddStatement(new NopStatement()); - CodeBuilder.AddStatement(new ReturnStatement()); + if (ReturnType == typeof(void)) + { + CodeBuilder.AddStatement(new ReturnStatement()); + } + else + { + CodeBuilder.AddStatement(new ReturnStatement(new DefaultValueExpression(ReturnType))); + } } } @@ -149,7 +146,7 @@ public virtual void Generate() return; } - codebuilder.Generate(this, builder.GetILGenerator()); + codeBuilder.Generate(builder.GetILGenerator()); } private void DefineParameters(ParameterInfo[] parameters) @@ -209,7 +206,7 @@ private void CopyDefaultValueConstant(ParameterInfo from, ParameterBuilder to) // If this bug is present, it is caused by a `null` default value: defaultValue = null; } - catch (FormatException) when (from.ParameterType.GetTypeInfo().IsEnum) + catch (FormatException) when (from.ParameterType.IsEnum) { // This catch clause guards against a CLR bug that makes it impossible to query // the default value of a (closed generic) enum parameter. For the CoreCLR, see @@ -253,7 +250,7 @@ private void CopyDefaultValueConstant(ParameterInfo from, ParameterBuilder to) // would "produce" a default value of `Missing.Value` in this situation). return; } - else if (parameterType.GetTypeInfo().IsValueType) + else if (parameterType.IsValueType) { // This guards against a CLR bug that prohibits replicating `null` default // values for non-nullable value types (which, despite the apparent type @@ -269,7 +266,7 @@ private void CopyDefaultValueConstant(ParameterInfo from, ParameterBuilder to) else if (parameterType.IsNullableType()) { parameterNonNullableType = from.ParameterType.GetGenericArguments()[0]; - if (parameterNonNullableType.GetTypeInfo().IsEnum || parameterNonNullableType.IsAssignableFrom(defaultValue.GetType())) + if (parameterNonNullableType.IsEnum || parameterNonNullableType.IsAssignableFrom(defaultValue.GetType())) { // This guards against two bugs: // @@ -323,7 +320,6 @@ private void SetSignature(Type returnType, ParameterInfo returnParameter, Type[] Type[][] parametersRequiredCustomModifiers; Type[][] parametersOptionalCustomModifiers; -#if FEATURE_EMIT_CUSTOMMODIFIERS returnRequiredCustomModifiers = returnParameter.GetRequiredCustomModifiers(); Array.Reverse(returnRequiredCustomModifiers); @@ -341,12 +337,6 @@ private void SetSignature(Type returnType, ParameterInfo returnParameter, Type[] parametersOptionalCustomModifiers[i] = baseMethodParameters[i].GetOptionalCustomModifiers(); Array.Reverse(parametersOptionalCustomModifiers[i]); } -#else - returnRequiredCustomModifiers = null; - returnOptionalCustomModifiers = null; - parametersRequiredCustomModifiers = null; - parametersOptionalCustomModifiers = null; -#endif builder.SetSignature( returnType, @@ -357,4 +347,4 @@ private void SetSignature(Type returnType, ParameterInfo returnParameter, Type[] parametersOptionalCustomModifiers); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassCollection.cs deleted file mode 100644 index 6bcc3370..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassCollection.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters -{ - using System.Collections.ObjectModel; - - internal class NestedClassCollection : Collection - { - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassEmitter.cs index 1df85d83..edef3149 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/NestedClassEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -20,30 +20,30 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters internal class NestedClassEmitter : AbstractTypeEmitter { - public NestedClassEmitter(AbstractTypeEmitter maintype, String name, Type baseType, Type[] interfaces) + public NestedClassEmitter(AbstractTypeEmitter mainType, string name, Type baseType, Type[] interfaces) : this( - maintype, - CreateTypeBuilder(maintype, name, TypeAttributes.Sealed | TypeAttributes.NestedPublic | TypeAttributes.Class, + mainType, + CreateTypeBuilder(mainType, name, TypeAttributes.Sealed | TypeAttributes.NestedPublic | TypeAttributes.Class, baseType, interfaces)) { } - public NestedClassEmitter(AbstractTypeEmitter maintype, String name, TypeAttributes attributes, Type baseType, + public NestedClassEmitter(AbstractTypeEmitter mainType, string name, TypeAttributes attributes, Type baseType, Type[] interfaces) - : this(maintype, CreateTypeBuilder(maintype, name, attributes, baseType, interfaces)) + : this(mainType, CreateTypeBuilder(mainType, name, attributes, baseType, interfaces)) { } - public NestedClassEmitter(AbstractTypeEmitter maintype, TypeBuilder typeBuilder) + public NestedClassEmitter(AbstractTypeEmitter mainType, TypeBuilder typeBuilder) : base(typeBuilder) { - maintype.Nested.Add(this); + mainType.AddNestedClass(this); } - private static TypeBuilder CreateTypeBuilder(AbstractTypeEmitter maintype, string name, TypeAttributes attributes, + private static TypeBuilder CreateTypeBuilder(AbstractTypeEmitter mainType, string name, TypeAttributes attributes, Type baseType, Type[] interfaces) { - return maintype.TypeBuilder.DefineNestedType( + return mainType.TypeBuilder.DefineNestedType( name, attributes, baseType, interfaces); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/OpCodeUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/OpCodeUtil.cs index c7d48b07..bf8d6034 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/OpCodeUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/OpCodeUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -25,21 +25,19 @@ internal abstract class OpCodeUtil /// Pops a pointer off the evaluation stack, dereferences it and loads /// a value of the specified type. /// - /// - /// public static void EmitLoadIndirectOpCodeForType(ILGenerator gen, Type type) { - if (type.GetTypeInfo().IsEnum) + if (type.IsEnum) { EmitLoadIndirectOpCodeForType(gen, GetUnderlyingTypeOfEnum(type)); return; } - if (type.GetTypeInfo().IsByRef) + if (type.IsByRef) { throw new NotSupportedException("Cannot load ByRef values"); } - else if (type.GetTypeInfo().IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr)) + else if (type.IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr)) { var opCode = LdindOpCodesDictionary.Instance[type]; @@ -50,11 +48,11 @@ public static void EmitLoadIndirectOpCodeForType(ILGenerator gen, Type type) gen.Emit(opCode); } - else if (type.GetTypeInfo().IsValueType) + else if (type.IsValueType) { gen.Emit(OpCodes.Ldobj, type); } - else if (type.GetTypeInfo().IsGenericParameter) + else if (type.IsGenericParameter) { gen.Emit(OpCodes.Ldobj, type); } @@ -64,41 +62,13 @@ public static void EmitLoadIndirectOpCodeForType(ILGenerator gen, Type type) } } - /// - /// Emits a load opcode of the appropriate kind for a constant string or - /// primitive value. - /// - /// - /// - public static void EmitLoadOpCodeForConstantValue(ILGenerator gen, object value) - { - if (value is String) - { - gen.Emit(OpCodes.Ldstr, value.ToString()); - } - else if (value is Int32) - { - var code = LdcOpCodesDictionary.Instance[value.GetType()]; - gen.Emit(code, (int)value); - } - else if (value is bool) - { - var code = LdcOpCodesDictionary.Instance[value.GetType()]; - gen.Emit(code, Convert.ToInt32(value)); - } - else - { - throw new NotSupportedException(); - } - } - /// /// Emits a load opcode of the appropriate kind for the constant default value of a /// type, such as 0 for value types and null for reference types. /// public static void EmitLoadOpCodeForDefaultValueOfType(ILGenerator gen, Type type) { - if (type.GetTypeInfo().IsPrimitive) + if (type.IsPrimitive) { var opCode = LdcOpCodesDictionary.Instance[type]; switch (opCode.StackBehaviourPush) @@ -135,21 +105,19 @@ public static void EmitLoadOpCodeForDefaultValueOfType(ILGenerator gen, Type typ /// Pops a value of the specified type and a pointer off the evaluation stack, and /// stores the value. /// - /// - /// public static void EmitStoreIndirectOpCodeForType(ILGenerator gen, Type type) { - if (type.GetTypeInfo().IsEnum) + if (type.IsEnum) { EmitStoreIndirectOpCodeForType(gen, GetUnderlyingTypeOfEnum(type)); return; } - if (type.GetTypeInfo().IsByRef) + if (type.IsByRef) { throw new NotSupportedException("Cannot store ByRef values"); } - else if (type.GetTypeInfo().IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr)) + else if (type.IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr)) { var opCode = StindOpCodesDictionary.Instance[type]; @@ -160,11 +128,11 @@ public static void EmitStoreIndirectOpCodeForType(ILGenerator gen, Type type) gen.Emit(opCode); } - else if (type.GetTypeInfo().IsValueType) + else if (type.IsValueType) { gen.Emit(OpCodes.Stobj, type); } - else if (type.GetTypeInfo().IsGenericParameter) + else if (type.IsGenericParameter) { gen.Emit(OpCodes.Stobj, type); } @@ -207,4 +175,4 @@ private static bool Is64BitTypeLoadedAsInt32(Type type) return type == typeof(long) || type == typeof(ulong); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertiesCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertiesCollection.cs deleted file mode 100644 index bbf974e0..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertiesCollection.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters -{ - using System.Collections.ObjectModel; - - /// - /// Summary description for PropertiesCollection. - /// - internal class PropertiesCollection : Collection - { - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertyEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertyEmitter.cs index d34f0cba..3313567d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertyEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/PropertyEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AddressOfReferenceExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AddressOfReferenceExpression.cs deleted file mode 100644 index ccd07ec3..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AddressOfReferenceExpression.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System.Reflection.Emit; - - internal class AddressOfReferenceExpression : Expression - { - private readonly Reference reference; - - public AddressOfReferenceExpression(Reference reference) - { - this.reference = reference; - } - - public override void Emit(IMemberEmitter member, ILGenerator gen) - { - ArgumentsUtil.EmitLoadOwnerAndReference(reference.OwnerReference, gen); - - reference.LoadAddressOfReference(gen); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ArgumentReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ArgumentReference.cs index 9fd911b4..d30da478 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ArgumentReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ArgumentReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,35 +16,37 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System; using System.Diagnostics; - using System.Reflection; - using System.Reflection.Emit; + using System.Reflection; + using System.Reflection.Emit; [DebuggerDisplay("argument {Type}")] internal class ArgumentReference : TypeReference { - public ArgumentReference(Type argumentType) - : this(argumentType, DBNull.Value) - { } - - public ArgumentReference(Type argumentType, object defaultValue) - : base(argumentType) - { - this.DefaultValue = defaultValue; - ParameterAttributes = ParameterAttributes.None; - Position = -1; - } - - public ArgumentReference(Type argumentType, int position, ParameterAttributes parameterAttributes) + private ArgumentReference(Type argumentType, object defaultValue, int position, ParameterAttributes parameterAttributes) : base(argumentType) { - Position = position; + DefaultValue = defaultValue; + Position = position; + ParameterAttributes = parameterAttributes; } - internal object DefaultValue { get; private set; } - internal int Position { get; set; } - internal ParameterAttributes ParameterAttributes { get; set; } + public ArgumentReference(Type argumentType) + : this(argumentType, DBNull.Value, -1, ParameterAttributes.None) + { } + + public ArgumentReference(Type argumentType, object defaultValue) + : this(argumentType, defaultValue, -1, ParameterAttributes.None) + { } + + public ArgumentReference(Type argumentType, int position, ParameterAttributes parameterAttributes) + : this(argumentType, DBNull.Value, position, parameterAttributes) + { } + + internal object DefaultValue { get; private set; } + internal int Position { get; set; } + internal ParameterAttributes ParameterAttributes { get; set; } - public override void LoadAddressOfReference(ILGenerator gen) + public override void LoadAddressOfReference(ILGenerator gen) { throw new NotSupportedException(); } @@ -53,7 +55,7 @@ public override void LoadReference(ILGenerator gen) { if (Position == -1) { - throw new ProxyGenerationException("ArgumentReference uninitialized"); + throw new InvalidOperationException("ArgumentReference uninitialized"); } switch (Position) { @@ -79,9 +81,9 @@ public override void StoreReference(ILGenerator gen) { if (Position == -1) { - throw new ProxyGenerationException("ArgumentReference uninitialized"); + throw new InvalidOperationException("ArgumentReference uninitialized"); } gen.Emit(OpCodes.Starg, Position); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AsTypeReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AsTypeReference.cs index d96b6eca..40efa690 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AsTypeReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AsTypeReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -28,11 +28,11 @@ public AsTypeReference(Reference reference, Type type) { if (reference == null) { - throw new ArgumentNullException("reference"); + throw new ArgumentNullException(nameof(reference)); } if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } this.reference = reference; this.type = type; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArgumentStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArgumentStatement.cs index e970d244..7324d815 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArgumentStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArgumentStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,21 +16,21 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class AssignArgumentStatement : Statement + internal class AssignArgumentStatement : IStatement { private readonly ArgumentReference argument; - private readonly Expression expression; + private readonly IExpression expression; - public AssignArgumentStatement(ArgumentReference argument, Expression expression) + public AssignArgumentStatement(ArgumentReference argument, IExpression expression) { this.argument = argument; this.expression = expression; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { ArgumentsUtil.EmitLoadOwnerAndReference(argument, gen); - expression.Emit(member, gen); + expression.Emit(gen); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArrayStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArrayStatement.cs index 8268b572..a4384d7c 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArrayStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignArrayStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,26 +16,26 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class AssignArrayStatement : Statement + internal class AssignArrayStatement : IStatement { private readonly Reference targetArray; private readonly int targetPosition; - private readonly Expression value; + private readonly IExpression value; - public AssignArrayStatement(Reference targetArray, int targetPosition, Expression value) + public AssignArrayStatement(Reference targetArray, int targetPosition, IExpression value) { this.targetArray = targetArray; this.targetPosition = targetPosition; this.value = value; } - public override void Emit(IMemberEmitter member, ILGenerator il) + public void Emit(ILGenerator il) { ArgumentsUtil.EmitLoadOwnerAndReference(targetArray, il); il.Emit(OpCodes.Ldc_I4, targetPosition); - value.Emit(member, il); + value.Emit(il); il.Emit(OpCodes.Stelem_Ref); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignStatement.cs index ae823ffb..27a61002 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/AssignStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,21 +16,21 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class AssignStatement : Statement + internal class AssignStatement : IStatement { - private readonly Expression expression; + private readonly IExpression expression; private readonly Reference target; - public AssignStatement(Reference target, Expression expression) + public AssignStatement(Reference target, IExpression expression) { this.target = target; this.expression = expression; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { ArgumentsUtil.EmitLoadOwnerAndReference(target.OwnerReference, gen); - expression.Emit(member, gen); + expression.Emit(gen); target.StoreReference(gen); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BindDelegateExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BindDelegateExpression.cs deleted file mode 100644 index 82b1edf7..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BindDelegateExpression.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System; - using System.Reflection; - using System.Reflection.Emit; - - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; - - internal class BindDelegateExpression : Expression - { - private readonly ConstructorInfo delegateCtor; - private readonly MethodInfo methodToBindTo; - private readonly Expression owner; - - public BindDelegateExpression(Type @delegate, Expression owner, MethodInfo methodToBindTo, - GenericTypeParameterBuilder[] genericTypeParams) - { - delegateCtor = @delegate.GetConstructors()[0]; - this.methodToBindTo = methodToBindTo; - if (@delegate.GetTypeInfo().IsGenericTypeDefinition) - { - var genericTypeParameters = genericTypeParams.AsTypeArray(); - var closedDelegate = @delegate.MakeGenericType(genericTypeParameters); - delegateCtor = TypeBuilder.GetConstructor(closedDelegate, delegateCtor); - this.methodToBindTo = methodToBindTo.MakeGenericMethod(genericTypeParameters); - } - this.owner = owner; - } - - public override void Emit(IMemberEmitter member, ILGenerator gen) - { - owner.Emit(member, gen); - gen.Emit(OpCodes.Dup); - if (methodToBindTo.IsFinal) - { - gen.Emit(OpCodes.Ldftn, methodToBindTo); - } - else - { - gen.Emit(OpCodes.Ldvirtftn, methodToBindTo); - } - gen.Emit(OpCodes.Newobj, delegateCtor); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferenceExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BlockStatement.cs similarity index 59% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferenceExpression.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BlockStatement.cs index 9c8b6538..eaf0aa84 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferenceExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/BlockStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,20 +14,24 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST { + using System.Collections.Generic; using System.Reflection.Emit; - internal class ReferenceExpression : Expression + internal class BlockStatement : IStatement { - private readonly Reference reference; + private readonly List statements = new List(); - public ReferenceExpression(Reference reference) + public void AddStatement(IStatement statement) { - this.reference = reference; + statements.Add(statement); } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { - ArgumentsUtil.EmitLoadOwnerAndReference(reference, gen); + foreach (var s in statements) + { + s.Emit(gen); + } } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ByRefReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ByRefReference.cs index f10e44d3..066edc50 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ByRefReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ByRefReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstReference.cs deleted file mode 100644 index 79da8952..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstReference.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System; - using System.Diagnostics; - using System.Reflection; - using System.Reflection.Emit; - - [DebuggerDisplay("{value}")] - internal class ConstReference : TypeReference - { - private readonly object value; - - public ConstReference(object value) - : base(value.GetType()) - { - if (!value.GetType().GetTypeInfo().IsPrimitive && !(value is String)) - { - throw new ProxyGenerationException("Invalid type to ConstReference"); - } - - this.value = value; - } - - public override void Generate(ILGenerator gen) - { - } - - public override void LoadAddressOfReference(ILGenerator gen) - { - throw new NotSupportedException(); - } - - public override void LoadReference(ILGenerator gen) - { - OpCodeUtil.EmitLoadOpCodeForConstantValue(gen, value); - } - - public override void StoreReference(ILGenerator gen) - { - throw new NotImplementedException("ConstReference.StoreReference"); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstructorInvocationStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstructorInvocationStatement.cs index 36131c5f..14293494 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstructorInvocationStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConstructorInvocationStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,36 +18,54 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - internal class ConstructorInvocationStatement : Statement + internal class ConstructorInvocationStatement : IStatement { - private readonly Expression[] args; + private readonly IExpression[] args; private readonly ConstructorInfo cmethod; - public ConstructorInvocationStatement(ConstructorInfo method, params Expression[] args) + public ConstructorInvocationStatement(Type baseType) + : this(GetDefaultConstructor(baseType)) + { + } + + public ConstructorInvocationStatement(ConstructorInfo method, params IExpression[] args) { if (method == null) { - throw new ArgumentNullException("method"); + throw new ArgumentNullException(nameof(method)); } if (args == null) { - throw new ArgumentNullException("args"); + throw new ArgumentNullException(nameof(args)); } cmethod = method; this.args = args; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.Emit(OpCodes.Ldarg_0); foreach (var exp in args) { - exp.Emit(member, gen); + exp.Emit(gen); } gen.Emit(OpCodes.Call, cmethod); } + + private static ConstructorInfo GetDefaultConstructor(Type baseType) + { + var type = baseType; + if (type.ContainsGenericParameters) + { + type = type.GetGenericTypeDefinition(); + // need to get generic type definition, otherwise the GetConstructor method might throw NotSupportedException + } + + var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + return type.GetConstructor(flags, null, Type.EmptyTypes, null); + } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConvertExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConvertExpression.cs index d99515f7..e5cf9142 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConvertExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ConvertExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,34 +18,34 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - internal class ConvertExpression : Expression + internal class ConvertExpression : IExpression { - private readonly Expression right; + private readonly IExpression right; private Type fromType; private Type target; - public ConvertExpression(Type targetType, Expression right) + public ConvertExpression(Type targetType, IExpression right) : this(targetType, typeof(object), right) { } - public ConvertExpression(Type targetType, Type fromType, Expression right) + public ConvertExpression(Type targetType, Type fromType, IExpression right) { target = targetType; this.fromType = fromType; this.right = right; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { - right.Emit(member, gen); + right.Emit(gen); if (fromType == target) { return; } - if (fromType.GetTypeInfo().IsByRef) + if (fromType.IsByRef) { fromType = fromType.GetElementType(); } @@ -55,19 +55,19 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) target = target.GetElementType(); } - if (target.IsPointer && fromType == typeof(object)) - { - gen.Emit(OpCodes.Unbox_Any, typeof(IntPtr)); - gen.Emit(OpCodes.Call, ArgumentsUtil.PointerFromIntPtr()); - } - else if (target == typeof(object) && fromType.IsPointer) - { - gen.Emit(OpCodes.Call, ArgumentsUtil.IntPtrFromPointer()); - gen.Emit(OpCodes.Box, typeof(IntPtr)); - } - else if (target.GetTypeInfo().IsValueType) + if (target.IsPointer && fromType == typeof(object)) { - if (fromType.GetTypeInfo().IsValueType) + gen.Emit(OpCodes.Unbox_Any, typeof(IntPtr)); + gen.Emit(OpCodes.Call, ArgumentsUtil.PointerFromIntPtr()); + } + else if (target == typeof(object) && fromType.IsPointer) + { + gen.Emit(OpCodes.Call, ArgumentsUtil.IntPtrFromPointer()); + gen.Emit(OpCodes.Box, typeof(IntPtr)); + } + else if (target.IsValueType) + { + if (fromType.IsValueType) { throw new NotImplementedException("Cannot convert between distinct value types"); } @@ -89,7 +89,7 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) } else { - if (fromType.GetTypeInfo().IsValueType) + if (fromType.IsValueType) { // Box conversion gen.Emit(OpCodes.Box, fromType); @@ -109,18 +109,18 @@ private static void EmitCastIfNeeded(Type from, Type target, ILGenerator gen) { gen.Emit(OpCodes.Unbox_Any, target); } - else if (from.GetTypeInfo().IsGenericParameter) + else if (from.IsGenericParameter) { gen.Emit(OpCodes.Box, from); } - else if (target.GetTypeInfo().IsGenericType && target != from) + else if (target.IsGenericType && target != from) { gen.Emit(OpCodes.Castclass, target); } - else if (target.GetTypeInfo().IsSubclassOf(from)) + else if (target.IsSubclassOf(from)) { gen.Emit(OpCodes.Castclass, target); } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/DefaultValueExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/DefaultValueExpression.cs index 3115e0e7..81d3b3e8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/DefaultValueExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/DefaultValueExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +18,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - internal class DefaultValueExpression : Expression + internal class DefaultValueExpression : IExpression { private readonly Type type; @@ -27,14 +27,14 @@ public DefaultValueExpression(Type type) this.type = type; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { // TODO: check if this can be simplified by using more of OpCodeUtil and other existing types if (IsPrimitiveOrClass(type)) { OpCodeUtil.EmitLoadOpCodeForDefaultValueOfType(gen, type); } - else if (type.GetTypeInfo().IsValueType || type.GetTypeInfo().IsGenericParameter) + else if (type.IsValueType || type.IsGenericParameter) { // TODO: handle decimal explicitly var local = gen.DeclareLocal(type); @@ -42,13 +42,13 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) gen.Emit(OpCodes.Initobj, type); gen.Emit(OpCodes.Ldloc, local); } - else if (type.GetTypeInfo().IsByRef) + else if (type.IsByRef) { EmitByRef(gen); } else { - throw new ProxyGenerationException("Can't emit default value for type " + type); + throw new NotImplementedException("Can't emit default value for type " + type); } } @@ -60,25 +60,25 @@ private void EmitByRef(ILGenerator gen) OpCodeUtil.EmitLoadOpCodeForDefaultValueOfType(gen, elementType); OpCodeUtil.EmitStoreIndirectOpCodeForType(gen, elementType); } - else if (elementType.GetTypeInfo().IsGenericParameter || elementType.GetTypeInfo().IsValueType) + else if (elementType.IsGenericParameter || elementType.IsValueType) { gen.Emit(OpCodes.Initobj, elementType); } else { - throw new ProxyGenerationException("Can't emit default value for reference of type " + elementType); + throw new NotImplementedException("Can't emit default value for reference of type " + elementType); } } private bool IsPrimitiveOrClass(Type type) { - if ((type.GetTypeInfo().IsPrimitive && type != typeof(IntPtr))) + if (type.IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr)) { return true; } - return ((type.GetTypeInfo().IsClass || type.GetTypeInfo().IsInterface) && - type.GetTypeInfo().IsGenericParameter == false && - type.GetTypeInfo().IsByRef == false); + return ((type.IsClass || type.IsInterface) && + type.IsGenericParameter == false && + type.IsByRef == false); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/EndExceptionBlockStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/EndExceptionBlockStatement.cs index 9174cdf0..6733ebe9 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/EndExceptionBlockStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/EndExceptionBlockStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,9 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class EndExceptionBlockStatement : Statement + internal class EndExceptionBlockStatement : IStatement { - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.EndExceptionBlock(); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ExpressionStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ExpressionStatement.cs deleted file mode 100644 index 230a65eb..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ExpressionStatement.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System.Reflection.Emit; - - internal class ExpressionStatement : Statement - { - private readonly Expression expression; - - public ExpressionStatement(Expression expression) - { - this.expression = expression; - } - - public override void Emit(IMemberEmitter member, ILGenerator gen) - { - // TODO: Should it discard any possible return value with a pop? - expression.Emit(member, gen); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FieldReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FieldReference.cs index 4f738e46..99f5aa93 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FieldReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FieldReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,11 +18,11 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - [DebuggerDisplay("{fieldbuilder.Name} ({fieldbuilder.FieldType})")] + [DebuggerDisplay("{fieldBuilder.Name} ({fieldBuilder.FieldType})")] internal class FieldReference : Reference { private readonly FieldInfo field; - private readonly FieldBuilder fieldbuilder; + private readonly FieldBuilder fieldBuilder; private readonly bool isStatic; public FieldReference(FieldInfo field) @@ -35,20 +35,20 @@ public FieldReference(FieldInfo field) } } - public FieldReference(FieldBuilder fieldbuilder) + public FieldReference(FieldBuilder fieldBuilder) { - this.fieldbuilder = fieldbuilder; - field = fieldbuilder; - if ((fieldbuilder.Attributes & FieldAttributes.Static) != 0) + this.fieldBuilder = fieldBuilder; + field = fieldBuilder; + if ((fieldBuilder.Attributes & FieldAttributes.Static) != 0) { isStatic = true; owner = null; } } - public FieldBuilder Fieldbuilder + public FieldBuilder FieldBuilder { - get { return fieldbuilder; } + get { return fieldBuilder; } } public FieldInfo Reference diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FinallyStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FinallyStatement.cs index ecc570f1..a207d039 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FinallyStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/FinallyStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,9 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class FinallyStatement : Statement + internal class FinallyStatement : IStatement { - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.BeginFinallyBlock(); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IExpression.cs similarity index 72% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventCollection.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IExpression.cs index 029a0988..151d3b65 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/EventCollection.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,11 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST { - using System.Collections.ObjectModel; - - internal class EventCollection : Collection + internal interface IExpression : IExpressionOrStatement { } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IILEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IExpressionOrStatement.cs similarity index 76% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IILEmitter.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IExpressionOrStatement.cs index 0005c272..69cfbbd9 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IILEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IExpressionOrStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal interface IILEmitter + internal interface IExpressionOrStatement { - void Emit(IMemberEmitter member, ILGenerator gen); + void Emit(ILGenerator gen); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IStatement.cs similarity index 71% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodCollection.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IStatement.cs index 21d2167c..bb4f96c2 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/MethodCollection.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IStatement.cs @@ -1,22 +1,20 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// +// +// http://www.apache.org/licenses/LICENSE-2.0 +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST { - using System.Collections.ObjectModel; - - internal class MethodCollection : Collection + internal interface IStatement : IExpressionOrStatement { } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IfNullExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IfNullExpression.cs index f1c901f8..d908079e 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IfNullExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IfNullExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,28 +17,28 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System; using System.Reflection.Emit; - internal class IfNullExpression : Expression + internal class IfNullExpression : IExpression, IStatement { - private readonly IILEmitter ifNotNull; - private readonly IILEmitter ifNull; + private readonly IExpressionOrStatement ifNotNull; + private readonly IExpressionOrStatement ifNull; private readonly Reference reference; - private readonly Expression expression; + private readonly IExpression expression; - public IfNullExpression(Reference reference, IILEmitter ifNull, IILEmitter ifNotNull = null) + public IfNullExpression(Reference reference, IExpressionOrStatement ifNull, IExpressionOrStatement ifNotNull = null) { this.reference = reference ?? throw new ArgumentNullException(nameof(reference)); this.ifNull = ifNull; this.ifNotNull = ifNotNull; } - public IfNullExpression(Expression expression, IILEmitter ifNull, IILEmitter ifNotNull = null) + public IfNullExpression(IExpression expression, IExpressionOrStatement ifNull, IExpressionOrStatement ifNotNull = null) { this.expression = expression ?? throw new ArgumentNullException(nameof(expression)); this.ifNull = ifNull; this.ifNotNull = ifNotNull; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { if (reference != null) { @@ -46,16 +46,16 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) } else if (expression != null) { - expression.Emit(member, gen); + expression.Emit(gen); } var notNull = gen.DefineLabel(); gen.Emit(OpCodes.Brtrue_S, notNull); - ifNull.Emit(member, gen); + ifNull.Emit(gen); gen.MarkLabel(notNull); if (ifNotNull != null) // yeah, I know that reads funny :) { - ifNotNull.Emit(member, gen); + ifNotNull.Emit(gen); } } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs index 8aaf7fb0..c0d37f52 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -29,9 +29,9 @@ internal class IndirectReference : TypeReference public IndirectReference(TypeReference byRefReference) : base(byRefReference, byRefReference.Type.GetElementType()) { - if (!byRefReference.Type.GetTypeInfo().IsByRef) + if (!byRefReference.Type.IsByRef) { - throw new ArgumentException("Expected an IsByRef reference", "byRefReference"); + throw new ArgumentException("Expected an IsByRef reference", nameof(byRefReference)); } } @@ -54,7 +54,7 @@ public override void StoreReference(ILGenerator gen) public static TypeReference WrapIfByRef(TypeReference reference) { - return reference.Type.GetTypeInfo().IsByRef ? new IndirectReference(reference) : reference; + return reference.Type.IsByRef ? new IndirectReference(reference) : reference; } // TODO: Better name diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Expression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralBoolExpression.cs similarity index 61% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Expression.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralBoolExpression.cs index 9e500b27..d172cf59 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Expression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralBoolExpression.cs @@ -1,11 +1,11 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// +// +// http://www.apache.org/licenses/LICENSE-2.0 +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,8 +16,18 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal abstract class Expression : IILEmitter + internal class LiteralBoolExpression : IExpression { - public abstract void Emit(IMemberEmitter member, ILGenerator gen); + private readonly bool value; + + public LiteralBoolExpression(bool value) + { + this.value = value; + } + + public void Emit(ILGenerator gen) + { + gen.Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralIntExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralIntExpression.cs index 4e766a69..28ccb414 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralIntExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralIntExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +16,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class LiteralIntExpression : Expression + internal class LiteralIntExpression : IExpression { private readonly int value; @@ -25,7 +25,7 @@ public LiteralIntExpression(int value) this.value = value; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { switch (value) { @@ -65,4 +65,4 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NopStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralStringExpression.cs similarity index 63% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NopStatement.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralStringExpression.cs index 31f92de6..9135dc1b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NopStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LiteralStringExpression.cs @@ -1,11 +1,11 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// +// +// http://www.apache.org/licenses/LICENSE-2.0 +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,11 +16,18 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class NopStatement : Statement + internal class LiteralStringExpression : IExpression { - public override void Emit(IMemberEmitter member, ILGenerator gen) + private readonly string value; + + public LiteralStringExpression(string value) + { + this.value = value; + } + + public void Emit(ILGenerator gen) { - gen.Emit(OpCodes.Nop); + gen.Emit(OpCodes.Ldstr, value); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadArrayElementExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadArrayElementExpression.cs deleted file mode 100644 index 6c62a186..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadArrayElementExpression.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System; - using System.Reflection.Emit; - - internal class LoadArrayElementExpression : Expression - { - private readonly Reference arrayReference; - private readonly ConstReference index; - private readonly Type returnType; - - public LoadArrayElementExpression(int index, Reference arrayReference, Type returnType) - : this(new ConstReference(index), arrayReference, returnType) - { - } - - public LoadArrayElementExpression(ConstReference index, Reference arrayReference, Type returnType) - { - this.index = index; - this.arrayReference = arrayReference; - this.returnType = returnType; - } - - public override void Emit(IMemberEmitter member, ILGenerator gen) - { - ArgumentsUtil.EmitLoadOwnerAndReference(arrayReference, gen); - ArgumentsUtil.EmitLoadOwnerAndReference(index, gen); - gen.Emit(OpCodes.Ldelem, returnType); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadRefArrayElementExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadRefArrayElementExpression.cs index ca1f881e..67120420 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadRefArrayElementExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LoadRefArrayElementExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,26 +16,21 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class LoadRefArrayElementExpression : Expression + internal class LoadRefArrayElementExpression : IExpression { private readonly Reference arrayReference; - private readonly ConstReference index; + private readonly LiteralIntExpression index; public LoadRefArrayElementExpression(int index, Reference arrayReference) - : this(new ConstReference(index), arrayReference) { - } - - public LoadRefArrayElementExpression(ConstReference index, Reference arrayReference) - { - this.index = index; + this.index = new LiteralIntExpression(index); this.arrayReference = arrayReference; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { ArgumentsUtil.EmitLoadOwnerAndReference(arrayReference, gen); - ArgumentsUtil.EmitLoadOwnerAndReference(index, gen); + index.Emit(gen); gen.Emit(OpCodes.Ldelem_Ref); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LocalReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LocalReference.cs index e528b882..29cdae18 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LocalReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/LocalReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +21,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS [DebuggerDisplay("local {Type}")] internal class LocalReference : TypeReference { - private LocalBuilder localbuilder; + private LocalBuilder localBuilder; public LocalReference(Type type) : base(type) { @@ -29,22 +29,22 @@ public LocalReference(Type type) : base(type) public override void Generate(ILGenerator gen) { - localbuilder = gen.DeclareLocal(base.Type); + localBuilder = gen.DeclareLocal(base.Type); } public override void LoadAddressOfReference(ILGenerator gen) { - gen.Emit(OpCodes.Ldloca, localbuilder); + gen.Emit(OpCodes.Ldloca, localBuilder); } public override void LoadReference(ILGenerator gen) { - gen.Emit(OpCodes.Ldloc, localbuilder); + gen.Emit(OpCodes.Ldloc, localBuilder); } public override void StoreReference(ILGenerator gen) { - gen.Emit(OpCodes.Stloc, localbuilder); + gen.Emit(OpCodes.Stloc, localBuilder); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodInvocationExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodInvocationExpression.cs index 5ddcf038..1241f2cb 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodInvocationExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodInvocationExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,28 +17,28 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - internal class MethodInvocationExpression : Expression + internal class MethodInvocationExpression : IExpression, IStatement { - protected readonly Expression[] args; + protected readonly IExpression[] args; protected readonly MethodInfo method; protected readonly Reference owner; - public MethodInvocationExpression(MethodInfo method, params Expression[] args) : + public MethodInvocationExpression(MethodInfo method, params IExpression[] args) : this(SelfReference.Self, method, args) { } - public MethodInvocationExpression(MethodEmitter method, params Expression[] args) : + public MethodInvocationExpression(MethodEmitter method, params IExpression[] args) : this(SelfReference.Self, method.MethodBuilder, args) { } - public MethodInvocationExpression(Reference owner, MethodEmitter method, params Expression[] args) : + public MethodInvocationExpression(Reference owner, MethodEmitter method, params IExpression[] args) : this(owner, method.MethodBuilder, args) { } - public MethodInvocationExpression(Reference owner, MethodInfo method, params Expression[] args) + public MethodInvocationExpression(Reference owner, MethodInfo method, params IExpression[] args) { this.owner = owner; this.method = method; @@ -47,13 +47,13 @@ public MethodInvocationExpression(Reference owner, MethodInfo method, params Exp public bool VirtualCall { get; set; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { ArgumentsUtil.EmitLoadOwnerAndReference(owner, gen); foreach (var exp in args) { - exp.Emit(member, gen); + exp.Emit(gen); } if (VirtualCall) diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodTokenExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodTokenExpression.cs index 2c9d38ea..43ec6624 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodTokenExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MethodTokenExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,30 +14,26 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST { - using System; + using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; - using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; - internal class MethodTokenExpression : Expression + using Castle.DynamicProxy.Tokens; + + internal class MethodTokenExpression : IExpression { private readonly MethodInfo method; - private readonly Type declaringType; public MethodTokenExpression(MethodInfo method) { this.method = method; - declaringType = method.DeclaringType; + Debug.Assert(method.DeclaringType != null); // DynamicProxy isn't using global methods nor `DynamicMethod` } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.Emit(OpCodes.Ldtoken, method); - if (declaringType == null) - { - throw new GeneratorException("declaringType can't be null for this situation"); - } - gen.Emit(OpCodes.Ldtoken, declaringType); + gen.Emit(OpCodes.Ldtoken, method.DeclaringType); var minfo = MethodBaseMethods.GetMethodFromHandle; gen.Emit(OpCodes.Call, minfo); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MultiStatementExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MultiStatementExpression.cs deleted file mode 100644 index 128afe9c..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/MultiStatementExpression.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System.Collections.Generic; - using System.Reflection.Emit; - - internal class MultiStatementExpression : Expression - { - private readonly List statements = new List(); - - public void AddStatement(Statement statement) - { - statements.Add(statement); - } - - public void AddExpression(Expression expression) - { - AddStatement(new ExpressionStatement(expression)); - } - - public override void Emit(IMemberEmitter member, ILGenerator gen) - { - foreach (Statement s in statements) - { - s.Emit(member, gen); - } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewArrayExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewArrayExpression.cs index 2e911d4c..e49da86b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewArrayExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewArrayExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,10 +17,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System; using System.Reflection.Emit; - /// - /// Summary description for NewArrayExpression. - /// - internal class NewArrayExpression : Expression + internal class NewArrayExpression : IExpression { private readonly Type arrayType; private readonly int size; @@ -31,7 +28,7 @@ public NewArrayExpression(int size, Type arrayType) this.arrayType = arrayType; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.Emit(OpCodes.Ldc_I4, size); gen.Emit(OpCodes.Newarr, arrayType); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewInstanceExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewInstanceExpression.cs index afbe3c38..87063ad2 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewInstanceExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NewInstanceExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,41 +18,31 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - internal class NewInstanceExpression : Expression + internal class NewInstanceExpression : IExpression { - private readonly Expression[] arguments; - private readonly Type[] constructorArgs; - private readonly Type type; + private readonly IExpression[] arguments; private ConstructorInfo constructor; - public NewInstanceExpression(ConstructorInfo constructor, params Expression[] args) + public NewInstanceExpression(ConstructorInfo constructor, params IExpression[] args) { - this.constructor = constructor; + this.constructor = constructor ?? throw new ArgumentNullException(nameof(constructor)); arguments = args; } - public NewInstanceExpression(Type target, Type[] constructor_args, params Expression[] args) + public NewInstanceExpression(Type target) { - type = target; - constructorArgs = constructor_args; - arguments = args; + constructor = target.GetConstructor(Type.EmptyTypes) ?? throw new MissingMethodException("Could not find default constructor."); + arguments = null; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { - foreach (var exp in arguments) - { - exp.Emit(member, gen); - } - - if (constructor == null) - { - constructor = type.GetConstructor(constructorArgs); - } - - if (constructor == null) + if (arguments != null) { - throw new ProxyGenerationException("Could not find constructor matching specified arguments"); + foreach (var exp in arguments) + { + exp.Emit(gen); + } } gen.Emit(OpCodes.Newobj, constructor); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullCoalescingOperatorExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullCoalescingOperatorExpression.cs index dc8698f9..35826b66 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullCoalescingOperatorExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullCoalescingOperatorExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,35 +17,35 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System; using System.Reflection.Emit; - internal class NullCoalescingOperatorExpression : Expression + internal class NullCoalescingOperatorExpression : IExpression { - private readonly Expression @default; - private readonly Expression expression; + private readonly IExpression @default; + private readonly IExpression expression; - public NullCoalescingOperatorExpression(Expression expression, Expression @default) + public NullCoalescingOperatorExpression(IExpression expression, IExpression @default) { if (expression == null) { - throw new ArgumentNullException("expression"); + throw new ArgumentNullException(nameof(expression)); } if (@default == null) { - throw new ArgumentNullException("default"); + throw new ArgumentNullException(nameof(@default)); } this.expression = expression; this.@default = @default; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { - expression.Emit(member, gen); + expression.Emit(gen); gen.Emit(OpCodes.Dup); var label = gen.DefineLabel(); gen.Emit(OpCodes.Brtrue_S, label); gen.Emit(OpCodes.Pop); - @default.Emit(member, gen); + @default.Emit(gen); gen.MarkLabel(label); } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullExpression.cs index 9f9727b1..237b99d3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/NullExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +16,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class NullExpression : Expression + internal class NullExpression : IExpression { public static readonly NullExpression Instance = new NullExpression(); @@ -24,7 +24,7 @@ protected NullExpression() { } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.Emit(OpCodes.Ldnull); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Reference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Reference.cs index e5658ee7..88a37170 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Reference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Reference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +16,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal abstract class Reference + internal abstract class Reference : IExpression { protected Reference owner = SelfReference.Self; @@ -45,14 +45,9 @@ public virtual void Generate(ILGenerator gen) { } - public virtual Expression ToAddressOfExpression() + public void Emit(ILGenerator gen) { - return new AddressOfReferenceExpression(this); - } - - public virtual Expression ToExpression() - { - return new ReferenceExpression(this); + ArgumentsUtil.EmitLoadOwnerAndReference(this, gen); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferencesToObjectArrayExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferencesToObjectArrayExpression.cs index 368e96a5..2b342058 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferencesToObjectArrayExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReferencesToObjectArrayExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,9 +18,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using System.Reflection; using System.Reflection.Emit; - /// - /// - internal class ReferencesToObjectArrayExpression : Expression + internal class ReferencesToObjectArrayExpression : IExpression { private readonly TypeReference[] args; @@ -29,7 +27,7 @@ public ReferencesToObjectArrayExpression(params TypeReference[] args) this.args = args; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { var local = gen.DeclareLocal(typeof(object[])); @@ -46,20 +44,22 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) ArgumentsUtil.EmitLoadOwnerAndReference(reference, gen); - if (reference.Type.GetTypeInfo().IsByRef) + if (reference.Type.IsByRef) { throw new NotSupportedException(); } - if (reference.Type.GetTypeInfo().IsPointer) - { - gen.Emit(OpCodes.Call, ArgumentsUtil.IntPtrFromPointer()); - gen.Emit(OpCodes.Box, typeof(IntPtr)); - } - if (reference.Type.GetTypeInfo().IsValueType) + + if (reference.Type.GetTypeInfo().IsPointer) + { + gen.Emit(OpCodes.Call, ArgumentsUtil.IntPtrFromPointer()); + gen.Emit(OpCodes.Box, typeof(IntPtr)); + } + + if (reference.Type.IsValueType) { gen.Emit(OpCodes.Box, reference.Type); } - else if (reference.Type.GetTypeInfo().IsGenericParameter) + else if (reference.Type.IsGenericParameter) { gen.Emit(OpCodes.Box, reference.Type); } @@ -70,4 +70,4 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) gen.Emit(OpCodes.Ldloc, local); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReturnStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReturnStatement.cs index ea98f5d2..dc0cfb80 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReturnStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ReturnStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,9 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class ReturnStatement : Statement + internal class ReturnStatement : IStatement { - private readonly Expression expression; + private readonly IExpression expression; private readonly Reference reference; public ReturnStatement() @@ -30,12 +30,12 @@ public ReturnStatement(Reference reference) this.reference = reference; } - public ReturnStatement(Expression expression) + public ReturnStatement(IExpression expression) { this.expression = expression; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { if (reference != null) { @@ -43,14 +43,7 @@ public override void Emit(IMemberEmitter member, ILGenerator gen) } else if (expression != null) { - expression.Emit(member, gen); - } - else - { - if (member.ReturnType != typeof(void)) - { - OpCodeUtil.EmitLoadOpCodeForDefaultValueOfType(gen, member.ReturnType); - } + expression.Emit(gen); } gen.Emit(OpCodes.Ret); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/SelfReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/SelfReference.cs index fcea64b7..691d6cc4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/SelfReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/SelfReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Statement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Statement.cs deleted file mode 100644 index 8e7acec3..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/Statement.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST -{ - using System.Reflection.Emit; - - internal abstract class Statement : IILEmitter - { - public abstract void Emit(IMemberEmitter member, ILGenerator gen); - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ThrowStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ThrowStatement.cs index 1c85e1d8..5ae6ac92 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ThrowStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/ThrowStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,27 +15,28 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST { using System; + using System.Reflection; using System.Reflection.Emit; - internal class ThrowStatement : Statement + internal class ThrowStatement : IStatement { private readonly string errorMessage; private readonly Type exceptionType; - public ThrowStatement(Type exceptionType, String errorMessage) + public ThrowStatement(Type exceptionType, string errorMessage) { this.exceptionType = exceptionType; this.errorMessage = errorMessage; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { - var ci = exceptionType.GetConstructor(new[] { typeof(String) }); - var constRef = new ConstReference(errorMessage); + var ci = exceptionType.GetConstructor(new[] { typeof(string) }); + var message = new LiteralStringExpression(errorMessage); - var creationStmt = new NewInstanceExpression(ci, constRef.ToExpression()); + var creationStmt = new NewInstanceExpression(ci, message); - creationStmt.Emit(member, gen); + creationStmt.Emit(gen); gen.Emit(OpCodes.Throw); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TryStatement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TryStatement.cs index e1063ef5..8258f7ca 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TryStatement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TryStatement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,9 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS { using System.Reflection.Emit; - internal class TryStatement : Statement + internal class TryStatement : IStatement { - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.BeginExceptionBlock(); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeReference.cs index d97d6669..c06ec068 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeReference.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeTokenExpression.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeTokenExpression.cs index fb57200f..f6c13525 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeTokenExpression.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/TypeTokenExpression.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -19,7 +19,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; - internal class TypeTokenExpression : Expression + internal class TypeTokenExpression : IExpression { private readonly Type type; @@ -28,7 +28,7 @@ public TypeTokenExpression(Type type) this.type = type; } - public override void Emit(IMemberEmitter member, ILGenerator gen) + public void Emit(ILGenerator gen) { gen.Emit(OpCodes.Ldtoken, type); gen.Emit(OpCodes.Call, TypeMethods.GetTypeFromHandle); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StindOpCodesDictionary.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StindOpCodesDictionary.cs index 13dadcfb..a2ec97b3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StindOpCodesDictionary.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StindOpCodesDictionary.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -49,9 +49,9 @@ private StindOpCodesDictionary() { get { - if (ContainsKey(type)) + if (TryGetValue(type, out var opCode)) { - return base[type]; + return opCode; } return EmptyOpCode; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StrongNameUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StrongNameUtil.cs index 1140c3dc..8abefb8f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StrongNameUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/StrongNameUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,47 +18,22 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters using System.Collections.Generic; using System.Linq; using System.Reflection; -#if FEATURE_SECURITY_PERMISSIONS - using System.Security; - using System.Security.Permissions; -#endif internal static class StrongNameUtil { private static readonly IDictionary signedAssemblyCache = new Dictionary(); private static readonly object lockObject = new object(); -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif - static StrongNameUtil() - { -#if FEATURE_SECURITY_PERMISSIONS - //idea after http://blogs.msdn.com/dmitryr/archive/2007/01/23/finding-out-the-current-trust-level-in-asp-net.aspx - try - { - new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); - CanStrongNameAssembly = true; - } - catch (SecurityException) - { - CanStrongNameAssembly = false; - } -#else - CanStrongNameAssembly = true; -#endif - } - public static bool IsAssemblySigned(this Assembly assembly) { lock (lockObject) { - if (signedAssemblyCache.ContainsKey(assembly) == false) + if (signedAssemblyCache.TryGetValue(assembly, out var isSigned) == false) { - var isSigned = assembly.ContainsPublicKey(); + isSigned = assembly.ContainsPublicKey(); signedAssemblyCache.Add(assembly, isSigned); } - return signedAssemblyCache[assembly]; + return isSigned; } } @@ -70,19 +45,17 @@ private static bool ContainsPublicKey(this Assembly assembly) public static bool IsAnyTypeFromUnsignedAssembly(IEnumerable types) { - return types.Any(t => t.GetTypeInfo().Assembly.IsAssemblySigned() == false); + return types.Any(t => t.Assembly.IsAssemblySigned() == false); } public static bool IsAnyTypeFromUnsignedAssembly(Type baseType, IEnumerable interfaces) { - if (baseType != null && baseType.GetTypeInfo().Assembly.IsAssemblySigned() == false) + if (baseType != null && baseType.Assembly.IsAssemblySigned() == false) { return true; } return IsAnyTypeFromUnsignedAssembly(interfaces); } - - public static bool CanStrongNameAssembly { get; set; } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/TypeConstructorEmitter.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/TypeConstructorEmitter.cs index 6b486fe9..fec82179 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/TypeConstructorEmitter.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/TypeConstructorEmitter.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,8 +18,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters internal class TypeConstructorEmitter : ConstructorEmitter { - internal TypeConstructorEmitter(AbstractTypeEmitter maintype) - : base(maintype, maintype.TypeBuilder.DefineTypeInitializer()) + internal TypeConstructorEmitter(AbstractTypeEmitter mainType) + : base(mainType, mainType.TypeBuilder.DefineTypeInitializer()) { } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ForwardingMethodGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ForwardingMethodGenerator.cs similarity index 82% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ForwardingMethodGenerator.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ForwardingMethodGenerator.cs index 3ef2eb73..89101be3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/ForwardingMethodGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/ForwardingMethodGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; @@ -30,7 +30,7 @@ public ForwardingMethodGenerator(MetaMethod method, OverrideMethodDelegate overr } protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, - ProxyGenerationOptions options, INamingScope namingScope) + INamingScope namingScope) { var targetReference = getTargetReference(@class, MethodToOverride); var arguments = ArgumentsUtil.ConvertToArgumentReferenceExpression(MethodToOverride.GetParameters()); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorException.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorException.cs deleted file mode 100644 index e29e485b..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorException.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators -{ - using System; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization; -#endif - -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal class GeneratorException : Exception - { - public GeneratorException(string message) : base(message) - { - } - - public GeneratorException(string message, Exception innerException) : base(message, innerException) - { - } - -#if FEATURE_SERIALIZATION - public GeneratorException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } -#endif - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorUtil.cs index 9e8231c8..8600c265 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/GeneratorUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,9 +14,9 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { - using System; using System.Linq; using System.Reflection; + using System.Runtime.InteropServices; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; @@ -28,24 +28,26 @@ public static void CopyOutAndRefParameters(TypeReference[] dereferencedArguments MethodInfo method, MethodEmitter emitter) { var parameters = method.GetParameters(); - if (!parameters.Any(IsByRef)) - { - return; //saving the need to create locals if there is no need - } - var arguments = StoreInvocationArgumentsInLocal(emitter, invocation); + // Create it only if there are byref writable arguments. + LocalReference arguments = null; for (var i = 0; i < parameters.Length; i++) { if (IsByRef(parameters[i]) && !IsReadOnly(parameters[i])) { + if (arguments == null) + { + arguments = StoreInvocationArgumentsInLocal(emitter, invocation); + } + emitter.CodeBuilder.AddStatement(AssignArgument(dereferencedArguments, i, arguments)); } } bool IsByRef(ParameterInfo parameter) { - return parameter.ParameterType.GetTypeInfo().IsByRef; + return parameter.ParameterType.IsByRef; } bool IsReadOnly(ParameterInfo parameter) @@ -74,25 +76,32 @@ bool IsReadOnly(ParameterInfo parameter) // // The above points inform the following detection logic: First, we rely on an IL // `[in]` modifier being present. This is a "fast guard" against non-`in` parameters: - if ((parameter.Attributes & (ParameterAttributes.In | ParameterAttributes.Out)) == ParameterAttributes.In) + if ((parameter.Attributes & (ParameterAttributes.In | ParameterAttributes.Out)) != ParameterAttributes.In) { - // Here we perform the actual check. We don't rely on cmods because support - // for them is at current too unreliable in general, and because we wouldn't - // be saving much time anyway. - if (parameter.GetCustomAttributes(false).Any(IsIsReadOnlyAttribute)) - { - return true; - } + return false; } - return false; + // This check allows to make the detection logic more robust on the platforms which support custom modifiers. + // The robustness is achieved by the fact, that usually the `IsReadOnlyAttribute` emitted by the compiler is internal to the assembly. + // Therefore, if clients use Reflection.Emit to create "a copy" of the methods with read-only members, they cannot re-use the existing attribute. + // Instead, they are forced to emit their own `IsReadOnlyAttribute` to mark some argument as immutable. + // The `InAttribute` type OTOH was always available in BCL. Therefore, it's much easier to copy the modreq and be recognized by Castle. + // + // If check fails, resort to the IsReadOnlyAttribute check. + // Check for the required modifiers first, as it's faster. + if (parameter.GetRequiredCustomModifiers().Any(x => x == typeof(InAttribute))) + { + return true; + } - bool IsIsReadOnlyAttribute(object attribute) + // The comparison by name is intentional; any assembly could define that attribute. + // See explanation in comment above. + if (parameter.GetCustomAttributes(false).Any(x => x.GetType().FullName == "System.Runtime.CompilerServices.IsReadOnlyAttribute")) { - // The comparison by name is intentional; any assembly could define that attribute. - // See explanation in comment above. - return attribute.GetType().FullName == "System.Runtime.CompilerServices.IsReadOnlyAttribute"; + return true; } + + return false; } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IGenerator.cs index 0b263d84..3818439b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/IGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +18,6 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators internal interface IGenerator { - T Generate(ClassEmitter @class, ProxyGenerationOptions options, INamingScope namingScope); + T Generate(ClassEmitter @class, INamingScope namingScope); } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/INamingScope.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/INamingScope.cs index fb5440b4..700ed297 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/INamingScope.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/INamingScope.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InheritanceInvocationTypeGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InheritanceInvocationTypeGenerator.cs index 6d8c9627..03a81682 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InheritanceInvocationTypeGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InheritanceInvocationTypeGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,6 +17,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using System; using System.Reflection; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; @@ -32,7 +33,6 @@ public InheritanceInvocationTypeGenerator(Type targetType, MetaMethod method, Me } protected override ArgumentReference[] GetBaseCtorArguments(Type targetFieldType, - ProxyGenerationOptions proxyGenerationOptions, out ConstructorInfo baseConstructor) { baseConstructor = InvocationMethods.InheritanceInvocationConstructor; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetGenerator.cs index 1d4f2e26..9a4053ad 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,71 +17,38 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using System; using System.Collections.Generic; using System.Linq; - using System.Reflection; -#if FEATURE_SERIALIZATION - using System.Xml.Serialization; -#endif - - using Telerik.JustMock.Core.Castle.DynamicProxy; - using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; - internal class InterfaceProxyWithTargetGenerator : BaseProxyGenerator + internal sealed class InterfaceProxyWithTargetGenerator : BaseInterfaceProxyGenerator { - protected FieldReference targetField; + public InterfaceProxyWithTargetGenerator(ModuleScope scope, Type targetType, Type[] interfaces, + Type proxyTargetType, ProxyGenerationOptions options) + : base(scope, targetType, interfaces, proxyTargetType, options) + { } - public InterfaceProxyWithTargetGenerator(ModuleScope scope, Type @interface) - : base(scope, @interface) - { - CheckNotGenericTypeDefinition(@interface, "@interface"); - } + protected override bool AllowChangeTarget => false; - protected virtual bool AllowChangeTarget - { - get { return false; } - } + protected override string GeneratorType => ProxyTypeConstants.InterfaceWithTarget; - protected virtual string GeneratorType + protected override CompositeTypeContributor GetProxyTargetContributor(Type proxyTargetType, INamingScope namingScope) { - get { return ProxyTypeConstants.InterfaceWithTarget; } + return new InterfaceProxyTargetContributor(proxyTargetType, AllowChangeTarget, namingScope) { Logger = Logger }; } - public Type GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options) + protected override ProxyTargetAccessorContributor GetProxyTargetAccessorContributor() { - // make sure ProxyGenerationOptions is initialized - options.Initialize(); - - CheckNotGenericTypeDefinition(proxyTargetType, "proxyTargetType"); - CheckNotGenericTypeDefinitions(interfaces, "interfaces"); - EnsureValidBaseType(options.BaseTypeForInterfaceProxy); - ProxyGenerationOptions = options; - - interfaces = TypeUtil.GetAllInterfaces(interfaces); - var cacheKey = new CacheKey(proxyTargetType.GetTypeInfo(), targetType, interfaces, options); - - return ObtainProxyType(cacheKey, (n, s) => GenerateType(n, proxyTargetType, interfaces, s)); + return new ProxyTargetAccessorContributor( + getTargetReference: () => targetField, + proxyTargetType); } - protected virtual ITypeContributor AddMappingForTargetType(IDictionary typeImplementerMapping, - Type proxyTargetType, ICollection targetInterfaces, - ICollection additionalInterfaces, - INamingScope namingScope) + protected override void AddMappingForAdditionalInterfaces(CompositeTypeContributor contributor, Type[] proxiedInterfaces, + IDictionary typeImplementerMapping, + ICollection targetInterfaces) { - var contributor = new InterfaceProxyTargetContributor(proxyTargetType, AllowChangeTarget, namingScope) - { Logger = Logger }; - var proxiedInterfaces = targetType.GetAllInterfaces(); - foreach (var @interface in proxiedInterfaces) - { - contributor.AddInterfaceToProxy(@interface); - AddMappingNoCheck(@interface, contributor, typeImplementerMapping); - } - - foreach (var @interface in additionalInterfaces) + foreach (var @interface in interfaces) { if (!ImplementedByTarget(targetInterfaces, @interface) || proxiedInterfaces.Contains(@interface)) { @@ -91,218 +58,11 @@ protected virtual ITypeContributor AddMappingForTargetType(IDictionary(); - } -#endif - - protected virtual Type GenerateType(string typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope) - { - IEnumerable contributors; - var allInterfaces = GetTypeImplementerMapping(interfaces, proxyTargetType, out contributors, namingScope); - - ClassEmitter emitter; - FieldReference interceptorsField; - var baseType = Init(typeName, out emitter, proxyTargetType, out interceptorsField, allInterfaces); - - var model = new MetaType(); - // Collect methods - foreach (var contributor in contributors) - { - contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); - } - - ProxyGenerationOptions.Hook.MethodsInspected(); - - // Constructor - - var cctor = GenerateStaticConstructor(emitter); - var ctorArguments = new List(); - - foreach (var contributor in contributors) - { - contributor.Generate(emitter, ProxyGenerationOptions); - - // TODO: redo it - if (contributor is MixinContributor) - { - ctorArguments.AddRange((contributor as MixinContributor).Fields); - } - } - - ctorArguments.Add(interceptorsField); - ctorArguments.Add(targetField); - var selector = emitter.GetField("__selector"); - if (selector != null) - { - ctorArguments.Add(selector); - } - - GenerateConstructors(emitter, baseType, ctorArguments.ToArray()); - - // Complete type initializer code body - CompleteInitCacheMethod(cctor.CodeBuilder); - - // Crosses fingers and build type - var generatedType = emitter.BuildType(); - - InitializeStaticFields(generatedType); - return generatedType; - } - - protected virtual InterfaceProxyWithoutTargetContributor GetContributorForAdditionalInterfaces( - INamingScope namingScope) - { - return new InterfaceProxyWithoutTargetContributor(namingScope, (c, m) => NullExpression.Instance) { Logger = Logger }; - } - - protected virtual IEnumerable GetTypeImplementerMapping(Type[] interfaces, Type proxyTargetType, - out IEnumerable contributors, - INamingScope namingScope) - { - IDictionary typeImplementerMapping = new Dictionary(); - var mixins = new MixinContributor(namingScope, AllowChangeTarget) { Logger = Logger }; - // Order of interface precedence: - // 1. first target - var targetInterfaces = proxyTargetType.GetAllInterfaces(); - var additionalInterfaces = TypeUtil.GetAllInterfaces(interfaces); - var target = AddMappingForTargetType(typeImplementerMapping, proxyTargetType, targetInterfaces, additionalInterfaces, - namingScope); - - // 2. then mixins - if (ProxyGenerationOptions.HasMixins) - { - foreach (var mixinInterface in ProxyGenerationOptions.MixinData.MixinInterfaces) - { - if (targetInterfaces.Contains(mixinInterface)) - { - // OK, so the target implements this interface. We now do one of two things: - if (additionalInterfaces.Contains(mixinInterface)) - { - // we intercept the interface, and forward calls to the target type - AddMapping(mixinInterface, target, typeImplementerMapping); - } - // we do not intercept the interface - mixins.AddEmptyInterface(mixinInterface); - } - else - { - if (!typeImplementerMapping.ContainsKey(mixinInterface)) - { - mixins.AddInterfaceToProxy(mixinInterface); - typeImplementerMapping.Add(mixinInterface, mixins); - } - } - } - } - - var additionalInterfacesContributor = GetContributorForAdditionalInterfaces(namingScope); - // 3. then additional interfaces - foreach (var @interface in additionalInterfaces) - { - if (typeImplementerMapping.ContainsKey(@interface)) - { - continue; - } - if (ProxyGenerationOptions.MixinData.ContainsMixin(@interface)) - { - continue; - } - - additionalInterfacesContributor.AddInterfaceToProxy(@interface); - AddMappingNoCheck(@interface, additionalInterfacesContributor, typeImplementerMapping); - } - - // 4. plus special interfaces - var instance = new InterfaceProxyInstanceContributor(targetType, GeneratorType, interfaces); -#if FEATURE_SERIALIZATION - AddMappingForISerializable(typeImplementerMapping, instance); -#endif - try - { - AddMappingNoCheck(typeof(IProxyTargetAccessor), instance, typeImplementerMapping); - } - catch (ArgumentException) - { - HandleExplicitlyPassedProxyTargetAccessor(targetInterfaces, additionalInterfaces); - } - - contributors = new List - { - target, - additionalInterfacesContributor, - mixins, - instance - }; - return typeImplementerMapping.Keys; - } - - protected virtual Type Init(string typeName, out ClassEmitter emitter, Type proxyTargetType, - out FieldReference interceptorsField, IEnumerable interfaces) - { - var baseType = ProxyGenerationOptions.BaseTypeForInterfaceProxy; - - emitter = BuildClassEmitter(typeName, baseType, interfaces); - - CreateFields(emitter, proxyTargetType); - CreateTypeAttributes(emitter); - - interceptorsField = emitter.GetField("__interceptors"); - return baseType; - } - - private void CreateFields(ClassEmitter emitter, Type proxyTargetType) - { - base.CreateFields(emitter); - targetField = emitter.CreateField("__target", proxyTargetType); -#if FEATURE_SERIALIZATION - emitter.DefineCustomAttributeFor(targetField); -#endif - } - - private void EnsureValidBaseType(Type type) - { - if (type == null) - { - throw new ArgumentException( - "Base type for proxy is null reference. Please set it to System.Object or some other valid type."); - } - - if (!type.GetTypeInfo().IsClass) - { - ThrowInvalidBaseType(type, "it is not a class type"); - } - - if (type.GetTypeInfo().IsSealed) - { - ThrowInvalidBaseType(type, "it is sealed"); - } - - var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - null, Type.EmptyTypes, null); - - if (constructor == null || constructor.IsPrivate) - { - ThrowInvalidBaseType(type, "it does not have accessible parameterless constructor"); - } } private bool ImplementedByTarget(ICollection targetInterfaces, Type @interface) { return targetInterfaces.Contains(@interface); } - - private void ThrowInvalidBaseType(Type type, string doesNotHaveAccessibleParameterlessConstructor) - { - var format = - "Type {0} is not valid base type for interface proxy, because {1}. Only a non-sealed class with non-private default constructor can be used as base type for interface proxy. Please use some other valid type."; - throw new ArgumentException(string.Format(format, type, doesNotHaveAccessibleParameterlessConstructor)); - } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetInterfaceGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetInterfaceGenerator.cs index 8698ff81..538b6f34 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetInterfaceGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithTargetInterfaceGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -24,38 +24,34 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; - internal class InterfaceProxyWithTargetInterfaceGenerator : InterfaceProxyWithTargetGenerator + internal sealed class InterfaceProxyWithTargetInterfaceGenerator : BaseInterfaceProxyGenerator { - public InterfaceProxyWithTargetInterfaceGenerator(ModuleScope scope, Type @interface) - : base(scope, @interface) + public InterfaceProxyWithTargetInterfaceGenerator(ModuleScope scope, Type targetType, Type[] interfaces, + Type proxyTargetType, ProxyGenerationOptions options) + : base(scope, targetType, interfaces, proxyTargetType, options) { } - protected override bool AllowChangeTarget + protected override bool AllowChangeTarget => true; + + protected override string GeneratorType => ProxyTypeConstants.InterfaceWithTargetInterface; + + protected override CompositeTypeContributor GetProxyTargetContributor(Type proxyTargetType, INamingScope namingScope) { - get { return true; } + return new InterfaceProxyWithTargetInterfaceTargetContributor(proxyTargetType, AllowChangeTarget, namingScope) { Logger = Logger }; } - protected override string GeneratorType + protected override ProxyTargetAccessorContributor GetProxyTargetAccessorContributor() { - get { return ProxyTypeConstants.InterfaceWithTargetInterface; } + return new ProxyTargetAccessorContributor( + getTargetReference: () => targetField, + proxyTargetType); } - protected override ITypeContributor AddMappingForTargetType( - IDictionary typeImplementerMapping, Type proxyTargetType, ICollection targetInterfaces, - ICollection additionalInterfaces, INamingScope namingScope) + protected override void AddMappingForAdditionalInterfaces(CompositeTypeContributor contributor, Type[] proxiedInterfaces, + IDictionary typeImplementerMapping, + ICollection targetInterfaces) { - var contributor = new InterfaceProxyWithTargetInterfaceTargetContributor( - proxyTargetType, - AllowChangeTarget, - namingScope) { Logger = Logger }; - foreach (var @interface in targetType.GetAllInterfaces()) - { - contributor.AddInterfaceToProxy(@interface); - AddMappingNoCheck(@interface, contributor, typeImplementerMapping); - } - - return contributor; } protected override InterfaceProxyWithoutTargetContributor GetContributorForAdditionalInterfaces( @@ -70,9 +66,9 @@ private Reference GetTarget(ClassEmitter @class, MethodInfo method) return new AsTypeReference(@class.GetField("__target"), method.DeclaringType); } - private Expression GetTargetExpression(ClassEmitter @class, MethodInfo method) + private IExpression GetTargetExpression(ClassEmitter @class, MethodInfo method) { - return GetTarget(@class, method).ToExpression(); + return GetTarget(@class, method); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithoutTargetGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithoutTargetGenerator.cs index 6e14a532..4d072b11 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithoutTargetGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InterfaceProxyWithoutTargetGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,89 +16,44 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Collections.Generic; - using Telerik.JustMock.Core.Castle.Core.Logging; - using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; - internal class InterfaceProxyWithoutTargetGenerator : InterfaceProxyWithTargetGenerator + internal sealed class InterfaceProxyWithoutTargetGenerator : BaseInterfaceProxyGenerator { - public InterfaceProxyWithoutTargetGenerator(ModuleScope scope, Type @interface) : base(scope, @interface) + public InterfaceProxyWithoutTargetGenerator(ModuleScope scope, Type targetType, Type[] interfaces, + Type proxyTargetType, ProxyGenerationOptions options) + : base(scope, targetType, interfaces, proxyTargetType, options) { } - protected override string GeneratorType + protected override bool AllowChangeTarget => false; + + protected override string GeneratorType => ProxyTypeConstants.InterfaceWithoutTarget; + + protected override CompositeTypeContributor GetProxyTargetContributor(Type proxyTargetType, INamingScope namingScope) { - get { return ProxyTypeConstants.InterfaceWithoutTarget; } + return new InterfaceProxyWithoutTargetContributor(namingScope, (c, m) => NullExpression.Instance) { Logger = Logger }; } - protected override ITypeContributor AddMappingForTargetType( - IDictionary interfaceTypeImplementerMapping, Type proxyTargetType, - ICollection targetInterfaces, ICollection additionalInterfaces, INamingScope namingScope) + protected override ProxyTargetAccessorContributor GetProxyTargetAccessorContributor() { - var contributor = new InterfaceProxyWithoutTargetContributor(namingScope, (c, m) => NullExpression.Instance) - { Logger = this.Logger }; - foreach (var @interface in targetType.GetAllInterfaces()) - { - contributor.AddInterfaceToProxy(@interface); - AddMappingNoCheck(@interface, contributor, interfaceTypeImplementerMapping); - } - return contributor; + return new ProxyTargetAccessorContributor( + getTargetReference: () => targetField, + proxyTargetType); } - protected override Type GenerateType(string typeName, Type proxyTargetType, Type[] interfaces, - INamingScope namingScope) + protected override void AddMappingForAdditionalInterfaces(CompositeTypeContributor contributor, Type[] proxiedInterfaces, + IDictionary typeImplementerMapping, + ICollection targetInterfaces) { - IEnumerable contributors; - var allInterfaces = GetTypeImplementerMapping(interfaces, targetType, out contributors, namingScope); - var model = new MetaType(); - // collect elements - foreach (var contributor in contributors) - { - contributor.CollectElementsToProxy(ProxyGenerationOptions.Hook, model); - } - - ProxyGenerationOptions.Hook.MethodsInspected(); - - ClassEmitter emitter; - FieldReference interceptorsField; - var baseType = Init(typeName, out emitter, proxyTargetType, out interceptorsField, allInterfaces); - - // Constructor - - var cctor = GenerateStaticConstructor(emitter); - var mixinFieldsList = new List(); - - foreach (var contributor in contributors) - { - contributor.Generate(emitter, ProxyGenerationOptions); - - // TODO: redo it - if (contributor is MixinContributor) - { - mixinFieldsList.AddRange((contributor as MixinContributor).Fields); - } - } - - var ctorArguments = new List(mixinFieldsList) { interceptorsField, targetField }; - var selector = emitter.GetField("__selector"); - if (selector != null) - { - ctorArguments.Add(selector); - } - - GenerateConstructors(emitter, baseType, ctorArguments.ToArray()); - - // Complete type initializer code body - CompleteInitCacheMethod(cctor.CodeBuilder); - - // Crosses fingers and build type - var generatedType = emitter.BuildType(); + } - InitializeStaticFields(generatedType); - return generatedType; + protected override IEnumerable GetTypeImplementerMapping(Type _, out IEnumerable contributors, INamingScope namingScope) + { + return base.GetTypeImplementerMapping(proxyTargetType: targetType, out contributors, namingScope); } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InvocationTypeGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InvocationTypeGenerator.cs index de4ef8e4..79e81aa7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InvocationTypeGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/InvocationTypeGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,8 +18,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using System.Collections.Generic; using System.Reflection; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens; @@ -46,18 +46,14 @@ protected InvocationTypeGenerator(Type targetType, MetaMethod method, MethodInfo /// Generates the constructor for the class that extends /// /// - /// - /// - /// protected abstract ArgumentReference[] GetBaseCtorArguments(Type targetFieldType, - ProxyGenerationOptions proxyGenerationOptions, out ConstructorInfo baseConstructor); protected abstract Type GetBaseType(); protected abstract FieldReference GetTargetReference(); - public AbstractTypeEmitter Generate(ClassEmitter @class, ProxyGenerationOptions options, INamingScope namingScope) + public AbstractTypeEmitter Generate(ClassEmitter @class, INamingScope namingScope) { var methodInfo = method.Method; @@ -73,7 +69,7 @@ public AbstractTypeEmitter Generate(ClassEmitter @class, ProxyGenerationOptions // targetType cannot be a generic type definition (YET!) invocation.CopyGenericParametersFromMethod(methodInfo); - CreateConstructor(invocation, options); + CreateConstructor(invocation); var targetField = GetTargetReference(); if (canChangeTarget) @@ -81,7 +77,7 @@ public AbstractTypeEmitter Generate(ClassEmitter @class, ProxyGenerationOptions ImplementChangeProxyTargetInterface(@class, invocation, targetField); } - ImplemementInvokeMethodOnTarget(invocation, methodInfo.GetParameters(), targetField, callback); + ImplementInvokeMethodOnTarget(invocation, methodInfo.GetParameters(), targetField, callback); #if FEATURE_SERIALIZATION invocation.DefineCustomAttribute(); @@ -91,7 +87,7 @@ public AbstractTypeEmitter Generate(ClassEmitter @class, ProxyGenerationOptions } protected virtual MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, - Expression[] args, MethodInfo callbackMethod, + IExpression[] args, MethodInfo callbackMethod, Reference targetField, MethodEmitter invokeMethodOnTarget) { @@ -117,12 +113,7 @@ protected virtual void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocat return; } - if (canChangeTarget) - { - EmitCallEnsureValidTarget(invokeMethodOnTarget); - } - - var args = new Expression[parameters.Length]; + var args = new IExpression[parameters.Length]; // Idea: instead of grab parameters one by one // we should grab an array @@ -144,7 +135,7 @@ protected virtual void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocat InvocationMethods.GetArgumentValue, new LiteralIntExpression(i))))); var byRefReference = new ByRefReference(localReference); - args[i] = new ReferenceExpression(byRefReference); + args[i] = byRefReference; byRefArguments[i] = localReference; } else @@ -173,7 +164,7 @@ protected virtual void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocat } else { - invokeMethodOnTarget.CodeBuilder.AddStatement(new ExpressionStatement(methodOnTargetInvocationExpression)); + invokeMethodOnTarget.CodeBuilder.AddStatement(methodOnTargetInvocationExpression); } AssignBackByRefArguments(invokeMethodOnTarget, byRefArguments); @@ -183,9 +174,9 @@ protected virtual void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocat var setRetVal = new MethodInvocationExpression(SelfReference.Self, InvocationMethods.SetReturnValue, - new ConvertExpression(typeof(object), returnValue.Type, returnValue.ToExpression())); + new ConvertExpression(typeof(object), returnValue.Type, returnValue)); - invokeMethodOnTarget.CodeBuilder.AddStatement(new ExpressionStatement(setRetVal)); + invokeMethodOnTarget.CodeBuilder.AddStatement(setRetVal); } invokeMethodOnTarget.CodeBuilder.AddStatement(new ReturnStatement()); @@ -204,27 +195,25 @@ private void AssignBackByRefArguments(MethodEmitter invokeMethodOnTarget, Dictio var index = byRefArgument.Key; var localReference = byRefArgument.Value; invokeMethodOnTarget.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression( - SelfReference.Self, - InvocationMethods.SetArgumentValue, - new LiteralIntExpression(index), - new ConvertExpression( - typeof(object), - localReference.Type, - new ReferenceExpression(localReference))) - )); + new MethodInvocationExpression( + SelfReference.Self, + InvocationMethods.SetArgumentValue, + new LiteralIntExpression(index), + new ConvertExpression( + typeof(object), + localReference.Type, + localReference))); } invokeMethodOnTarget.CodeBuilder.AddStatement(new EndExceptionBlockStatement()); } - private void CreateConstructor(AbstractTypeEmitter invocation, ProxyGenerationOptions options) + private void CreateConstructor(AbstractTypeEmitter invocation) { ConstructorInfo baseConstructor; - var baseCtorArguments = GetBaseCtorArguments(targetType, options, out baseConstructor); + var baseCtorArguments = GetBaseCtorArguments(targetType, out baseConstructor); var constructor = CreateConstructor(invocation, baseCtorArguments); - constructor.CodeBuilder.InvokeBaseConstructor(baseConstructor, baseCtorArguments); + constructor.CodeBuilder.AddStatement(new ConstructorInvocationStatement(baseConstructor, baseCtorArguments)); constructor.CodeBuilder.AddStatement(new ReturnStatement()); } @@ -237,16 +226,9 @@ private ConstructorEmitter CreateConstructor(AbstractTypeEmitter invocation, Arg return contributor.CreateConstructor(baseCtorArguments, invocation); } - private AbstractCodeBuilder EmitCallEnsureValidTarget(MethodEmitter invokeMethodOnTarget) - { - return invokeMethodOnTarget.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression(SelfReference.Self, InvocationMethods.EnsureValidTarget))); - } - private void EmitCallThrowOnNoTarget(MethodEmitter invokeMethodOnTarget) { - var throwOnNoTarget = new ExpressionStatement(new MethodInvocationExpression(InvocationMethods.ThrowOnNoTarget)); + var throwOnNoTarget = new MethodInvocationExpression(InvocationMethods.ThrowOnNoTarget); invokeMethodOnTarget.CodeBuilder.AddStatement(throwOnNoTarget); invokeMethodOnTarget.CodeBuilder.AddStatement(new ReturnStatement()); @@ -281,8 +263,8 @@ private AbstractTypeEmitter GetEmitter(ClassEmitter @class, Type[] interfaces, I return new ClassEmitter(@class.ModuleScope, uniqueName, GetBaseType(), interfaces, ClassEmitter.DefaultAttributes, forceUnsigned: @class.InStrongNamedModule == false); } - private void ImplemementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters, - FieldReference targetField, MethodInfo callbackMethod) + private void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters, + FieldReference targetField, MethodInfo callbackMethod) { var invokeMethodOnTarget = invocation.CreateMethod("InvokeMethodOnTarget", typeof(void)); ImplementInvokeMethodOnTarget(invocation, parameters, invokeMethodOnTarget, targetField); @@ -293,7 +275,7 @@ private void ImplementChangeInvocationTarget(AbstractTypeEmitter invocation, Fie var changeInvocationTarget = invocation.CreateMethod("ChangeInvocationTarget", typeof(void), new[] { typeof(object) }); changeInvocationTarget.CodeBuilder.AddStatement( new AssignStatement(targetField, - new ConvertExpression(targetType, changeInvocationTarget.Arguments[0].ToExpression()))); + new ConvertExpression(targetType, changeInvocationTarget.Arguments[0]))); changeInvocationTarget.CodeBuilder.AddStatement(new ReturnStatement()); } @@ -305,16 +287,15 @@ private void ImplementChangeProxyTarget(AbstractTypeEmitter invocation, ClassEmi var localProxy = changeProxyTarget.CodeBuilder.DeclareLocal(typeof(IProxyTargetAccessor)); changeProxyTarget.CodeBuilder.AddStatement( new AssignStatement(localProxy, - new ConvertExpression(localProxy.Type, proxyObject.ToExpression()))); + new ConvertExpression(localProxy.Type, proxyObject))); var dynSetProxy = typeof(IProxyTargetAccessor).GetMethod(nameof(IProxyTargetAccessor.DynProxySetTarget)); changeProxyTarget.CodeBuilder.AddStatement( - new ExpressionStatement( - new MethodInvocationExpression(localProxy, dynSetProxy, changeProxyTarget.Arguments[0].ToExpression()) - { - VirtualCall = true - })); + new MethodInvocationExpression(localProxy, dynSetProxy, changeProxyTarget.Arguments[0]) + { + VirtualCall = true + }); changeProxyTarget.CodeBuilder.AddStatement(new ReturnStatement()); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaEvent.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaEvent.cs index 6a2bf4ee..effa7247 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaEvent.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaEvent.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -23,33 +23,26 @@ internal class MetaEvent : MetaTypeElement, IEquatable { private readonly MetaMethod adder; private readonly MetaMethod remover; - private readonly Type type; private EventEmitter emitter; - private string name; /// /// Initializes a new instance of the class. /// - /// The name. - /// Type declaring the original event being overridden, or null. - /// + /// The event. /// The add method. /// The remove method. /// The attributes. - public MetaEvent(string name, Type declaringType, Type eventDelegateType, MetaMethod adder, MetaMethod remover, - EventAttributes attributes) - : base(declaringType) + public MetaEvent(EventInfo @event, MetaMethod adder, MetaMethod remover, EventAttributes attributes) + : base(@event) { if (adder == null) { - throw new ArgumentNullException("adder"); + throw new ArgumentNullException(nameof(adder)); } if (remover == null) { - throw new ArgumentNullException("remover"); + throw new ArgumentNullException(nameof(remover)); } - this.name = name; - type = eventDelegateType; this.adder = adder; this.remover = remover; Attributes = attributes; @@ -81,13 +74,18 @@ public MetaMethod Remover get { return remover; } } + private Type Type + { + get { return ((EventInfo)Member).EventHandlerType; } + } + public void BuildEventEmitter(ClassEmitter classEmitter) { if (emitter != null) { throw new InvalidOperationException(); } - emitter = classEmitter.CreateEvent(name, Attributes, type); + emitter = classEmitter.CreateEvent(Name, Attributes, Type); } public override bool Equals(object obj) @@ -130,12 +128,7 @@ public bool Equals(MetaEvent other) return true; } - if (!type.Equals(other.type)) - { - return false; - } - - if (!StringComparer.OrdinalIgnoreCase.Equals(name, other.name)) + if (!StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name)) { return false; } @@ -143,9 +136,9 @@ public bool Equals(MetaEvent other) return true; } - internal override void SwitchToExplicitImplementation() + public override void SwitchToExplicitImplementation() { - name = MetaTypeElementUtil.CreateNameForExplicitImplementation(sourceType, name); + SwitchToExplicitImplementationName(); adder.SwitchToExplicitImplementation(); remover.SwitchToExplicitImplementation(); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaMethod.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaMethod.cs index 65a8f32c..35ea285d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaMethod.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaMethod.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -27,13 +27,10 @@ internal class MetaMethod : MetaTypeElement, IEquatable MethodAttributes.NewSlot | MethodAttributes.Final; - private string name; - public MetaMethod(MethodInfo method, MethodInfo methodOnTarget, bool standalone, bool proxyable, bool hasTarget) - : base(method.DeclaringType) + : base(method) { Method = method; - name = method.Name; MethodOnTarget = methodOnTarget; Standalone = standalone; Proxyable = proxyable; @@ -47,10 +44,7 @@ public MetaMethod(MethodInfo method, MethodInfo methodOnTarget, bool standalone, public MethodInfo MethodOnTarget { get; private set; } - public string Name - { - get { return name; } - } + public bool Ignore { get; internal set; } public bool Proxyable { get; private set; } @@ -67,13 +61,13 @@ public bool Equals(MetaMethod other) return true; } - if (!StringComparer.OrdinalIgnoreCase.Equals(name, other.name)) + if (!StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name)) { return false; } var comparer = MethodSignatureComparer.Instance; - if (!comparer.EqualSignatureTypes(Method.ReturnType, other.Method.ReturnType)) + if (!comparer.EqualReturnTypes(Method, other.Method)) { return false; } @@ -91,7 +85,7 @@ public bool Equals(MetaMethod other) return true; } - internal override void SwitchToExplicitImplementation() + public override void SwitchToExplicitImplementation() { Attributes = ExplicitImplementationAttributes; if (Standalone == false) @@ -99,7 +93,7 @@ internal override void SwitchToExplicitImplementation() Attributes |= MethodAttributes.SpecialName; } - name = MetaTypeElementUtil.CreateNameForExplicitImplementation(sourceType, Method.Name); + SwitchToExplicitImplementationName(); } private MethodAttributes ObtainAttributes() @@ -107,7 +101,7 @@ private MethodAttributes ObtainAttributes() var methodInfo = Method; var attributes = MethodAttributes.Virtual; - if (methodInfo.IsFinal || Method.DeclaringType.GetTypeInfo().IsInterface) + if (methodInfo.IsFinal || Method.DeclaringType.IsInterface) { attributes |= MethodAttributes.NewSlot; } @@ -122,7 +116,7 @@ private MethodAttributes ObtainAttributes() attributes |= MethodAttributes.HideBySig; } if (ProxyUtil.IsInternal(methodInfo) && - ProxyUtil.AreInternalsVisibleToDynamicProxy(methodInfo.DeclaringType.GetTypeInfo().Assembly)) + ProxyUtil.AreInternalsVisibleToDynamicProxy(methodInfo.DeclaringType.Assembly)) { attributes |= MethodAttributes.Assembly; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaProperty.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaProperty.cs index 9a738e5f..879e0dd7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaProperty.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaProperty.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -28,16 +28,12 @@ internal class MetaProperty : MetaTypeElement, IEquatable private readonly IEnumerable customAttributes; private readonly MetaMethod getter; private readonly MetaMethod setter; - private readonly Type type; private PropertyEmitter emitter; - private string name; - public MetaProperty(string name, Type propertyType, Type declaringType, MetaMethod getter, MetaMethod setter, + public MetaProperty(PropertyInfo property, MetaMethod getter, MetaMethod setter, IEnumerable customAttributes, Type[] arguments) - : base(declaringType) + : base(property) { - this.name = name; - type = propertyType; this.getter = getter; this.setter = setter; attributes = PropertyAttributes.None; @@ -107,6 +103,11 @@ public MetaMethod Setter get { return setter; } } + private Type Type + { + get { return ((PropertyInfo)Member).PropertyType; } + } + public void BuildPropertyEmitter(ClassEmitter classEmitter) { if (emitter != null) @@ -114,7 +115,7 @@ public void BuildPropertyEmitter(ClassEmitter classEmitter) throw new InvalidOperationException("Emitter is already created. It is illegal to invoke this method twice."); } - emitter = classEmitter.CreateProperty(name, attributes, type, arguments); + emitter = classEmitter.CreateProperty(Name, attributes, Type, arguments); foreach (var attribute in customAttributes) { emitter.DefineCustomAttribute(attribute); @@ -158,12 +159,7 @@ public bool Equals(MetaProperty other) return true; } - if (!type.Equals(other.type)) - { - return false; - } - - if (!StringComparer.OrdinalIgnoreCase.Equals(name, other.name)) + if (!StringComparer.OrdinalIgnoreCase.Equals(Name, other.Name)) { return false; } @@ -182,9 +178,9 @@ public bool Equals(MetaProperty other) return true; } - internal override void SwitchToExplicitImplementation() + public override void SwitchToExplicitImplementation() { - name = MetaTypeElementUtil.CreateNameForExplicitImplementation(sourceType, name); + SwitchToExplicitImplementationName(); if (setter != null) { setter.SwitchToExplicitImplementation(); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaType.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaType.cs index 523e1031..3fcb9334 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaType.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaType.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,12 +15,14 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System.Collections.Generic; + using System.Reflection; internal class MetaType { - private readonly ICollection events = new TypeElementCollection(); - private readonly ICollection methods = new TypeElementCollection(); - private readonly ICollection properties = new TypeElementCollection(); + private readonly MetaTypeElementCollection events = new MetaTypeElementCollection(); + private readonly MetaTypeElementCollection methods = new MetaTypeElementCollection(); + private readonly Dictionary methodsIndex = new Dictionary(); + private readonly MetaTypeElementCollection properties = new MetaTypeElementCollection(); public IEnumerable Events { @@ -46,11 +48,17 @@ public void AddEvent(MetaEvent @event) public void AddMethod(MetaMethod method) { methods.Add(method); + methodsIndex.Add(method.Method, method); // shouldn't get added twice } public void AddProperty(MetaProperty property) { properties.Add(property); } + + public MetaMethod FindMethod(MethodInfo method) + { + return methodsIndex.TryGetValue(method, out var metaMethod) ? metaMethod : null; + } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElement.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElement.cs index 27cef517..b0b3c741 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElement.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElement.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,22 +15,85 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; + using System.Diagnostics; using System.Reflection; + using System.Text; internal abstract class MetaTypeElement { - protected readonly Type sourceType; + private readonly MemberInfo member; + private string name; - protected MetaTypeElement(Type sourceType) + protected MetaTypeElement(MemberInfo member) { - this.sourceType = sourceType; + this.member = member; + this.name = member.Name; } - internal bool CanBeImplementedExplicitly + public bool CanBeImplementedExplicitly { - get { return sourceType != null && sourceType.GetTypeInfo().IsInterface; } + get { return member.DeclaringType?.IsInterface ?? false; } } - internal abstract void SwitchToExplicitImplementation(); + public string Name + { + get { return name; } + } + + protected MemberInfo Member + { + get { return member; } + } + + public abstract void SwitchToExplicitImplementation(); + + protected void SwitchToExplicitImplementationName() + { + var name = member.Name; + var sourceType = member.DeclaringType; + var ns = sourceType.Namespace; + Debug.Assert(ns == null || ns != ""); + + if (sourceType.IsGenericType) + { + var nameBuilder = new StringBuilder(); + if (ns != null) + { + nameBuilder.Append(ns); + nameBuilder.Append('.'); + } + AppendTypeName(nameBuilder, sourceType); + nameBuilder.Append('.'); + nameBuilder.Append(name); + this.name = nameBuilder.ToString(); + } + else if (ns != null) + { + this.name = string.Concat(ns, ".", sourceType.Name, ".", name); + } + else + { + this.name = string.Concat(sourceType.Name, ".", name); + } + } + + private static void AppendTypeName(StringBuilder nameBuilder, Type type) + { + nameBuilder.Append(type.Name); + if (type.IsGenericType) + { + nameBuilder.Append('['); + var genericTypeArguments = type.GetGenericArguments(); + for (int i = 0, n = genericTypeArguments.Length; i < n; ++i) + { + if (i > 0) + { + nameBuilder.Append(','); + } + AppendTypeName(nameBuilder, genericTypeArguments[i]); + } + nameBuilder.Append(']'); + } + } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/TypeElementCollection.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementCollection.cs similarity index 67% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/TypeElementCollection.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementCollection.cs index 79c4bff9..0351ba7a 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/TypeElementCollection.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementCollection.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -18,21 +18,11 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators using System.Collections; using System.Collections.Generic; - internal class TypeElementCollection : ICollection + internal class MetaTypeElementCollection : IEnumerable where TElement : MetaTypeElement, IEquatable { private readonly ICollection items = new List(); - public int Count - { - get { return items.Count; } - } - - bool ICollection.IsReadOnly - { - get { return false; } - } - public void Add(TElement item) { if (item.CanBeImplementedExplicitly == false) @@ -46,7 +36,7 @@ public void Add(TElement item) if (Contains(item)) { // there is something *really* wrong going on here - throw new ProxyGenerationException("Duplicate element: " + item); + throw new DynamicProxyException("Duplicate element: " + item); } } items.Add(item); @@ -70,21 +60,6 @@ public IEnumerator GetEnumerator() return items.GetEnumerator(); } - void ICollection.Clear() - { - throw new NotSupportedException(); - } - - void ICollection.CopyTo(TElement[] array, int arrayIndex) - { - throw new NotSupportedException(); - } - - bool ICollection.Remove(TElement item) - { - throw new NotSupportedException(); - } - IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementUtil.cs deleted file mode 100644 index 08f2d31a..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MetaTypeElementUtil.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators -{ - using System; - using System.Reflection; - using System.Text; - - internal static class MetaTypeElementUtil - { - public static string CreateNameForExplicitImplementation(Type sourceType, string name) - { - if (sourceType.GetTypeInfo().IsGenericType) - { - var nameBuilder = new StringBuilder(); - nameBuilder.AppendNameOf(sourceType); - nameBuilder.Append('.'); - nameBuilder.Append(name); - return nameBuilder.ToString(); - } - else - { - return string.Concat(sourceType.Name, ".", name); - } - } - - private static void AppendNameOf(this StringBuilder nameBuilder, Type type) - { - nameBuilder.Append(type.Name); - if (type.GetTypeInfo().IsGenericType) - { - nameBuilder.Append('['); - var genericTypeArguments = type.GetGenericArguments(); - for (int i = 0, n = genericTypeArguments.Length; i < n; ++i) - { - if (i > 0) - { - nameBuilder.Append(','); - } - nameBuilder.AppendNameOf(genericTypeArguments[i]); - } - nameBuilder.Append(']'); - } - } - } -} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs index a625f813..bb7057a4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -59,7 +59,7 @@ private static MethodInfo[] MakeFilteredCopy(MethodInfo[] methodsInCache, Bindin { if ((visibilityFlags & ~(BindingFlags.Public | BindingFlags.NonPublic)) != 0) { - throw new ArgumentException("Only supports BindingFlags.Public and NonPublic.", "visibilityFlags"); + throw new ArgumentException("Only supports BindingFlags.Public and NonPublic.", nameof(visibilityFlags)); } var includePublic = (visibilityFlags & BindingFlags.Public) == BindingFlags.Public; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodGenerator.cs index ebb4535d..511f47ac 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -41,14 +41,14 @@ protected MethodInfo MethodToOverride } protected abstract MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, - ProxyGenerationOptions options, INamingScope namingScope); + INamingScope namingScope); - public MethodEmitter Generate(ClassEmitter @class, ProxyGenerationOptions options, INamingScope namingScope) + public MethodEmitter Generate(ClassEmitter @class, INamingScope namingScope) { var methodEmitter = overrideMethod(method.Name, method.Attributes, MethodToOverride); - var proxiedMethod = BuildProxiedMethodBody(methodEmitter, @class, options, namingScope); + var proxiedMethod = BuildProxiedMethodBody(methodEmitter, @class, namingScope); - if (MethodToOverride.DeclaringType.GetTypeInfo().IsInterface) + if (MethodToOverride.DeclaringType.IsInterface) { @class.TypeBuilder.DefineMethodOverride(proxiedMethod.MethodBuilder, MethodToOverride); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodSignatureComparer.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodSignatureComparer.cs index e3194dd7..22c921f7 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodSignatureComparer.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodSignatureComparer.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -22,6 +22,8 @@ internal class MethodSignatureComparer : IEqualityComparer { public static readonly MethodSignatureComparer Instance = new MethodSignatureComparer(); + private static readonly Type preserveBaseOverridesAttribute = Type.GetType("System.Runtime.CompilerServices.PreserveBaseOverridesAttribute", throwOnError: false); + public bool EqualGenericParameters(MethodInfo x, MethodInfo y) { if (x.IsGenericMethod != y.IsGenericMethod) @@ -41,12 +43,12 @@ public bool EqualGenericParameters(MethodInfo x, MethodInfo y) for (var i = 0; i < xArgs.Length; ++i) { - if (xArgs[i].GetTypeInfo().IsGenericParameter != yArgs[i].GetTypeInfo().IsGenericParameter) + if (xArgs[i].IsGenericParameter != yArgs[i].IsGenericParameter) { return false; } - if (!xArgs[i].GetTypeInfo().IsGenericParameter && !xArgs[i].Equals(yArgs[i])) + if (!xArgs[i].IsGenericParameter && !xArgs[i].Equals(yArgs[i])) { return false; } @@ -77,31 +79,50 @@ public bool EqualParameters(MethodInfo x, MethodInfo y) return true; } - public bool EqualSignatureTypes(Type x, Type y) + public bool EqualReturnTypes(MethodInfo x, MethodInfo y) { - var xti = x.GetTypeInfo(); - var yti = y.GetTypeInfo(); + var xr = x.ReturnType; + var yr = y.ReturnType; + + if (EqualSignatureTypes(xr, yr)) + { + return true; + } - if (xti.IsGenericParameter != yti.IsGenericParameter) + // This enables covariant method returns for .NET 5 and newer. + // No need to check for runtime support, since such methods are marked with a custom attribute; + // see https://github.com/dotnet/runtime/blob/main/docs/design/features/covariant-return-methods.md. + if (preserveBaseOverridesAttribute != null) + { + return (x.IsDefined(preserveBaseOverridesAttribute, inherit: false) && yr.IsAssignableFrom(xr)) + || (y.IsDefined(preserveBaseOverridesAttribute, inherit: false) && xr.IsAssignableFrom(yr)); + } + + return false; + } + + private bool EqualSignatureTypes(Type x, Type y) + { + if (x.IsGenericParameter != y.IsGenericParameter) { return false; } - else if (xti.IsGenericType != yti.IsGenericType) + else if (x.IsGenericType != y.IsGenericType) { return false; } - if (xti.IsGenericParameter) + if (x.IsGenericParameter) { - if (xti.GenericParameterPosition != yti.GenericParameterPosition) + if (x.GenericParameterPosition != y.GenericParameterPosition) { return false; } } - else if (xti.IsGenericType) + else if (x.IsGenericType) { - var xGenericTypeDef = xti.GetGenericTypeDefinition(); - var yGenericTypeDef = yti.GetGenericTypeDefinition(); + var xGenericTypeDef = x.GetGenericTypeDefinition(); + var yGenericTypeDef = y.GetGenericTypeDefinition(); if (xGenericTypeDef != yGenericTypeDef) { @@ -118,7 +139,7 @@ public bool EqualSignatureTypes(Type x, Type y) for (var i = 0; i < xArgs.Length; ++i) { - if(!EqualSignatureTypes(xArgs[i], yArgs[i])) return false; + if(!EqualSignatureTypes(xArgs[i], yArgs[i])) return false; } } else @@ -145,7 +166,7 @@ public bool Equals(MethodInfo x, MethodInfo y) return EqualNames(x, y) && EqualGenericParameters(x, y) && - EqualSignatureTypes(x.ReturnType, y.ReturnType) && + EqualReturnTypes(x, y) && EqualParameters(x, y); } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodWithInvocationGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodWithInvocationGenerator.cs index bf720464..a5910bec 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodWithInvocationGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodWithInvocationGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -34,17 +34,17 @@ internal class MethodWithInvocationGenerator : MethodGenerator private readonly IInvocationCreationContributor contributor; private readonly GetTargetExpressionDelegate getTargetExpression; private readonly GetTargetExpressionDelegate getTargetTypeExpression; - private readonly Reference interceptors; + private readonly IExpression interceptors; private readonly Type invocation; - public MethodWithInvocationGenerator(MetaMethod method, Reference interceptors, Type invocation, + public MethodWithInvocationGenerator(MetaMethod method, IExpression interceptors, Type invocation, GetTargetExpressionDelegate getTargetExpression, OverrideMethodDelegate createMethod, IInvocationCreationContributor contributor) : this(method, interceptors, invocation, getTargetExpression, null, createMethod, contributor) { } - public MethodWithInvocationGenerator(MetaMethod method, Reference interceptors, Type invocation, + public MethodWithInvocationGenerator(MetaMethod method, IExpression interceptors, Type invocation, GetTargetExpressionDelegate getTargetExpression, GetTargetExpressionDelegate getTargetTypeExpression, OverrideMethodDelegate createMethod, IInvocationCreationContributor contributor) @@ -69,32 +69,34 @@ protected FieldReference BuildMethodInterceptorsField(ClassEmitter @class, Metho return methodInterceptors; } - protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, ProxyGenerationOptions options, INamingScope namingScope) + protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, INamingScope namingScope) { var invocationType = invocation; - Trace.Assert(MethodToOverride.IsGenericMethod == invocationType.GetTypeInfo().IsGenericTypeDefinition); var genericArguments = Type.EmptyTypes; var constructor = invocation.GetConstructors()[0]; - Expression proxiedMethodTokenExpression; + IExpression proxiedMethodTokenExpression; if (MethodToOverride.IsGenericMethod) { - // bind generic method arguments to invocation's type arguments - genericArguments = emitter.MethodBuilder.GetGenericArguments(); - invocationType = invocationType.MakeGenericType(genericArguments); - constructor = TypeBuilder.GetConstructor(invocationType, constructor); - // Not in the cache: generic method + genericArguments = emitter.MethodBuilder.GetGenericArguments(); proxiedMethodTokenExpression = new MethodTokenExpression(MethodToOverride.MakeGenericMethod(genericArguments)); + + if (invocationType.IsGenericTypeDefinition) + { + // bind generic method arguments to invocation's type arguments + invocationType = invocationType.MakeGenericType(genericArguments); + constructor = TypeBuilder.GetConstructor(invocationType, constructor); + } } else { var proxiedMethodToken = @class.CreateStaticField(namingScope.GetUniqueName("token_" + MethodToOverride.Name), typeof(MethodInfo)); @class.ClassConstructor.CodeBuilder.AddStatement(new AssignStatement(proxiedMethodToken, new MethodTokenExpression(MethodToOverride))); - proxiedMethodTokenExpression = proxiedMethodToken.ToExpression(); + proxiedMethodTokenExpression = proxiedMethodToken; } var methodInterceptors = SetMethodInterceptors(@class, namingScope, emitter, proxiedMethodTokenExpression); @@ -111,7 +113,7 @@ protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, C if (MethodToOverride.ContainsGenericParameters) { - EmitLoadGenricMethodArguments(emitter, MethodToOverride.MakeGenericMethod(genericArguments), invocationLocal); + EmitLoadGenericMethodArguments(emitter, MethodToOverride.MakeGenericMethod(genericArguments), invocationLocal); } if (hasByRefArguments) @@ -119,7 +121,7 @@ protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, C emitter.CodeBuilder.AddStatement(new TryStatement()); } - var proceed = new ExpressionStatement(new MethodInvocationExpression(invocationLocal, InvocationMethods.Proceed)); + var proceed = new MethodInvocationExpression(invocationLocal, InvocationMethods.Proceed); emitter.CodeBuilder.AddStatement(proceed); if (hasByRefArguments) @@ -144,7 +146,7 @@ protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, C LocalReference returnValue = emitter.CodeBuilder.DeclareLocal(typeof(object)); emitter.CodeBuilder.AddStatement(new AssignStatement(returnValue, getRetVal)); - emitter.CodeBuilder.AddExpression(new IfNullExpression(returnValue, new ThrowStatement(typeof(InvalidOperationException), + emitter.CodeBuilder.AddStatement(new IfNullExpression(returnValue, new ThrowStatement(typeof(InvalidOperationException), "Interceptors failed to set a return value, or swallowed the exception thrown by the target"))); } @@ -159,7 +161,7 @@ protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, C return emitter; } - private Expression SetMethodInterceptors(ClassEmitter @class, INamingScope namingScope, MethodEmitter emitter, Expression proxiedMethodTokenExpression) + private IExpression SetMethodInterceptors(ClassEmitter @class, INamingScope namingScope, MethodEmitter emitter, IExpression proxiedMethodTokenExpression) { var selector = @class.GetField("__selector"); if(selector == null) @@ -169,7 +171,7 @@ private Expression SetMethodInterceptors(ClassEmitter @class, INamingScope namin var methodInterceptorsField = BuildMethodInterceptorsField(@class, MethodToOverride, namingScope); - Expression targetTypeExpression; + IExpression targetTypeExpression; if (getTargetTypeExpression != null) { targetTypeExpression = getTargetTypeExpression(@class, MethodToOverride); @@ -182,20 +184,20 @@ private Expression SetMethodInterceptors(ClassEmitter @class, INamingScope namin var emptyInterceptors = new NewArrayExpression(0, typeof(IInterceptor)); var selectInterceptors = new MethodInvocationExpression(selector, InterceptorSelectorMethods.SelectInterceptors, targetTypeExpression, - proxiedMethodTokenExpression, interceptors.ToExpression()) + proxiedMethodTokenExpression, interceptors) { VirtualCall = true }; - emitter.CodeBuilder.AddExpression( + emitter.CodeBuilder.AddStatement( new IfNullExpression(methodInterceptorsField, new AssignStatement(methodInterceptorsField, new NullCoalescingOperatorExpression(selectInterceptors, emptyInterceptors)))); - return methodInterceptorsField.ToExpression(); + return methodInterceptorsField; } - private void EmitLoadGenricMethodArguments(MethodEmitter methodEmitter, MethodInfo method, Reference invocationLocal) + private void EmitLoadGenericMethodArguments(MethodEmitter methodEmitter, MethodInfo method, Reference invocationLocal) { - var genericParameters = method.GetGenericArguments().FindAll(t => t.GetTypeInfo().IsGenericParameter); + var genericParameters = Array.FindAll(method.GetGenericArguments(), t => t.IsGenericParameter); var genericParamsArrayLocal = methodEmitter.CodeBuilder.DeclareLocal(typeof(Type[])); methodEmitter.CodeBuilder.AddStatement( new AssignStatement(genericParamsArrayLocal, new NewArrayExpression(genericParameters.Length, typeof(Type)))); @@ -205,26 +207,25 @@ private void EmitLoadGenricMethodArguments(MethodEmitter methodEmitter, MethodIn methodEmitter.CodeBuilder.AddStatement( new AssignArrayStatement(genericParamsArrayLocal, i, new TypeTokenExpression(genericParameters[i]))); } - methodEmitter.CodeBuilder.AddExpression( + methodEmitter.CodeBuilder.AddStatement( new MethodInvocationExpression(invocationLocal, InvocationMethods.SetGenericMethodArguments, - new ReferenceExpression( - genericParamsArrayLocal))); + genericParamsArrayLocal)); } - private Expression[] GetCtorArguments(ClassEmitter @class, Expression proxiedMethodTokenExpression, TypeReference[] dereferencedArguments, Expression methodInterceptors) + private IExpression[] GetCtorArguments(ClassEmitter @class, IExpression proxiedMethodTokenExpression, TypeReference[] dereferencedArguments, IExpression methodInterceptors) { return new[] { getTargetExpression(@class, MethodToOverride), - SelfReference.Self.ToExpression(), - methodInterceptors ?? interceptors.ToExpression(), + SelfReference.Self, + methodInterceptors ?? interceptors, proxiedMethodTokenExpression, new ReferencesToObjectArrayExpression(dereferencedArguments) }; } - private Expression[] ModifyArguments(ClassEmitter @class, Expression[] arguments) + private IExpression[] ModifyArguments(ClassEmitter @class, IExpression[] arguments) { if (contributor == null) { @@ -238,7 +239,7 @@ private bool HasByRefArguments(ArgumentReference[] arguments) { for (int i = 0; i < arguments.Length; i++ ) { - if (arguments[i].Type.GetTypeInfo().IsByRef) + if (arguments[i].Type.IsByRef) { return true; } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MinimialisticMethodGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MinimalisticMethodGenerator.cs similarity index 76% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MinimialisticMethodGenerator.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MinimalisticMethodGenerator.cs index 77ef6944..0b234245 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/MinimialisticMethodGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MinimalisticMethodGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,23 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System.Reflection; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; - internal class MinimialisticMethodGenerator : MethodGenerator + internal class MinimalisticMethodGenerator : MethodGenerator { - public MinimialisticMethodGenerator(MetaMethod method, OverrideMethodDelegate overrideMethod) + public MinimalisticMethodGenerator(MetaMethod method, OverrideMethodDelegate overrideMethod) : base(method, overrideMethod) { } protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, - ProxyGenerationOptions options, INamingScope namingScope) + INamingScope namingScope) { InitOutParameters(emitter, MethodToOverride.GetParameters()); @@ -58,4 +58,4 @@ private void InitOutParameters(MethodEmitter emitter, ParameterInfo[] parameters } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/NamingScope.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/NamingScope.cs index ce464dd8..fc85f4c4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/NamingScope.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/NamingScope.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/OptionallyForwardingMethodGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/OptionallyForwardingMethodGenerator.cs similarity index 67% rename from Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/OptionallyForwardingMethodGenerator.cs rename to Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/OptionallyForwardingMethodGenerator.cs index c1ad7286..c8d7bdbb 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Contributors/OptionallyForwardingMethodGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/OptionallyForwardingMethodGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -12,12 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators { using System; using System.Reflection; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST; @@ -34,57 +34,60 @@ public OptionallyForwardingMethodGenerator(MetaMethod method, OverrideMethodDele } protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, - ProxyGenerationOptions options, INamingScope namingScope) + INamingScope namingScope) { var targetReference = getTargetReference(@class, MethodToOverride); emitter.CodeBuilder.AddStatement( - new ExpressionStatement( - new IfNullExpression(targetReference, IfNull(emitter.ReturnType), IfNotNull(targetReference)))); + new IfNullExpression( + targetReference, + IfNull(emitter.ReturnType), + IfNotNull(targetReference))); + return emitter; } - private Expression IfNotNull(Reference targetReference) + private IStatement IfNotNull(Reference targetReference) { - var expression = new MultiStatementExpression(); + var statements = new BlockStatement(); var arguments = ArgumentsUtil.ConvertToArgumentReferenceExpression(MethodToOverride.GetParameters()); - expression.AddStatement(new ReturnStatement( + statements.AddStatement(new ReturnStatement( new MethodInvocationExpression( targetReference, MethodToOverride, arguments) { VirtualCall = true })); - return expression; + return statements; } - private Expression IfNull(Type returnType) + private IStatement IfNull(Type returnType) { - var expression = new MultiStatementExpression(); - InitOutParameters(expression, MethodToOverride.GetParameters()); + var statements = new BlockStatement(); + InitOutParameters(statements, MethodToOverride.GetParameters()); if (returnType == typeof(void)) { - expression.AddStatement(new ReturnStatement()); + statements.AddStatement(new ReturnStatement()); } else { - expression.AddStatement(new ReturnStatement(new DefaultValueExpression(returnType))); + statements.AddStatement(new ReturnStatement(new DefaultValueExpression(returnType))); } - return expression; + return statements; } - private void InitOutParameters(MultiStatementExpression expression, ParameterInfo[] parameters) + private void InitOutParameters(BlockStatement statements, ParameterInfo[] parameters) { for (var index = 0; index < parameters.Length; index++) { var parameter = parameters[index]; if (parameter.IsOut) { - expression.AddStatement( + statements.AddStatement( new AssignArgumentStatement(new ArgumentReference(parameter.ParameterType, index + 1, parameter.Attributes), new DefaultValueExpression(parameter.ParameterType))); } } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IAttributeDisassembler.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IAttributeDisassembler.cs deleted file mode 100644 index ff7fd174..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IAttributeDisassembler.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy -{ - using System; - using System.Reflection.Emit; - - /// - /// Provides functionality for disassembling instances of attributes to CustomAttributeBuilder form, during the process of emiting new types by Dynamic Proxy. - /// - internal interface IAttributeDisassembler - { - /// - /// Disassembles given attribute instance back to corresponding CustomAttributeBuilder. - /// - /// An instance of attribute to disassemble - /// corresponding 1 to 1 to given attribute instance, or null reference. - /// - /// Implementers should return that corresponds to given attribute instance 1 to 1, - /// that is after calling specified constructor with specified arguments, and setting specified properties and fields with values specified - /// we should be able to get an attribute instance identical to the one passed in . Implementer can return null - /// if it wishes to opt out of replicating the attribute. Notice however, that for some cases, like attributes passed explicitly by the user - /// it is illegal to return null, and doing so will result in exception. - /// - CustomAttributeBuilder Disassemble(Attribute attribute); - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IChangeProxyTarget.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IChangeProxyTarget.cs index 330faaf1..6a945703 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IChangeProxyTarget.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IChangeProxyTarget.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptor.cs index 35bc0ae8..2784a407 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,14 +14,11 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy { - /// - /// An implementation detail interface. Not intended for external usage. Provides the main DynamicProxy extension point that allows member interception. - /// - public interface IInterceptor + /// + /// Provides the main DynamicProxy extension point that allows member interception. + /// + public interface IInterceptor { - /// - /// An implementation detail. Not intended for external usage. - /// - void Intercept(IInvocation invocation); + void Intercept(IInvocation invocation); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptorSelector.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptorSelector.cs index 8e37c60f..6b153284 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptorSelector.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInterceptorSelector.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -39,4 +39,4 @@ public interface IInterceptorSelector /// IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocation.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocation.cs index fc735e40..b12ebbf8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocation.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocation.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -114,6 +114,12 @@ public interface IInvocation /// void Proceed(); + /// + /// Returns an object describing the operation for this + /// at this specific point during interception. + /// + IInvocationProceedInfo CaptureProceedInfo(); + /// /// Overrides the value of an argument at the given with the /// new provided. @@ -126,4 +132,4 @@ public interface IInvocation /// The new value for the argument. void SetArgumentValue(int index, object value); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocationProceedInfo.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocationProceedInfo.cs new file mode 100644 index 00000000..236bbc97 --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IInvocationProceedInfo.cs @@ -0,0 +1,31 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy +{ + using System; + + /// + /// Describes the operation for an + /// at a specific point during interception. + /// + public interface IInvocationProceedInfo + { + /// + /// Executes the operation described by this instance. + /// + /// There is no interceptor, nor a proxy target object, to proceed to. + void Invoke(); + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyBuilder.cs index 63db3a6c..db1c3691 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyBuilder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyBuilder.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -49,9 +49,9 @@ internal interface IProxyBuilder /// Additional interfaces should be only 'mark' interfaces, that is, they should work like interface proxy without target. (See method.) /// - /// Thrown when or any of Thrown when or any of is a generic type definition. - /// Thrown when or any of Thrown when or any of is not public. /// Note that to avoid this exception, you can mark offending type internal, and define @@ -77,9 +77,9 @@ Type CreateClassProxyTypeWithTarget(Type classToProxy, Type[] additionalInterfac /// Additional interfaces should be only 'mark' interfaces, that is, they should work like interface proxy without target. (See method.) /// - /// Thrown when or any of Thrown when or any of is a generic type definition. - /// Thrown when or any of Thrown when or any of is not public. /// Note that to avoid this exception, you can mark offending type internal, and define @@ -102,9 +102,9 @@ Type CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy, Type[] additional /// cref = "IInvocation" /> classes should then implement interface, /// to allow interceptors to switch invocation target with instance of another type implementing called interface. /// - /// Thrown when or any of Thrown when or any of is a generic type definition. - /// Thrown when or any of Thrown when or any of is not public. /// Note that to avoid this exception, you can mark offending type internal, and define @@ -123,9 +123,9 @@ Type CreateInterfaceProxyTypeWithTargetInterface(Type interfaceToProxy, Type[] a /// /// Implementers should return a proxy type for the specified interface and additional interfaces that delegate all executions to the specified interceptors. /// - /// Thrown when or any of Thrown when or any of is a generic type definition. - /// Thrown when or any of Thrown when or any of is not public. /// Note that to avoid this exception, you can mark offending type internal, and define diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerationHook.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerationHook.cs index d1dae311..469193f1 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerationHook.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerationHook.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs index 04a6dc6e..3e483a05 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyTargetAccessor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyTargetAccessor.cs index 3b31b033..2fc819d3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyTargetAccessor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyTargetAccessor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -23,7 +23,6 @@ public interface IProxyTargetAccessor /// /// Get the proxy target (note that null is a valid target!) /// - /// object DynProxyGetTarget(); /// @@ -35,7 +34,6 @@ public interface IProxyTargetAccessor /// /// Gets the interceptors for the proxy /// - /// IInterceptor[] GetInterceptors(); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/AttributeUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/AttributeUtil.cs index 0d22f2c1..811bf02f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/AttributeUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/AttributeUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -19,8 +19,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal using System.Diagnostics; using System.Linq; using System.Reflection; - using System.Reflection.Emit; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using System.Reflection.Emit; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; internal static class AttributeUtil { @@ -28,30 +28,17 @@ public static CustomAttributeInfo CreateInfo(CustomAttributeData attribute) { Debug.Assert(attribute != null, "attribute != null"); - // .NET Core does not provide CustomAttributeData.Constructor, so we'll implement it - // by finding a constructor ourselves - Type[] constructorArgTypes; - object[] constructorArgs; - GetArguments(attribute.ConstructorArguments, out constructorArgTypes, out constructorArgs); -#if FEATURE_LEGACY_REFLECTION_API - var constructor = attribute.Constructor; -#else - var constructor = attribute.AttributeType.GetConstructor(constructorArgTypes); -#endif + object[] constructorArgs = GetArguments(attribute.ConstructorArguments); PropertyInfo[] properties; object[] propertyValues; FieldInfo[] fields; object[] fieldValues; GetSettersAndFields( -#if FEATURE_LEGACY_REFLECTION_API - null, -#else attribute.AttributeType, -#endif attribute.NamedArguments, out properties, out propertyValues, out fields, out fieldValues); - return new CustomAttributeInfo(constructor, + return new CustomAttributeInfo(attribute.Constructor, constructorArgs, properties, propertyValues, @@ -59,18 +46,6 @@ public static CustomAttributeInfo CreateInfo(CustomAttributeData attribute) fieldValues); } - private static void GetArguments(IList constructorArguments, - out Type[] constructorArgTypes, out object[] constructorArgs) - { - constructorArgTypes = new Type[constructorArguments.Count]; - constructorArgs = new object[constructorArguments.Count]; - for (var i = 0; i < constructorArguments.Count; i++) - { - constructorArgTypes[i] = constructorArguments[i].ArgumentType; - constructorArgs[i] = ReadAttributeValue(constructorArguments[i]); - } - } - private static object[] GetArguments(IList constructorArguments) { var arguments = new object[constructorArguments.Count]; @@ -85,15 +60,18 @@ private static object[] GetArguments(IList constru private static object ReadAttributeValue(CustomAttributeTypedArgument argument) { var value = argument.Value; - if (argument.ArgumentType.GetTypeInfo().IsArray == false) + + if (argument.ArgumentType.IsArray && value is IList values) { - return value; + // `CustomAttributeInfo` represents array values as `ReadOnlyCollection`, + // but `CustomAttributeBuilder` will require plain arrays, so we need a (recursive) conversion: + var arguments = GetArguments(values); + var array = new object[arguments.Length]; + arguments.CopyTo(array, 0); + return array; } - //special case for handling arrays in attributes - var arguments = GetArguments((IList)value); - var array = new object[arguments.Length]; - arguments.CopyTo(array, 0); - return array; + + return value; } private static void GetSettersAndFields(Type attributeType, IEnumerable namedArguments, @@ -106,18 +84,6 @@ private static void GetSettersAndFields(Type attributeType, IEnumerable(); foreach (var argument in namedArguments) { -#if FEATURE_LEGACY_REFLECTION_API - if (argument.MemberInfo.MemberType == MemberTypes.Field) - { - fieldList.Add(argument.MemberInfo as FieldInfo); - fieldValuesList.Add(ReadAttributeValue(argument.TypedValue)); - } - else - { - propertyList.Add(argument.MemberInfo as PropertyInfo); - propertyValuesList.Add(ReadAttributeValue(argument.TypedValue)); - } -#else if (argument.IsField) { fieldList.Add(attributeType.GetField(argument.MemberName)); @@ -128,7 +94,6 @@ private static void GetSettersAndFields(Type attributeType, IEnumerable GetNonInheritableAttributes(this MemberInfo member) { Debug.Assert(member != null, "member != null"); -#if FEATURE_LEGACY_REFLECTION_API - var attributes = CustomAttributeData.GetCustomAttributes(member); -#else var attributes = member.CustomAttributes; -#endif foreach (var attribute in attributes) { -#if FEATURE_LEGACY_REFLECTION_API - var attributeType = attribute.Constructor.DeclaringType; -#else var attributeType = attribute.AttributeType; -#endif if (ShouldSkipAttributeReplication(attributeType, ignoreInheritance: false)) { continue; @@ -171,13 +128,9 @@ public static IEnumerable GetNonInheritableAttributes(this "To avoid this error you can chose not to replicate this attribute type by calling '{3}.Add(typeof({0}))'.", attributeType.FullName, member.DeclaringType.FullName, -#if FEATURE_LEGACY_REFLECTION_API - (member is Type) ? "" : ("." + member.Name), -#else (member is TypeInfo) ? "" : ("." + member.Name), -#endif typeof(AttributesToAvoidReplicating).FullName); - throw new ProxyGenerationException(message, e); + throw new NotSupportedException(message, e); } if (info != null) { @@ -190,21 +143,13 @@ public static IEnumerable GetNonInheritableAttributes(this { Debug.Assert(parameter != null, "parameter != null"); -#if FEATURE_LEGACY_REFLECTION_API - var attributes = CustomAttributeData.GetCustomAttributes(parameter); -#else var attributes = parameter.CustomAttributes; -#endif var ignoreInheritance = parameter.Member is ConstructorInfo; foreach (var attribute in attributes) { -#if FEATURE_LEGACY_REFLECTION_API - var attributeType = attribute.Constructor.DeclaringType; -#else var attributeType = attribute.AttributeType; -#endif if (ShouldSkipAttributeReplication(attributeType, ignoreInheritance)) { @@ -226,7 +171,7 @@ public static IEnumerable GetNonInheritableAttributes(this /// private static bool ShouldSkipAttributeReplication(Type attribute, bool ignoreInheritance) { - if (attribute.GetTypeInfo().IsPublic == false) + if (attribute.IsPublic == false && attribute.IsNestedPublic == false) { return true; } @@ -247,7 +192,7 @@ private static bool ShouldSkipAttributeReplication(Type attribute, bool ignoreIn if (!ignoreInheritance) { - var attrs = attribute.GetTypeInfo().GetCustomAttributes(true).ToArray(); + var attrs = attribute.GetCustomAttributes(true).ToArray(); if (attrs.Length != 0) { return attrs[0].Inherited; @@ -289,12 +234,12 @@ private static Type[] GetTypes(object[] objects) return types; } - public static CustomAttributeBuilder CreateBuilder() where TAttribute : Attribute, new() - { - var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes); - Debug.Assert(constructor != null, "constructor != null"); + public static CustomAttributeBuilder CreateBuilder() where TAttribute : Attribute, new() + { + var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes); + Debug.Assert(constructor != null, "constructor != null"); - return new CustomAttributeBuilder(constructor, new object[0]); - } - } -} \ No newline at end of file + return new CustomAttributeBuilder(constructor, new object[0]); + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/CompositionInvocation.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/CompositionInvocation.cs index 7621f1ba..0b11fb9b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/CompositionInvocation.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/CompositionInvocation.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,9 +17,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal using System; using System.Reflection; -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public abstract class CompositionInvocation : AbstractInvocation - { + public abstract class CompositionInvocation : AbstractInvocation + { protected object target; protected CompositionInvocation( @@ -52,7 +51,7 @@ protected void EnsureValidProxyTarget(object newTarget) { if (newTarget == null) { - throw new ArgumentNullException("newTarget"); + throw new ArgumentNullException(nameof(newTarget)); } if (!ReferenceEquals(newTarget, proxyObject)) @@ -84,5 +83,4 @@ protected void EnsureValidTarget() throw new InvalidOperationException(message); } } -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocation.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocation.cs index 97030bed..e2e5ab16 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocation.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocation.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -17,9 +17,8 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal using System; using System.Reflection; -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public abstract class InheritanceInvocation : AbstractInvocation - { + public abstract class InheritanceInvocation : AbstractInvocation + { private readonly Type targetType; protected InheritanceInvocation( @@ -50,5 +49,4 @@ public override Type TargetType protected abstract override void InvokeMethodOnTarget(); } -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} +} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocationWithoutTarget.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocationWithoutTarget.cs new file mode 100644 index 00000000..75408a0c --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InheritanceInvocationWithoutTarget.cs @@ -0,0 +1,36 @@ +// Copyright 2004-2022 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal +{ + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.Reflection; + +#if FEATURE_SERIALIZATION + [Serializable] +#endif + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class InheritanceInvocationWithoutTarget : InheritanceInvocation + { + public InheritanceInvocationWithoutTarget(Type targetType, object proxy, IInterceptor[] interceptors, MethodInfo proxiedMethod, object[] arguments) + : base(targetType, proxy, interceptors, proxiedMethod, arguments) + { + Debug.Assert(proxiedMethod.IsAbstract, $"{nameof(InheritanceInvocationWithoutTarget)} does not support non-abstract methods."); + } + + protected override void InvokeMethodOnTarget() => ThrowOnNoTarget(); + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InterfaceMethodWithoutTargetInvocation.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InterfaceMethodWithoutTargetInvocation.cs new file mode 100644 index 00000000..709d3738 --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InterfaceMethodWithoutTargetInvocation.cs @@ -0,0 +1,61 @@ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal +{ + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.Reflection; + +#if FEATURE_SERIALIZATION + [Serializable] +#endif + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class InterfaceMethodWithoutTargetInvocation : AbstractInvocation + { + public InterfaceMethodWithoutTargetInvocation(object target, object proxy, IInterceptor[] interceptors, MethodInfo proxiedMethod, object[] arguments) + : base(proxy, interceptors, proxiedMethod, arguments) + { + // This invocation type is suitable for interface method invocations that cannot proceed + // to a target, i.e. where `InvokeMethodOnTarget` will always throw: + + Debug.Assert(target == null, $"{nameof(InterfaceMethodWithoutTargetInvocation)} does not support targets."); + Debug.Assert(proxiedMethod.IsAbstract, $"{nameof(InterfaceMethodWithoutTargetInvocation)} does not support non-abstract methods."); + + // Why this restriction? Because it greatly benefits proxy type generation performance. + // + // For invocations that can proceed to a target, `InvokeMethodOnTarget`'s implementation + // depends on the target method's signature. Because of this, DynamicProxy needs to + // dynamically generate a separate invocation type per such method. Type generation is + // always expensive... that is, slow. + // + // However, if it is known that `InvokeMethodOnTarget` won't forward, but throw, + // no custom (dynamically generated) invocation type is needed at all, and we can use + // this unspecific invocation type instead. + } + + // The next three properties mimick the behavior seen with an interface proxy without target. + // (This is why this type's name starts with `Interface`.) A similar type could be written + // for class proxies without target, but the values returned here would be different. + + public override object InvocationTarget => null; + + public override MethodInfo MethodInvocationTarget => null; + + public override Type TargetType => null; + + protected override void InvokeMethodOnTarget() => ThrowOnNoTarget(); + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InternalsUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InternalsUtil.cs deleted file mode 100644 index b7c433b7..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InternalsUtil.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal -{ - using System; - using System.ComponentModel; - using System.Reflection; - - internal static class InternalsUtil - { - /// - /// Determines whether the specified method is internal. - /// - /// The method. - /// - /// true if the specified method is internal; otherwise, false. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete] - public static bool IsInternal(this MethodBase method) - { - return ProxyUtil.IsInternal(method); - } - - /// - /// Determines whether this assembly has internals visible to dynamic proxy. - /// - /// The assembly to inspect. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete] - public static bool IsInternalToDynamicProxy(this Assembly asm) - { - return ProxyUtil.AreInternalsVisibleToDynamicProxy(asm); - } - - /// - /// Checks if the method is public or protected. - /// - /// - /// - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Use " + nameof(ProxyUtil) + "." + nameof(ProxyUtil.IsAccessible) + " instead, " + - "which performs a more accurate accessibility check.")] - public static bool IsAccessible(this MethodBase method) - { - return ProxyUtil.IsAccessibleMethod(method); - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InvocationHelper.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InvocationHelper.cs index 5046c1d6..17881835 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InvocationHelper.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/InvocationHelper.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,22 +16,17 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Reflection; -#if NETCORE - using Debug = Telerik.JustMock.Diagnostics.JMDebug; -#else -using Debug = System.Diagnostics.Debug; -#endif + using System.Threading; - using Telerik.JustMock.Core.Castle.Core.Internal; + using Telerik.JustMock.Core.Castle.Core.Internal; using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; internal static class InvocationHelper { - private static readonly Dictionary cache = - new Dictionary(); - - private static readonly Lock @lock = Lock.Create(); + private static readonly SynchronizedDictionary cache = + new SynchronizedDictionary(); public static MethodInfo GetMethodOnObject(object target, MethodInfo proxiedMethod) { @@ -47,44 +42,15 @@ public static MethodInfo GetMethodOnType(Type type, MethodInfo proxiedMethod) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } Debug.Assert(proxiedMethod.DeclaringType.IsAssignableFrom(type), "proxiedMethod.DeclaringType.IsAssignableFrom(type)"); - using (var locker = @lock.ForReading()) - { - var methodOnTarget = GetFromCache(proxiedMethod, type); - if (methodOnTarget != null) - { - return methodOnTarget; - } - } - - using (var locker = @lock.ForReadingUpgradeable()) - { - var methodOnTarget = GetFromCache(proxiedMethod, type); - if (methodOnTarget != null) - { - return methodOnTarget; - } - // Upgrade the lock to a write lock. - using (locker.Upgrade()) - { - methodOnTarget = ObtainMethod(proxiedMethod, type); - PutToCache(proxiedMethod, type, methodOnTarget); - } - return methodOnTarget; - } - } + var cacheKey = new CacheKey(proxiedMethod, type); - private static MethodInfo GetFromCache(MethodInfo methodInfo, Type type) - { - var key = new CacheKey(methodInfo, type); - MethodInfo method; - cache.TryGetValue(key, out method); - return method; + return cache.GetOrAdd(cacheKey, ck => ObtainMethod(proxiedMethod, type)); } private static MethodInfo ObtainMethod(MethodInfo proxiedMethod, Type type) @@ -97,11 +63,11 @@ private static MethodInfo ObtainMethod(MethodInfo proxiedMethod, Type type) } var declaringType = proxiedMethod.DeclaringType; MethodInfo methodOnTarget = null; - if (declaringType.GetTypeInfo().IsInterface) + if (declaringType.IsInterface) { - var mapping = type.GetTypeInfo().GetRuntimeInterfaceMap(declaringType); + var mapping = type.GetInterfaceMap(declaringType); var index = Array.IndexOf(mapping.InterfaceMethods, proxiedMethod); - Debug.Assert(index != -1); + Debug.Assert(index != -1); methodOnTarget = mapping.TargetMethods[index]; } else @@ -131,12 +97,6 @@ private static MethodInfo ObtainMethod(MethodInfo proxiedMethod, Type type) return methodOnTarget.MakeGenericMethod(genericArguments); } - private static void PutToCache(MethodInfo methodInfo, Type type, MethodInfo value) - { - var key = new CacheKey(methodInfo, type); - cache.Add(key, value); - } - private struct CacheKey : IEquatable { public CacheKey(MethodInfo method, Type type) diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/TypeUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/TypeUtil.cs index a4c86e37..d506e83a 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/TypeUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Internal/TypeUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,33 +16,28 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Internal { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; -#if NETCORE - using Debug = Telerik.JustMock.Diagnostics.JMDebug; -#else -using Debug = System.Diagnostics.Debug; -#endif - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters; internal static class TypeUtil { - public static bool IsNullableType(this Type type) + internal static bool IsNullableType(this Type type) { - return type.GetTypeInfo().IsGenericType && + return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } - public static FieldInfo[] GetAllFields(this Type type) + internal static FieldInfo[] GetAllFields(this Type type) { if (type == null) { - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); } - if (type.GetTypeInfo().IsClass == false) + if (type.IsClass == false) { throw new ArgumentException(string.Format("Type {0} is not a class type. This method supports only classes", type)); } @@ -51,10 +46,10 @@ public static FieldInfo[] GetAllFields(this Type type) var currentType = type; while (currentType != typeof(object)) { - Debug.Assert(currentType != null); + Debug.Assert(currentType != null); var currentFields = currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); fields.AddRange(currentFields); - currentType = currentType.GetTypeInfo().BaseType; + currentType = currentType.BaseType; } return fields.ToArray(); @@ -63,9 +58,7 @@ public static FieldInfo[] GetAllFields(this Type type) /// /// Returns list of all unique interfaces implemented given types, including their base interfaces. /// - /// - /// - public static Type[] GetAllInterfaces(params Type[] types) + internal static Type[] GetAllInterfaces(params Type[] types) { if (types == null) { @@ -81,7 +74,7 @@ public static Type[] GetAllInterfaces(params Type[] types) continue; } - if (type.GetTypeInfo().IsInterface) + if (type.IsInterface) { if (interfaces.Add(type) == false) { @@ -100,49 +93,11 @@ public static Type[] GetAllInterfaces(params Type[] types) return Sort(interfaces); } - public static Type[] GetAllInterfaces(this Type type) + public static Type[] GetAllInterfaces(this Type type) // NOTE: also used by Windsor { return GetAllInterfaces(new[] { type }); } - public static Type GetClosedParameterType(this AbstractTypeEmitter type, Type parameter) - { - if (parameter.GetTypeInfo().IsGenericTypeDefinition) - { - return parameter.GetGenericTypeDefinition().MakeGenericType(type.GetGenericArgumentsFor(parameter)); - } - - if (parameter.GetTypeInfo().IsGenericType) - { - var arguments = parameter.GetGenericArguments(); - if (CloseGenericParametersIfAny(type, arguments)) - { - return parameter.GetGenericTypeDefinition().MakeGenericType(arguments); - } - } - - if (parameter.GetTypeInfo().IsGenericParameter) - { - return type.GetGenericArgument(parameter.Name); - } - - if (parameter.GetTypeInfo().IsArray) - { - var elementType = GetClosedParameterType(type, parameter.GetElementType()); - int rank = parameter.GetArrayRank(); - return rank == 1 - ? elementType.MakeArrayType() - : elementType.MakeArrayType(rank); - } - - if (parameter.GetTypeInfo().IsByRef) - { - var elementType = GetClosedParameterType(type, parameter.GetElementType()); - return elementType.MakeByRefType(); - } - - return parameter; - } public static Type GetTypeOrNull(object target) { @@ -153,39 +108,39 @@ public static Type GetTypeOrNull(object target) return target.GetType(); } - public static Type[] AsTypeArray(this GenericTypeParameterBuilder[] typeInfos) + internal static Type[] AsTypeArray(this GenericTypeParameterBuilder[] typeInfos) { Type[] types = new Type[typeInfos.Length]; for (int i = 0; i < types.Length; i++) { - types[i] = typeInfos[i].AsType(); + types[i] = typeInfos[i]; } return types; } - public static bool IsFinalizer(this MethodInfo methodInfo) + internal static bool IsFinalizer(this MethodInfo methodInfo) { return string.Equals("Finalize", methodInfo.Name) && methodInfo.GetBaseDefinition().DeclaringType == typeof(object); } - public static bool IsGetType(this MethodInfo methodInfo) + internal static bool IsGetType(this MethodInfo methodInfo) { return methodInfo.DeclaringType == typeof(object) && string.Equals("GetType", methodInfo.Name, StringComparison.OrdinalIgnoreCase); } - public static bool IsMemberwiseClone(this MethodInfo methodInfo) + internal static bool IsMemberwiseClone(this MethodInfo methodInfo) { return methodInfo.DeclaringType == typeof(object) && string.Equals("MemberwiseClone", methodInfo.Name, StringComparison.OrdinalIgnoreCase); } - public static void SetStaticField(this Type type, string fieldName, BindingFlags additionalFlags, object value) + internal static void SetStaticField(this Type type, string fieldName, BindingFlags additionalFlags, object value) { var flags = additionalFlags | BindingFlags.Static; FieldInfo field = type.GetField(fieldName, flags); if (field == null) { - throw new ProxyGenerationException(string.Format( + throw new DynamicProxyException(string.Format( "Could not find field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.", fieldName, type)); } @@ -196,29 +151,27 @@ public static void SetStaticField(this Type type, string fieldName, BindingFlags } catch (MissingFieldException e) { - throw new ProxyGenerationException( + throw new DynamicProxyException( string.Format( "Could not find field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.", fieldName, type), e); } -#if FEATURE_TARGETEXCEPTION catch (TargetException e) { - throw new ProxyGenerationException( + throw new DynamicProxyException( string.Format( "There was an error trying to set field named '{0}' on type {1}. This is likely a bug in DynamicProxy. Please report it.", fieldName, type), e); } -#endif catch (TargetInvocationException e) // yes, this is not documented in MSDN. Yay for documentation { if ((e.InnerException is TypeInitializationException) == false) { throw; } - throw new ProxyGenerationException( + throw new DynamicProxyException( string.Format( "There was an error in static constructor on type {0}. This is likely a bug in DynamicProxy. Please report it.", type), e); @@ -233,19 +186,12 @@ public static MemberInfo[] Sort(MemberInfo[] members) return sortedMembers; } - private static bool CloseGenericParametersIfAny(AbstractTypeEmitter emitter, Type[] arguments) + /// + /// Checks whether the specified is a delegate type (i.e. a direct subclass of ). + /// + internal static bool IsDelegateType(this Type type) { - var hasAnyGenericParameters = false; - for (var i = 0; i < arguments.Length; i++) - { - var newType = GetClosedParameterType(emitter, arguments[i]); - if (newType != null && !ReferenceEquals(newType, arguments[i])) - { - arguments[i] = newType; - hasAnyGenericParameters = true; - } - } - return hasAnyGenericParameters; + return type.BaseType == typeof(MulticastDelegate); } private static Type[] Sort(ICollection types) @@ -253,8 +199,27 @@ private static Type[] Sort(ICollection types) var array = new Type[types.Count]; types.CopyTo(array, 0); //NOTE: is there a better, stable way to sort Types. We will need to revise this once we allow open generics - Array.Sort(array, (l, r) => string.Compare(l.AssemblyQualifiedName, r.AssemblyQualifiedName, StringComparison.OrdinalIgnoreCase)); + Array.Sort(array, TypeNameComparer.Instance); + // ^^^^^^^^^^^^^^^^^^^^^^^^^ + // Using a `IComparer` object instead of a `Comparison` delegate prevents + // an unnecessary level of indirection inside the framework (as the latter get + // wrapped as `IComparer` objects). return array; } + + private sealed class TypeNameComparer : IComparer + { + public static readonly TypeNameComparer Instance = new TypeNameComparer(); + + public int Compare(Type x, Type y) + { + // Comparing by `type.AssemblyQualifiedName` would give the same result, + // but it performs a hidden concatenation (and therefore string allocation) + // of `type.FullName` and `type.Assembly.FullName`. We can avoid this + // overhead by comparing the two properties separately. + int result = string.CompareOrdinal(x.FullName, y.FullName); + return result != 0 ? result : string.CompareOrdinal(x.Assembly.FullName, y.Assembly.FullName); + } + } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidMixinConfigurationException.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidMixinConfigurationException.cs deleted file mode 100644 index 5d147244..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidMixinConfigurationException.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy -{ - using System; -#if FEATURE_SERIALIZATION - using System.Runtime.Serialization; -#endif - -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal class InvalidMixinConfigurationException : Exception - { - public InvalidMixinConfigurationException(string message) - : base(message) - { - } - - public InvalidMixinConfigurationException(string message, Exception innerException) : base(message, innerException) - { - } - -#if FEATURE_SERIALIZATION - protected InvalidMixinConfigurationException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } -#endif - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidProxyConstructorArgumentsException.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidProxyConstructorArgumentsException.cs deleted file mode 100644 index 41d03de9..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/InvalidProxyConstructorArgumentsException.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy -{ - using System; - -#if FEATURE_SERIALIZATION - [Serializable] -#endif - internal class InvalidProxyConstructorArgumentsException : ArgumentException - { - public InvalidProxyConstructorArgumentsException(string message, Type proxyType, Type classToProxy) : base(message) - { - ProxyType = proxyType; - ClassToProxy = classToProxy; - } - - public Type ClassToProxy { get; private set; } - public Type ProxyType { get; private set; } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs index ae788006..d52a5410 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,11 +16,18 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy { using System; using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; internal class MixinData { private readonly Dictionary mixinPositions = new Dictionary(); private readonly List mixinsImpl = new List(); + private int delegateMixinCount = 0; /// /// Because we need to cache the types based on the mixed in mixins, we do the following here: @@ -37,29 +44,78 @@ public MixinData(IEnumerable mixinInstances) { var sortedMixedInterfaceTypes = new List(); var interface2Mixin = new Dictionary(); + delegateMixinCount = 0; foreach (var mixin in mixinInstances) { - var mixinInterfaces = mixin.GetType().GetInterfaces(); + Type[] mixinInterfaces; + object target; + if (mixin is Delegate) + { + ++delegateMixinCount; + mixinInterfaces = new[] { mixin.GetType() }; + target = mixin; + } + else if (mixin is Type delegateType && delegateType.IsDelegateType()) + { + ++delegateMixinCount; + mixinInterfaces = new[] { delegateType }; + target = null; + } + else + { + mixinInterfaces = mixin.GetType().GetInterfaces(); + target = mixin; + } foreach (var inter in mixinInterfaces) { sortedMixedInterfaceTypes.Add(inter); - if (interface2Mixin.ContainsKey(inter)) + if (interface2Mixin.TryGetValue(inter, out var interMixin)) { - var message = string.Format( - "The list of mixins contains two mixins implementing the same interface '{0}': {1} and {2}. An interface cannot be added by more than one mixin.", - inter.FullName, - interface2Mixin[inter].GetType().Name, - mixin.GetType().Name); - throw new ArgumentException(message, "mixinInstances"); + string message; + if (interMixin != null) + { + message = string.Format( + "The list of mixins contains two mixins implementing the same interface '{0}': {1} and {2}. An interface cannot be added by more than one mixin.", + inter.FullName, + interMixin.GetType().Name, + mixin.GetType().Name); + } + else + { + Debug.Assert(inter.IsDelegateType()); + message = string.Format( + "The list of mixins already contains a mixin for delegate type '{0}'.", + inter.FullName); + } + throw new ArgumentException(message, nameof(mixinInstances)); } + interface2Mixin[inter] = target; + } + } - interface2Mixin[inter] = mixin; + if (delegateMixinCount > 1) + { + // If at least two delegate mixins have been added, we need to ensure that + // the `Invoke` methods contributed by them don't have identical signatures: + var invokeMethods = new HashSet(); + foreach (var mixedInType in interface2Mixin.Keys) + { + if (mixedInType.IsDelegateType()) + { + var invokeMethod = mixedInType.GetMethod("Invoke"); + if (invokeMethods.Contains(invokeMethod, MethodSignatureComparer.Instance)) + { + throw new ArgumentException("The list of mixins contains at least two delegate mixins for the same delegate signature.", nameof(mixinInstances)); + } + invokeMethods.Add(invokeMethod); + } } } - sortedMixedInterfaceTypes.Sort((x, y) => x.FullName.CompareTo(y.FullName)); + + sortedMixedInterfaceTypes.Sort((x, y) => string.CompareOrdinal(x.FullName, y.FullName)); for (var i = 0; i < sortedMixedInterfaceTypes.Count; i++) { @@ -106,14 +162,26 @@ public override bool Equals(object obj) return false; } + if (delegateMixinCount != other.delegateMixinCount) + { + return false; + } + for (var i = 0; i < mixinsImpl.Count; ++i) { - if (mixinsImpl[i].GetType() != other.mixinsImpl[i].GetType()) + if (mixinsImpl[i]?.GetType() != other.mixinsImpl[i]?.GetType()) { return false; } } + if (delegateMixinCount > 0) + { + var delegateMixinTypes = mixinPositions.Select(m => m.Key).Where(TypeUtil.IsDelegateType); + var otherDelegateMixinTypes = other.mixinPositions.Select(m => m.Key).Where(TypeUtil.IsDelegateType); + return Enumerable.SequenceEqual(delegateMixinTypes, otherDelegateMixinTypes); + } + return true; } @@ -123,7 +191,7 @@ public override int GetHashCode() var hashCode = 0; foreach (var mixinImplementation in mixinsImpl) { - hashCode = 29*hashCode + mixinImplementation.GetType().GetHashCode(); + hashCode = unchecked(29 * hashCode + mixinImplementation?.GetType().GetHashCode() ?? 307); } return hashCode; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs index 1ea77708..2e099701 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,573 +14,529 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy { - using System; - using System.Collections.Generic; - using System.IO; - using System.Reflection; - using System.Reflection.Emit; - using System.Resources; - - using Telerik.JustMock.Core.Castle.Core.Internal; - using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Reflection; + using System.Reflection.Emit; + using System.Resources; + using System.Threading; + + using Telerik.JustMock.Core.Castle.Core.Internal; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; using Telerik.JustMock.Core.DynamicProxy; #if FEATURE_SERIALIZATION - using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; + using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; #endif - /// - /// Summary description for ModuleScope. - /// - internal class ModuleScope - { - /// - /// The default file name used when the assembly is saved using . - /// - public static readonly String DEFAULT_FILE_NAME = "Telerik.JustMock.Dynamic.dll"; - - /// - /// The default assembly (simple) name used for the assemblies generated by a instance. - /// - public static readonly String DEFAULT_ASSEMBLY_NAME = "Telerik.JustMock"; - - private ModuleBuilder moduleBuilderWithStrongName; - private ModuleBuilder moduleBuilder; - - // The names to use for the generated assemblies and the paths (including the names) of their manifest modules - private readonly string strongAssemblyName; - private readonly string weakAssemblyName; - private readonly string strongModulePath; - private readonly string weakModulePath; - - // Keeps track of generated types - private readonly Dictionary typeCache = new Dictionary(); - - // Users of ModuleScope should use this lock when accessing the cache - private readonly Lock cacheLock = Lock.Create(); - - // Used to lock the module builder creation - private readonly object moduleLocker = new object(); - - // Specified whether the generated assemblies are intended to be saved - private readonly bool savePhysicalAssembly; - private readonly bool disableSignedModule; - private readonly INamingScope namingScope; - - /// - /// Initializes a new instance of the class; assemblies created by this instance will not be saved. - /// - public ModuleScope() : this(false, false) - { - } - - /// - /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance - /// should be saved. - /// - /// If set to true saves the generated module. - public ModuleScope(bool savePhysicalAssembly) - : this(savePhysicalAssembly, false) - { - } - - /// - /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance - /// should be saved. - /// - /// If set to true saves the generated module. - /// If set to true disables ability to generate signed module. This should be used in cases where ran under constrained permissions. - public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule) - : this( - savePhysicalAssembly, disableSignedModule, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME, - DEFAULT_FILE_NAME) - { - } - - /// - /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance - /// should be saved and what simple names are to be assigned to them. - /// - /// If set to true saves the generated module. - /// If set to true disables ability to generate signed module. This should be used in cases where ran under constrained permissions. - /// The simple name of the strong-named assembly generated by this . - /// The path and file name of the manifest module of the strong-named assembly generated by this . - /// The simple name of the weak-named assembly generated by this . - /// The path and file name of the manifest module of the weak-named assembly generated by this . - public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, string strongAssemblyName, - string strongModulePath, - string weakAssemblyName, string weakModulePath) - : this( - savePhysicalAssembly, disableSignedModule, new NamingScope(), strongAssemblyName, strongModulePath, weakAssemblyName, - weakModulePath) - { - } - - /// - /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance - /// should be saved and what simple names are to be assigned to them. - /// - /// If set to true saves the generated module. - /// If set to true disables ability to generate signed module. This should be used in cases where ran under constrained permissions. - /// Naming scope used to provide unique names to generated types and their members (usually via sub-scopes). - /// The simple name of the strong-named assembly generated by this . - /// The path and file name of the manifest module of the strong-named assembly generated by this . - /// The simple name of the weak-named assembly generated by this . - /// The path and file name of the manifest module of the weak-named assembly generated by this . - public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, INamingScope namingScope, - string strongAssemblyName, string strongModulePath, - string weakAssemblyName, string weakModulePath) - { - this.savePhysicalAssembly = savePhysicalAssembly; - this.disableSignedModule = disableSignedModule; - this.namingScope = namingScope; - this.strongAssemblyName = strongAssemblyName; - this.strongModulePath = strongModulePath; - this.weakAssemblyName = weakAssemblyName; - this.weakModulePath = weakModulePath; - } - - public INamingScope NamingScope - { - get { return namingScope; } - } - - /// - /// Users of this should use this lock when accessing the cache. - /// - public Lock Lock - { - get { return cacheLock; } - } - - /// - /// Returns a type from this scope's type cache, or null if the key cannot be found. - /// - /// The key to be looked up in the cache. - /// The type from this scope's type cache matching the key, or null if the key cannot be found - public Type GetFromCache(CacheKey key) - { - Type type; - typeCache.TryGetValue(key, out type); - return type; - } - - /// - /// Registers a type in this scope's type cache. - /// - /// The key to be associated with the type. - /// The type to be stored in the cache. - public void RegisterInCache(CacheKey key, Type type) - { - typeCache[key] = type; - } - - /// - /// Gets the key pair used to sign the strong-named assembly generated by this . - /// - /// - public static byte[] GetKeyPair() - { + internal class ModuleScope + { + /// + /// The default file name used when the assembly is saved using . + /// + public static readonly string DEFAULT_FILE_NAME = "Telerik.JustMock.Dynamic.dll"; + + /// + /// The default assembly (simple) name used for the assemblies generated by a instance. + /// + public static readonly string DEFAULT_ASSEMBLY_NAME = "Telerik.JustMock"; + + private ModuleBuilder moduleBuilderWithStrongName; + private ModuleBuilder moduleBuilder; + + // The names to use for the generated assemblies and the paths (including the names) of their manifest modules + private readonly string strongAssemblyName; + private readonly string weakAssemblyName; + private readonly string strongModulePath; + private readonly string weakModulePath; + + // Keeps track of generated types + private readonly SynchronizedDictionary typeCache = new SynchronizedDictionary(); + + // Used to lock the module builder creation + private readonly object moduleLocker = new object(); + + // Specified whether the generated assemblies are intended to be saved + private readonly bool savePhysicalAssembly; + private readonly bool disableSignedModule; + private readonly INamingScope namingScope; + + /// + /// Initializes a new instance of the class; assemblies created by this instance will not be saved. + /// + public ModuleScope() : this(false, false) + { + } + + /// + /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance + /// should be saved. + /// + /// If set to true saves the generated module. + public ModuleScope(bool savePhysicalAssembly) + : this(savePhysicalAssembly, false) + { + } + + /// + /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance + /// should be saved. + /// + /// If set to true saves the generated module. + /// If set to true disables ability to generate signed module. This should be used in cases where ran under constrained permissions. + public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule) + : this( + savePhysicalAssembly, disableSignedModule, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME, + DEFAULT_FILE_NAME) + { + } + + /// + /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance + /// should be saved and what simple names are to be assigned to them. + /// + /// If set to true saves the generated module. + /// If set to true disables ability to generate signed module. This should be used in cases where ran under constrained permissions. + /// The simple name of the strong-named assembly generated by this . + /// The path and file name of the manifest module of the strong-named assembly generated by this . + /// The simple name of the weak-named assembly generated by this . + /// The path and file name of the manifest module of the weak-named assembly generated by this . + public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, string strongAssemblyName, + string strongModulePath, + string weakAssemblyName, string weakModulePath) + : this( + savePhysicalAssembly, disableSignedModule, new NamingScope(), strongAssemblyName, strongModulePath, weakAssemblyName, + weakModulePath) + { + } + + /// + /// Initializes a new instance of the class, allowing to specify whether the assemblies generated by this instance + /// should be saved and what simple names are to be assigned to them. + /// + /// If set to true saves the generated module. + /// If set to true disables ability to generate signed module. This should be used in cases where ran under constrained permissions. + /// Naming scope used to provide unique names to generated types and their members (usually via sub-scopes). + /// The simple name of the strong-named assembly generated by this . + /// The path and file name of the manifest module of the strong-named assembly generated by this . + /// The simple name of the weak-named assembly generated by this . + /// The path and file name of the manifest module of the weak-named assembly generated by this . + internal ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, INamingScope namingScope, + string strongAssemblyName, string strongModulePath, + string weakAssemblyName, string weakModulePath) + { + this.savePhysicalAssembly = savePhysicalAssembly; + this.disableSignedModule = disableSignedModule; + this.namingScope = namingScope; + this.strongAssemblyName = strongAssemblyName; + this.strongModulePath = strongModulePath; + this.weakAssemblyName = weakAssemblyName; + this.weakModulePath = weakModulePath; + } + + internal INamingScope NamingScope + { + get { return namingScope; } + } + + internal SynchronizedDictionary TypeCache => typeCache; + + /// + /// Gets the key pair used to sign the strong-named assembly generated by this . + /// + public static byte[] GetKeyPair() + { string snkeyName = DEFAULT_ASSEMBLY_NAME + ".Core.DynamicProxy.DynamicProxy.snk"; - var assembly = typeof(ModuleScope).GetTypeInfo().Assembly; - - using (var stream = typeof(ModuleScope).GetTypeInfo().Assembly.GetManifestResourceStream(snkeyName)) - { - if (stream == null) - { - throw new MissingManifestResourceException( - "Should have a "+ snkeyName + " as an embedded resource, so Dynamic Proxy could sign generated assembly"); - } - - var length = (int)stream.Length; - var keyPair = new byte[length]; - stream.Read(keyPair, 0, length); - return keyPair; - } - } - - /// - /// Gets the strong-named module generated by this scope, or if none has yet been generated. - /// - /// The strong-named module generated by this scope, or if none has yet been generated. - public ModuleBuilder StrongNamedModule - { - get { return moduleBuilderWithStrongName; } - } - - /// - /// Gets the file name of the strongly named module generated by this scope. - /// - /// The file name of the strongly named module generated by this scope. - public string StrongNamedModuleName - { - get { return Path.GetFileName(strongModulePath); } - } + using (var stream = typeof(ModuleScope).Assembly.GetManifestResourceStream(snkeyName)) + { + if (stream == null) + { + throw new MissingManifestResourceException( + "Should have a " + snkeyName + " as an embedded resource, so Dynamic Proxy could sign generated assembly"); + } + + var length = (int)stream.Length; + var keyPair = new byte[length]; + stream.Read(keyPair, 0, length); + return keyPair; + } + } + + /// + /// Gets the strong-named module generated by this scope, or if none has yet been generated. + /// + /// The strong-named module generated by this scope, or if none has yet been generated. + internal ModuleBuilder StrongNamedModule + { + get { return moduleBuilderWithStrongName; } + } + + /// + /// Gets the file name of the strongly named module generated by this scope. + /// + /// The file name of the strongly named module generated by this scope. + public string StrongNamedModuleName + { + get { return Path.GetFileName(strongModulePath); } + } #if FEATURE_ASSEMBLYBUILDER_SAVE - /// - /// Gets the directory where the strongly named module generated by this scope will be saved, or if the current directory - /// is used. - /// - /// The directory where the strongly named module generated by this scope will be saved when is called - /// (if this scope was created to save modules). - public string StrongNamedModuleDirectory - { - get - { - var directory = Path.GetDirectoryName(strongModulePath); - if (string.IsNullOrEmpty(directory)) - { - return null; - } - return directory; - } - } + /// + /// Gets the directory where the strongly named module generated by this scope will be saved, or if the current directory + /// is used. + /// + /// The directory where the strongly named module generated by this scope will be saved when is called + /// (if this scope was created to save modules). + public string StrongNamedModuleDirectory + { + get + { + var directory = Path.GetDirectoryName(strongModulePath); + if (string.IsNullOrEmpty(directory)) + { + return null; + } + return directory; + } + } #endif - /// - /// Gets the weak-named module generated by this scope, or if none has yet been generated. - /// - /// The weak-named module generated by this scope, or if none has yet been generated. - public ModuleBuilder WeakNamedModule - { - get { return moduleBuilder; } - } - - /// - /// Gets the file name of the weakly named module generated by this scope. - /// - /// The file name of the weakly named module generated by this scope. - public string WeakNamedModuleName - { - get { return Path.GetFileName(weakModulePath); } - } + /// + /// Gets the weak-named module generated by this scope, or if none has yet been generated. + /// + /// The weak-named module generated by this scope, or if none has yet been generated. + internal ModuleBuilder WeakNamedModule + { + get { return moduleBuilder; } + } + + /// + /// Gets the file name of the weakly named module generated by this scope. + /// + /// The file name of the weakly named module generated by this scope. + public string WeakNamedModuleName + { + get { return Path.GetFileName(weakModulePath); } + } #if FEATURE_ASSEMBLYBUILDER_SAVE - /// - /// Gets the directory where the weakly named module generated by this scope will be saved, or if the current directory - /// is used. - /// - /// The directory where the weakly named module generated by this scope will be saved when is called - /// (if this scope was created to save modules). - public string WeakNamedModuleDirectory - { - get - { - var directory = Path.GetDirectoryName(weakModulePath); - if (directory == string.Empty) - { - return null; - } - return directory; - } - } + /// + /// Gets the directory where the weakly named module generated by this scope will be saved, or if the current directory + /// is used. + /// + /// The directory where the weakly named module generated by this scope will be saved when is called + /// (if this scope was created to save modules). + public string WeakNamedModuleDirectory + { + get + { + var directory = Path.GetDirectoryName(weakModulePath); + if (directory == string.Empty) + { + return null; + } + return directory; + } + } #endif - /// - /// Gets the specified module generated by this scope, creating a new one if none has yet been generated. - /// - /// If set to true, a strong-named module is returned; otherwise, a weak-named module is returned. - /// A strong-named or weak-named module generated by this scope, as specified by the parameter. - public ModuleBuilder ObtainDynamicModule(bool isStrongNamed) - { - if (isStrongNamed) - { - return ObtainDynamicModuleWithStrongName(); - } - - return ObtainDynamicModuleWithWeakName(); - } - - /// - /// Gets the strong-named module generated by this scope, creating a new one if none has yet been generated. - /// - /// A strong-named module generated by this scope. - public ModuleBuilder ObtainDynamicModuleWithStrongName() - { - if (disableSignedModule) - { - throw new InvalidOperationException( - "Usage of signed module has been disabled. Use unsigned module or enable signed module."); - } - lock (moduleLocker) - { - if (moduleBuilderWithStrongName == null) - { - moduleBuilderWithStrongName = CreateModule(true); - } - return moduleBuilderWithStrongName; - } - } - - /// - /// Gets the weak-named module generated by this scope, creating a new one if none has yet been generated. - /// - /// A weak-named module generated by this scope. - public ModuleBuilder ObtainDynamicModuleWithWeakName() - { - lock (moduleLocker) - { - if (moduleBuilder == null) - { - moduleBuilder = CreateModule(false); - } - return moduleBuilder; - } - } - - private ModuleBuilder CreateModule(bool signStrongName) - { - var assemblyName = GetAssemblyName(signStrongName); - var moduleName = signStrongName ? StrongNamedModuleName : WeakNamedModuleName; + /// + /// Gets the specified module generated by this scope, creating a new one if none has yet been generated. + /// + /// If set to true, a strong-named module is returned; otherwise, a weak-named module is returned. + /// A strong-named or weak-named module generated by this scope, as specified by the parameter. + internal ModuleBuilder ObtainDynamicModule(bool isStrongNamed) + { + if (isStrongNamed) + { + return ObtainDynamicModuleWithStrongName(); + } + + return ObtainDynamicModuleWithWeakName(); + } + + /// + /// Gets the strong-named module generated by this scope, creating a new one if none has yet been generated. + /// + /// A strong-named module generated by this scope. + internal ModuleBuilder ObtainDynamicModuleWithStrongName() + { + if (disableSignedModule) + { + throw new InvalidOperationException( + "Usage of signed module has been disabled. Use unsigned module or enable signed module."); + } + lock (moduleLocker) + { + if (moduleBuilderWithStrongName == null) + { + moduleBuilderWithStrongName = CreateModule(true); + } + return moduleBuilderWithStrongName; + } + } + + /// + /// Gets the weak-named module generated by this scope, creating a new one if none has yet been generated. + /// + /// A weak-named module generated by this scope. + internal ModuleBuilder ObtainDynamicModuleWithWeakName() + { + lock (moduleLocker) + { + if (moduleBuilder == null) + { + moduleBuilder = CreateModule(false); + } + return moduleBuilder; + } + } + + private ModuleBuilder CreateModule(bool signStrongName) + { + var assemblyName = GetAssemblyName(signStrongName); + var moduleName = signStrongName ? StrongNamedModuleName : WeakNamedModuleName; #if FEATURE_APPDOMAIN - if (savePhysicalAssembly) - { - AssemblyBuilder assemblyBuilder; - try - { - assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( - assemblyName, AssemblyBuilderAccess.RunAndSave, signStrongName ? StrongNamedModuleDirectory : WeakNamedModuleDirectory); - } - catch (ArgumentException e) - { - if (signStrongName == false && e.StackTrace.Contains("ComputePublicKey") == false) - { - // I have no idea what that could be - throw; - } - var message = string.Format( - "There was an error creating dynamic assembly for your proxies - you don't have permissions " + - "required to sign the assembly. To workaround it you can enforce generating non-signed assembly " + - "only when creating {0}. Alternatively ensure that your account has all the required permissions.", - GetType()); - throw new ArgumentException(message, e); - } - var module = assemblyBuilder.DefineDynamicModule(moduleName, moduleName, false); - return module; - } - else + if (savePhysicalAssembly) + { + AssemblyBuilder assemblyBuilder; + try + { + assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( + assemblyName, AssemblyBuilderAccess.RunAndSave, signStrongName ? StrongNamedModuleDirectory : WeakNamedModuleDirectory); + } + catch (ArgumentException e) + { + if (signStrongName == false && e.StackTrace.Contains("ComputePublicKey") == false) + { + // I have no idea what that could be + throw; + } + var message = string.Format( + "There was an error creating dynamic assembly for your proxies - you don't have permissions " + + "required to sign the assembly. To workaround it you can enforce generating non-signed assembly " + + "only when creating {0}. Alternatively ensure that your account has all the required permissions.", + GetType()); + throw new ArgumentException(message, e); + } + var module = assemblyBuilder.DefineDynamicModule(moduleName, moduleName, false); + return module; + } + else #endif - { + { #if FEATURE_APPDOMAIN - var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( - assemblyName, AssemblyBuilderAccess.Run); + var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( + assemblyName, AssemblyBuilderAccess.Run); #else var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); #endif - var module = assemblyBuilder.DefineDynamicModule(moduleName); - return module; - } - } + var module = assemblyBuilder.DefineDynamicModule(moduleName); + return module; + } + } - private AssemblyName GetAssemblyName(bool signStrongName) - { - var assemblyName = new AssemblyName - { - Name = signStrongName ? strongAssemblyName : weakAssemblyName - }; + private AssemblyName GetAssemblyName(bool signStrongName) + { + var assemblyName = new AssemblyName { + Name = signStrongName ? strongAssemblyName : weakAssemblyName + }; - if (signStrongName) - { + if (signStrongName) + { #if FEATURE_ASSEMBLYBUILDER_SAVE - byte[] keyPairStream = GetKeyPair(); - if (keyPairStream != null) - { - assemblyName.KeyPair = new StrongNameKeyPair(keyPairStream); - } + assemblyName.KeyPair = new StrongNameKeyPair(GetKeyPair()); #else assemblyName.SetPublicKey(JustMockInternalsVisible.JustMockGenAssemblyPublicKey); #endif } return assemblyName; - } + } #if FEATURE_ASSEMBLYBUILDER_SAVE - /// - /// Saves the generated assembly with the name and directory information given when this instance was created (or with - /// the and current directory if none was given). - /// - /// - /// - /// This method stores the generated assembly in the directory passed as part of the module information specified when this instance was - /// constructed (if any, else the current directory is used). If both a strong-named and a weak-named assembly - /// have been generated, it will throw an exception; in this case, use the overload. - /// - /// - /// If this was created without indicating that the assembly should be saved, this method does nothing. - /// - /// - /// Both a strong-named and a weak-named assembly have been generated. - /// The path of the generated assembly file, or null if no file has been generated. - public string SaveAssembly() - { - if (!savePhysicalAssembly) - { - return null; - } - - if (StrongNamedModule != null && WeakNamedModule != null) - { - throw new InvalidOperationException("Both a strong-named and a weak-named assembly have been generated."); - } - - if (StrongNamedModule != null) - { - return SaveAssembly(true); - } - - if (WeakNamedModule != null) - { - return SaveAssembly(false); - } - - return null; - } - - /// - /// Saves the specified generated assembly with the name and directory information given when this instance was created - /// (or with the and current directory if none was given). - /// - /// True if the generated assembly with a strong name should be saved (see ); - /// false if the generated assembly without a strong name should be saved (see . - /// - /// - /// This method stores the specified generated assembly in the directory passed as part of the module information specified when this instance was - /// constructed (if any, else the current directory is used). - /// - /// - /// If this was created without indicating that the assembly should be saved, this method does nothing. - /// - /// - /// No assembly has been generated that matches the parameter. - /// - /// The path of the generated assembly file, or null if no file has been generated. - public string SaveAssembly(bool strongNamed) - { - if (!savePhysicalAssembly) - { - return null; - } - - AssemblyBuilder assemblyBuilder; - string assemblyFileName; - string assemblyFilePath; - - if (strongNamed) - { - if (StrongNamedModule == null) - { - throw new InvalidOperationException("No strong-named assembly has been generated."); - } - assemblyBuilder = (AssemblyBuilder)StrongNamedModule.Assembly; - assemblyFileName = StrongNamedModuleName; - assemblyFilePath = StrongNamedModule.FullyQualifiedName; - } - else - { - if (WeakNamedModule == null) - { - throw new InvalidOperationException("No weak-named assembly has been generated."); - } - assemblyBuilder = (AssemblyBuilder)WeakNamedModule.Assembly; - assemblyFileName = WeakNamedModuleName; - assemblyFilePath = WeakNamedModule.FullyQualifiedName; - } - - if (File.Exists(assemblyFilePath)) - { - File.Delete(assemblyFilePath); - } + /// + /// Saves the generated assembly with the name and directory information given when this instance was created (or with + /// the and current directory if none was given). + /// + /// + /// + /// This method stores the generated assembly in the directory passed as part of the module information specified when this instance was + /// constructed (if any, else the current directory is used). If both a strong-named and a weak-named assembly + /// have been generated, it will throw an exception; in this case, use the overload. + /// + /// + /// If this was created without indicating that the assembly should be saved, this method does nothing. + /// + /// + /// Both a strong-named and a weak-named assembly have been generated. + /// The path of the generated assembly file, or null if no file has been generated. + public string SaveAssembly() + { + if (!savePhysicalAssembly) + { + return null; + } + + if (StrongNamedModule != null && WeakNamedModule != null) + { + throw new InvalidOperationException("Both a strong-named and a weak-named assembly have been generated."); + } + + if (StrongNamedModule != null) + { + return SaveAssembly(true); + } + + if (WeakNamedModule != null) + { + return SaveAssembly(false); + } + + return null; + } + + /// + /// Saves the specified generated assembly with the name and directory information given when this instance was created + /// (or with the and current directory if none was given). + /// + /// True if the generated assembly with a strong name should be saved (see ); + /// false if the generated assembly without a strong name should be saved (see . + /// + /// + /// This method stores the specified generated assembly in the directory passed as part of the module information specified when this instance was + /// constructed (if any, else the current directory is used). + /// + /// + /// If this was created without indicating that the assembly should be saved, this method does nothing. + /// + /// + /// No assembly has been generated that matches the parameter. + /// + /// The path of the generated assembly file, or null if no file has been generated. + public string SaveAssembly(bool strongNamed) + { + if (!savePhysicalAssembly) + { + return null; + } + + AssemblyBuilder assemblyBuilder; + string assemblyFileName; + string assemblyFilePath; + + if (strongNamed) + { + if (StrongNamedModule == null) + { + throw new InvalidOperationException("No strong-named assembly has been generated."); + } + assemblyBuilder = (AssemblyBuilder)StrongNamedModule.Assembly; + assemblyFileName = StrongNamedModuleName; + assemblyFilePath = StrongNamedModule.FullyQualifiedName; + } + else + { + if (WeakNamedModule == null) + { + throw new InvalidOperationException("No weak-named assembly has been generated."); + } + assemblyBuilder = (AssemblyBuilder)WeakNamedModule.Assembly; + assemblyFileName = WeakNamedModuleName; + assemblyFilePath = WeakNamedModule.FullyQualifiedName; + } + + if (File.Exists(assemblyFilePath)) + { + File.Delete(assemblyFilePath); + } #if FEATURE_SERIALIZATION - AddCacheMappings(assemblyBuilder); + AddCacheMappings(assemblyBuilder); #endif - assemblyBuilder.Save(assemblyFileName); - return assemblyFilePath; - } + assemblyBuilder.Save(assemblyFileName); + return assemblyFilePath; + } #endif #if FEATURE_SERIALIZATION - private void AddCacheMappings(AssemblyBuilder builder) - { - Dictionary mappings; - - using (Lock.ForReading()) - { - mappings = new Dictionary(); - foreach (var cacheEntry in typeCache) - { - // NOTE: using == returns invalid results. - // we need to use Equals here for it to work properly - if (builder.Equals(cacheEntry.Value.Assembly)) - { - mappings.Add(cacheEntry.Key, cacheEntry.Value.FullName); - } - } - } - - CacheMappingsAttribute.ApplyTo(builder, mappings); - } - - /// - /// Loads the generated types from the given assembly into this 's cache. - /// - /// The assembly to load types from. This assembly must have been saved via or - /// , or it must have the manually applied. - /// - /// This method can be used to load previously generated and persisted proxy types from disk into this scope's type cache, e.g. in order - /// to avoid the performance hit associated with proxy generation. - /// - public void LoadAssemblyIntoCache(Assembly assembly) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - var cacheMappings = - (CacheMappingsAttribute[])assembly.GetCustomAttributes(typeof(CacheMappingsAttribute), false); - - if (cacheMappings.Length == 0) - { - var message = string.Format( - "The given assembly '{0}' does not contain any cache information for generated types.", - assembly.FullName); - throw new ArgumentException(message, "assembly"); - } - - foreach (var mapping in cacheMappings[0].GetDeserializedMappings()) - { - var loadedType = assembly.GetType(mapping.Value); - - if (loadedType != null) - { - RegisterInCache(mapping.Key, loadedType); - } - } - } + private void AddCacheMappings(AssemblyBuilder builder) + { + var mappings = new Dictionary(); + + typeCache.ForEach((key, value) => + { + // NOTE: using == returns invalid results. + // we need to use Equals here for it to work properly + if (builder.Equals(value.Assembly)) + { + mappings.Add(key, value.FullName); + } + }); + + CacheMappingsAttribute.ApplyTo(builder, mappings); + } + + /// + /// Loads the generated types from the given assembly into this 's cache. + /// + /// The assembly to load types from. This assembly must have been saved via or + /// , or it must have the manually applied. + /// + /// This method can be used to load previously generated and persisted proxy types from disk into this scope's type cache, e.g. in order + /// to avoid the performance hit associated with proxy generation. + /// + public void LoadAssemblyIntoCache(Assembly assembly) + { + if (assembly == null) + { + throw new ArgumentNullException(nameof(assembly)); + } + + var cacheMappings = + (CacheMappingsAttribute[])assembly.GetCustomAttributes(typeof(CacheMappingsAttribute), false); + + if (cacheMappings.Length == 0) + { + var message = string.Format( + "The given assembly '{0}' does not contain any cache information for generated types.", + assembly.FullName); + throw new ArgumentException(message, nameof(assembly)); + } + + foreach (var mapping in cacheMappings[0].GetDeserializedMappings()) + { + var loadedType = assembly.GetType(mapping.Value); + + if (loadedType != null) + { + typeCache.AddOrUpdateWithoutTakingLock(mapping.Key, loadedType); + } + } + } #endif - public TypeBuilder DefineType(bool inSignedModulePreferably, string name, TypeAttributes flags) - { - var module = ObtainDynamicModule(disableSignedModule == false && inSignedModulePreferably); - return module.DefineType(name, flags); - } - } + internal TypeBuilder DefineType(bool inSignedModulePreferably, string name, TypeAttributes flags) + { + var module = ObtainDynamicModule(disableSignedModule == false && inSignedModulePreferably); + return module.DefineType(name, flags); + } + } } diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs index 9bb48df7..842cd91c 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -14,17 +14,15 @@ #if FEATURE_ASSEMBLYBUILDER_SAVE -namespace Telerik.JustMock.Core.InternalsVisibleCastle.DynamicProxy +namespace Telerik.JustMock.Core.Castle.DynamicProxy { - using Telerik.JustMock.Core.Castle.DynamicProxy; - - /// - /// ProxyBuilder that persists the generated type. - /// - /// - /// The saved assembly contains just the last generated type. - /// - internal class PersistentProxyBuilder : DefaultProxyBuilder + /// + /// ProxyBuilder that persists the generated type. + /// + /// + /// The saved assembly contains just the last generated type. + /// + internal class PersistentProxyBuilder : DefaultProxyBuilder { /// /// Initializes a new instance of the class. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationException.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationException.cs deleted file mode 100644 index 39734575..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationException.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy -{ - using System; - - internal class ProxyGenerationException : Exception - { - public ProxyGenerationException(string message) : base(message) - { - } - - public ProxyGenerationException(string message, Exception innerException) : base(message, innerException) - { - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs index 531d0c71..4c8c24f4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,19 +16,27 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy { using System; using System.Collections.Generic; + using System.Linq; + using System.Reflection; using System.Reflection.Emit; #if FEATURE_SERIALIZATION using System.Runtime.Serialization; #endif - using CollectionExtensions = Telerik.JustMock.Core.Castle.Core.Internal.CollectionExtensions; -#if DOTNET40 - using System.Security; -#endif + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + + /// + /// allows customization of the behavior of proxies created by + /// an (or proxy types generated by an ). + /// + /// You should not modify an instance of once it has been + /// used to create a proxy (or proxy type). + /// + /// #if FEATURE_SERIALIZATION [Serializable] #endif - internal class ProxyGenerationOptions + internal class ProxyGenerationOptions #if FEATURE_SERIALIZATION : ISerializable #endif @@ -36,7 +44,6 @@ internal class ProxyGenerationOptions public static readonly ProxyGenerationOptions Default = new ProxyGenerationOptions(); private List mixins; - internal readonly IList attributesToAddToGeneratedTypes = new List(); private readonly IList additionalAttributes = new List(); #if FEATURE_SERIALIZATION @@ -82,16 +89,13 @@ public void Initialize() } catch (ArgumentException ex) { - throw new InvalidMixinConfigurationException( - "There is a problem with the mixins added to this ProxyGenerationOptions: " + ex.Message, ex); + throw new InvalidOperationException( + "There is a problem with the mixins added to this ProxyGenerationOptions. See the inner exception for details.", ex); } } } #if FEATURE_SERIALIZATION -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("hook", Hook); @@ -101,12 +105,45 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) } #endif + /// + /// Gets or sets the that should be used during proxy type + /// generation. Defaults to an instance of . + /// + /// You should not modify this property once this instance + /// has been used to create a proxy. + /// + /// public IProxyGenerationHook Hook { get; set; } + /// + /// Gets or sets the that should be used by created proxies + /// to determine which interceptors to use for an interception. If set to + /// (which is the default), created proxies will not use any selector. + /// + /// You should not modify this property once this instance + /// has been used to create a proxy. + /// + /// public IInterceptorSelector Selector { get; set; } + /// + /// Gets or sets the class type from which generated interface proxy types will be derived. + /// Defaults to (). + /// + /// You should not modify this property once this instance + /// has been used to create a proxy. + /// + /// public Type BaseTypeForInterfaceProxy { get; set; } + /// + /// Gets the collection of additional custom attributes that will be put on generated proxy types. + /// This collection is initially empty. + /// + /// You should not modify this collection once this instance + /// has been used to create a proxy. + /// + /// public IList AdditionalAttributes { get { return additionalAttributes; } @@ -124,19 +161,71 @@ public MixinData MixinData } } + /// + /// Adds a delegate type to the list of mixins that will be added to generated proxies. + /// That is, generated proxies will have a `Invoke` method with a signature matching that + /// of the specified . + /// + /// You should not call this method once this instance + /// has been used to create a proxy. + /// + /// + /// The delegate type whose `Invoke` method should be reproduced in generated proxies. + /// is . + /// is not a delegate type. + public void AddDelegateTypeMixin(Type delegateType) + { + if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); + if (!delegateType.IsDelegateType()) throw new ArgumentException("Type must be a delegate type.", nameof(delegateType)); + + AddMixinImpl(delegateType); + } + + /// + /// Adds a delegate to be mixed into generated proxies. The + /// will act as the target for calls to a `Invoke` method with a signature matching that + /// of the delegate. + /// + /// You should not call this method once this instance + /// has been used to create a proxy. + /// + /// + /// The delegate that should act as the target for calls to `Invoke` methods with a matching signature. + /// is . + public void AddDelegateMixin(Delegate @delegate) + { + if (@delegate == null) throw new ArgumentNullException(nameof(@delegate)); + + AddMixinImpl(@delegate); + } + + /// + /// Mixes the interfaces implemented by the specified object into + /// created proxies, and uses as the target for these mixed-in interfaces. + /// + /// You should not call this method once this instance + /// has been used to create a proxy. + /// + /// + /// The object that should act as the target for all of its implemented interfaces' methods. + /// is . + /// is an instance of . public void AddMixinInstance(object instance) { - if (instance == null) - { - throw new ArgumentNullException("instance"); - } + if (instance == null) throw new ArgumentNullException(nameof(instance)); + if (instance is Type) throw new ArgumentException("You may not mix in types using this method.", nameof(instance)); + + AddMixinImpl(instance); + } + private void AddMixinImpl(object instanceOrType) + { if (mixins == null) { mixins = new List(); } - mixins.Add(instance); + mixins.Add(instanceOrType); mixinData = null; } @@ -188,7 +277,7 @@ public override bool Equals(object obj) { return false; } - if (!CollectionExtensions.AreEquivalent(AdditionalAttributes, proxyGenerationOptions.AdditionalAttributes)) + if (!HasEquivalentAdditionalAttributes(proxyGenerationOptions)) { return false; } @@ -204,8 +293,61 @@ public override int GetHashCode() result = 29*result + (Selector != null ? 1 : 0); result = 29*result + MixinData.GetHashCode(); result = 29*result + (BaseTypeForInterfaceProxy != null ? BaseTypeForInterfaceProxy.GetHashCode() : 0); - result = 29*result + CollectionExtensions.GetContentsHashCode(AdditionalAttributes); + result = 29*result + GetAdditionalAttributesHashCode(); return result; } + + private int GetAdditionalAttributesHashCode() + { + var result = 0; + for (var i = 0; i < additionalAttributes.Count; i++) + { + if (additionalAttributes[i] != null) + { + // simply add since order does not matter + result += additionalAttributes[i].GetHashCode(); + } + } + + return result; + } + + private bool HasEquivalentAdditionalAttributes(ProxyGenerationOptions other) + { + var listA = additionalAttributes; + var listB = other.additionalAttributes; + + if (listA.Count != listB.Count) + { + return false; + } + + // copy contents to another list so that contents can be removed as they are found, + // in order to consider duplicates + var listBAvailableContents = listB.ToList(); + + // order is not important, just make sure that each entry in A is also found in B + for (var i = 0; i < listA.Count; i++) + { + var found = false; + + for (var j = 0; j < listBAvailableContents.Count; j++) + { + if (Equals(listA[i], listBAvailableContents[j])) + { + found = true; + listBAvailableContents.RemoveAt(j); + break; + } + } + + if (!found) + { + return false; + } + } + + return true; + } } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs index adbc34d9..7857a05b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2016 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2022 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -16,21 +16,12 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy { using System; using System.Collections.Generic; - using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; -#if FEATURE_REMOTING - using System.Runtime.Remoting; -#endif -#if FEATURE_SECURITY_PERMISSIONS - using System.Security; - using System.Security.Permissions; -#endif using System.Text; - using Castle.Core.Internal; - using Castle.Core.Logging; - using Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.Core.Internal; + using Telerik.JustMock.Core.Castle.Core.Logging; /// /// Provides proxy objects for classes and interfaces. @@ -49,21 +40,8 @@ public ProxyGenerator(IProxyBuilder builder) { proxyBuilder = builder; -#if FEATURE_SECURITY_PERMISSIONS - if (HasSecurityPermission()) -#endif - { - Logger = new TraceLogger("Castle.DynamicProxy", LoggerLevel.Warn); - } - } - -#if FEATURE_SECURITY_PERMISSIONS - private bool HasSecurityPermission() - { - const SecurityPermissionFlag flag = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy; - return new SecurityPermission(flag).IsGranted(); + Logger = new TraceLogger("Castle.DynamicProxy", LoggerLevel.Warn); } -#endif /// /// Initializes a new instance of the class. @@ -309,30 +287,30 @@ public virtual object CreateInterfaceProxyWithTarget(Type interfaceToProxy, Type { if (interfaceToProxy == null) { - throw new ArgumentNullException("interfaceToProxy"); + throw new ArgumentNullException(nameof(interfaceToProxy)); } if (target == null) { - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); } if (interceptors == null) { - throw new ArgumentNullException("interceptors"); + throw new ArgumentNullException(nameof(interceptors)); } - if (!interfaceToProxy.GetTypeInfo().IsInterface) + if (!interfaceToProxy.IsInterface) { - throw new ArgumentException("Specified type is not an interface", "interfaceToProxy"); + throw new ArgumentException("Specified type is not an interface", nameof(interfaceToProxy)); } var targetType = target.GetType(); if (!interfaceToProxy.IsAssignableFrom(targetType)) { - throw new ArgumentException("Target does not implement interface " + interfaceToProxy.FullName, "target"); + throw new ArgumentException("Target does not implement interface " + interfaceToProxy.FullName, nameof(target)); } - CheckNotGenericTypeDefinition(interfaceToProxy, "interfaceToProxy"); - CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy"); + CheckNotGenericTypeDefinition(interfaceToProxy, nameof(interfaceToProxy)); + CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); var generatedType = CreateInterfaceProxyTypeWithTarget(interfaceToProxy, additionalInterfacesToProxy, targetType, options); @@ -550,9 +528,6 @@ public object CreateInterfaceProxyWithTargetInterface(Type interfaceToProxy, obj /// This method uses implementation to generate a proxy type. /// As such caller should expect any type of exception that given implementation may throw. /// -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public virtual object CreateInterfaceProxyWithTargetInterface(Type interfaceToProxy, Type[] additionalInterfacesToProxy, object target, ProxyGenerationOptions options, @@ -562,30 +537,32 @@ public virtual object CreateInterfaceProxyWithTargetInterface(Type interfaceToPr if (interfaceToProxy == null) { - throw new ArgumentNullException("interfaceToProxy"); + throw new ArgumentNullException(nameof(interfaceToProxy)); } // In the case of a transparent proxy, the call to IsInstanceOfType was executed on the real object. if (target != null && interfaceToProxy.IsInstanceOfType(target) == false) { - throw new ArgumentException("Target does not implement interface " + interfaceToProxy.FullName, "target"); + throw new ArgumentException("Target does not implement interface " + interfaceToProxy.FullName, nameof(target)); } if (interceptors == null) { - throw new ArgumentNullException("interceptors"); + throw new ArgumentNullException(nameof(interceptors)); } - if (!interfaceToProxy.GetTypeInfo().IsInterface) + if (!interfaceToProxy.IsInterface) { - throw new ArgumentException("Specified type is not an interface", "interfaceToProxy"); + throw new ArgumentException("Specified type is not an interface", nameof(interfaceToProxy)); } - var isRemotingProxy = false; -#if FEATURE_REMOTING if (target != null) { - isRemotingProxy = RemotingServices.IsTransparentProxy(target); +#if NET6_0_OR_GREATER + bool doComHandling = OperatingSystem.IsWindows(); +#else + bool doComHandling = true; +#endif - if (!isRemotingProxy && Marshal.IsComObject(target)) + if (doComHandling && Marshal.IsComObject(target)) { var interfaceId = interfaceToProxy.GUID; if (interfaceId != Guid.Empty) @@ -603,27 +580,18 @@ public virtual object CreateInterfaceProxyWithTargetInterface(Type interfaceToPr if (result == 0 && isInterfacePointerNull) { throw new ArgumentException("Target COM object does not implement interface " + interfaceToProxy.FullName, - "target"); + nameof(target)); } } } } -#endif - CheckNotGenericTypeDefinition(interfaceToProxy, "interfaceToProxy"); - CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy"); + CheckNotGenericTypeDefinition(interfaceToProxy, nameof(interfaceToProxy)); + CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); var generatedType = CreateInterfaceProxyTypeWithTargetInterface(interfaceToProxy, additionalInterfacesToProxy, options); var arguments = GetConstructorArguments(target, interceptors, options); - if (isRemotingProxy) - { - var constructors = generatedType.GetConstructors(); - - // one .ctor to rule them all - Debug.Assert(constructors.Length == 1, "constructors.Length == 1"); - return constructors[0].Invoke(arguments.ToArray()); - } return Activator.CreateInstance(generatedType, arguments.ToArray()); } @@ -849,20 +817,20 @@ public virtual object CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, T { if (interfaceToProxy == null) { - throw new ArgumentNullException("interfaceToProxy"); + throw new ArgumentNullException(nameof(interfaceToProxy)); } if (interceptors == null) { - throw new ArgumentNullException("interceptors"); + throw new ArgumentNullException(nameof(interceptors)); } - if (!interfaceToProxy.GetTypeInfo().IsInterface) + if (!interfaceToProxy.IsInterface) { - throw new ArgumentException("Specified type is not an interface", "interfaceToProxy"); + throw new ArgumentException("Specified type is not an interface", nameof(interfaceToProxy)); } - CheckNotGenericTypeDefinition(interfaceToProxy, "interfaceToProxy"); - CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy"); + CheckNotGenericTypeDefinition(interfaceToProxy, nameof(interfaceToProxy)); + CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); var generatedType = CreateInterfaceProxyTypeWithoutTarget(interfaceToProxy, additionalInterfacesToProxy, options); var arguments = GetConstructorArguments(null, interceptors, options); @@ -1159,19 +1127,19 @@ public virtual object CreateClassProxyWithTarget(Type classToProxy, Type[] addit { if (classToProxy == null) { - throw new ArgumentNullException("classToProxy"); + throw new ArgumentNullException(nameof(classToProxy)); } if (options == null) { - throw new ArgumentNullException("options"); + throw new ArgumentNullException(nameof(options)); } - if (!classToProxy.GetTypeInfo().IsClass) + if (!classToProxy.IsClass) { - throw new ArgumentException("'classToProxy' must be a class", "classToProxy"); + throw new ArgumentException("'classToProxy' must be a class", nameof(classToProxy)); } - CheckNotGenericTypeDefinition(classToProxy, "classToProxy"); - CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy"); + CheckNotGenericTypeDefinition(classToProxy, nameof(classToProxy)); + CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); var proxyType = CreateClassProxyTypeWithTarget(classToProxy, additionalInterfacesToProxy, options); @@ -1423,19 +1391,19 @@ public virtual object CreateClassProxy(Type classToProxy, Type[] additionalInter { if (classToProxy == null) { - throw new ArgumentNullException("classToProxy"); + throw new ArgumentNullException(nameof(classToProxy)); } if (options == null) { - throw new ArgumentNullException("options"); + throw new ArgumentNullException(nameof(options)); } - if (!classToProxy.GetTypeInfo().IsClass) + if (!classToProxy.IsClass) { - throw new ArgumentException("'classToProxy' must be a class", "classToProxy"); + throw new ArgumentException("'classToProxy' must be a class", nameof(classToProxy)); } - CheckNotGenericTypeDefinition(classToProxy, "classToProxy"); - CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy"); + CheckNotGenericTypeDefinition(classToProxy, nameof(classToProxy)); + CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, nameof(additionalInterfacesToProxy)); var proxyType = CreateClassProxyType(classToProxy, additionalInterfacesToProxy, options); @@ -1453,9 +1421,9 @@ protected object CreateClassProxyInstance(Type proxyType, List proxyArgu { try { - return proxyType.CreateObject(proxyArguments.ToArray()); - } - catch (MissingMethodException) + return CreateObjectInstance(proxyType, proxyArguments.ToArray()); + } + catch (MissingMethodException ex) { var message = new StringBuilder(); message.AppendFormat("Can not instantiate proxy of class: {0}.", classToProxy.FullName); @@ -1474,16 +1442,17 @@ protected object CreateClassProxyInstance(Type proxyType, List proxyArgu } } - throw new InvalidProxyConstructorArgumentsException(message.ToString(),proxyType,classToProxy); + throw new ArgumentException(message.ToString(), nameof(constructorArguments), ex); } } protected void CheckNotGenericTypeDefinition(Type type, string argumentName) { - if (type != null && type.GetTypeInfo().IsGenericTypeDefinition) + if (type != null && type.IsGenericTypeDefinition) { - throw new GeneratorException(string.Format("Can not create proxy for type {0} because it is an open generic type.", - type.GetBestName())); + throw new ArgumentException( + $"Can not create proxy for type {type.GetBestName()} because it is an open generic type.", + argumentName); } } @@ -1595,5 +1564,14 @@ protected Type CreateClassProxyTypeWithTarget(Type classToProxy, Type[] addition // create proxy return ProxyBuilder.CreateClassProxyTypeWithTarget(classToProxy, additionalInterfacesToProxy, options); } + + private static object CreateObjectInstance(Type type, object[] arguments) + { +#if FEATURE_DEFAULT_ACTIVATOR + return Activator.CreateInstance(type, arguments); +#else + return type.CreateObject(arguments); +#endif + } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyUtil.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyUtil.cs index 7376cace..02631689 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyUtil.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyUtil.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -19,29 +19,71 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; - -#if FEATURE_REMOTING - using System.Runtime.Remoting; -#endif + using System.Threading; using Telerik.JustMock.Core.Castle.Core.Internal; + using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; + using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; internal static class ProxyUtil { - private static readonly IDictionary internalsVisibleToDynamicProxy = new Dictionary(); - private static readonly Lock internalsVisibleToDynamicProxyLock = Lock.Create(); + private static readonly SynchronizedDictionary internalsVisibleToDynamicProxy = new SynchronizedDictionary(); + + /// + /// Creates a delegate of the specified type to a suitable `Invoke` method + /// on the given instance. + /// + /// The proxy instance to which the delegate should be bound. + /// The type of delegate that should be created. + /// + /// The does not have an `Invoke` method that is compatible with + /// the requested type. + /// + public static TDelegate CreateDelegateToMixin(object proxy) + { + return (TDelegate)(object)CreateDelegateToMixin(proxy, typeof(TDelegate)); + } + + /// + /// Creates a delegate of the specified type to a suitable `Invoke` method + /// on the given instance. + /// + /// The proxy instance to which the delegate should be bound. + /// The type of delegate that should be created. + /// + /// The does not have an `Invoke` method that is compatible with + /// the requested . + /// + public static Delegate CreateDelegateToMixin(object proxy, Type delegateType) + { + if (proxy == null) throw new ArgumentNullException(nameof(proxy)); + if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); + if (!delegateType.IsDelegateType()) throw new ArgumentException("Type is not a delegate type.", nameof(delegateType)); + + var invokeMethod = delegateType.GetMethod("Invoke"); + var proxiedInvokeMethod = + proxy + .GetType() + .GetMember("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .Cast() + .FirstOrDefault(m => MethodSignatureComparer.Instance.EqualParameters(m, invokeMethod)); + + if (proxiedInvokeMethod == null) + { + throw new MissingMethodException("The proxy does not have an Invoke method " + + "that is compatible with the requested delegate type."); + } + else + { + return Delegate.CreateDelegate(delegateType, proxy, proxiedInvokeMethod); + } + } public static object GetUnproxiedInstance(object instance) { -#if FEATURE_REMOTING - if (!RemotingServices.IsTransparentProxy(instance)) -#endif + if (instance is IProxyTargetAccessor accessor) { - var accessor = instance as IProxyTargetAccessor; - if (accessor != null) - { - instance = accessor.DynProxyGetTarget(); - } + instance = accessor.DynProxyGetTarget(); } return instance; @@ -49,25 +91,17 @@ public static object GetUnproxiedInstance(object instance) public static Type GetUnproxiedType(object instance) { -#if FEATURE_REMOTING - if (!RemotingServices.IsTransparentProxy(instance)) -#endif + if (instance is IProxyTargetAccessor accessor) { - var accessor = instance as IProxyTargetAccessor; - - if (accessor != null) + var target = accessor.DynProxyGetTarget(); + if (target != null) { - var target = accessor.DynProxyGetTarget(); - - if (target != null) + if (ReferenceEquals(target, instance)) { - if (ReferenceEquals(target, instance)) - { - return instance.GetType().GetTypeInfo().BaseType; - } - - instance = target; + return instance.GetType().BaseType; } + + instance = target; } } @@ -76,12 +110,6 @@ public static Type GetUnproxiedType(object instance) public static bool IsProxy(object instance) { -#if FEATURE_REMOTING - if (RemotingServices.IsTransparentProxy(instance)) - { - return true; - } -#endif return instance is IProxyTargetAccessor; } @@ -131,47 +159,26 @@ public static bool IsAccessible(Type type) /// The assembly to inspect. internal static bool AreInternalsVisibleToDynamicProxy(Assembly asm) { - using (var locker = internalsVisibleToDynamicProxyLock.ForReading()) - { - if (internalsVisibleToDynamicProxy.ContainsKey(asm)) - { - return internalsVisibleToDynamicProxy[asm]; - } - } - - using (var locker = internalsVisibleToDynamicProxyLock.ForReadingUpgradeable()) + return internalsVisibleToDynamicProxy.GetOrAdd(asm, a => { - if (internalsVisibleToDynamicProxy.ContainsKey(asm)) - { - return internalsVisibleToDynamicProxy[asm]; - } - - // Upgrade the lock to a write lock. - using (locker.Upgrade()) - { - var internalsVisibleTo = asm.GetCustomAttributes(); - var found = internalsVisibleTo.Any(attr => attr.AssemblyName.Contains(ModuleScope.DEFAULT_ASSEMBLY_NAME)); - internalsVisibleToDynamicProxy.Add(asm, found); - return found; - } - } + var internalsVisibleTo = asm.GetCustomAttributes(); + return internalsVisibleTo.Any(attr => attr.AssemblyName.Contains(ModuleScope.DEFAULT_ASSEMBLY_NAME)); + }); } internal static bool IsAccessibleType(Type target) { - var typeInfo = target.GetTypeInfo(); - - var isPublic = typeInfo.IsPublic || typeInfo.IsNestedPublic; + var isPublic = target.IsPublic || target.IsNestedPublic; if (isPublic) { return true; } var isTargetNested = target.IsNested; - var isNestedAndInternal = isTargetNested && (typeInfo.IsNestedAssembly || typeInfo.IsNestedFamORAssem); - var isInternalNotNested = typeInfo.IsVisible == false && isTargetNested == false; + var isNestedAndInternal = isTargetNested && (target.IsNestedAssembly || target.IsNestedFamORAssem); + var isInternalNotNested = target.IsVisible == false && isTargetNested == false; var isInternal = isInternalNotNested || isNestedAndInternal; - if (isInternal && AreInternalsVisibleToDynamicProxy(typeInfo.Assembly)) + if (isInternal && AreInternalsVisibleToDynamicProxy(target.Assembly)) { return true; } @@ -194,7 +201,7 @@ internal static bool IsAccessibleMethod(MethodBase method) if (method.IsAssembly || method.IsFamilyAndAssembly) { - return AreInternalsVisibleToDynamicProxy(method.DeclaringType.GetTypeInfo().Assembly); + return AreInternalsVisibleToDynamicProxy(method.DeclaringType.Assembly); } return false; @@ -215,7 +222,7 @@ internal static bool IsInternal(MethodBase method) private static string CreateMessageForInaccessibleMethod(MethodBase inaccessibleMethod) { var containingType = inaccessibleMethod.DeclaringType; - var targetAssembly = containingType.GetTypeInfo().Assembly; + var targetAssembly = containingType.Assembly; var messageFormat = "Can not create proxy for method {0} because it or its declaring type is not accessible. "; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs index 604c16d9..a039a402 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -47,7 +47,7 @@ public byte[] SerializedCacheMappings get { return serializedCacheMappings; } } - public Dictionary GetDeserializedMappings() + internal Dictionary GetDeserializedMappings() { using (var stream = new MemoryStream(SerializedCacheMappings)) { @@ -56,7 +56,7 @@ public Dictionary GetDeserializedMappings() } } - public static void ApplyTo(AssemblyBuilder assemblyBuilder, Dictionary mappings) + internal static void ApplyTo(AssemblyBuilder assemblyBuilder, Dictionary mappings) { using (var stream = new MemoryStream()) { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs index c60c5529..4ae099a8 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,9 +21,6 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Serialization using System.Diagnostics; using System.Reflection; using System.Runtime.Serialization; -#if DOTNET40 - using System.Security; -#endif using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; @@ -70,7 +67,7 @@ public static void SetScope(ModuleScope scope) { if (scope == null) { - throw new ArgumentNullException("scope"); + throw new ArgumentNullException(nameof(scope)); } ProxyObjectReference.scope = scope; } @@ -86,9 +83,6 @@ public static ModuleScope ModuleScope get { return scope; } } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif protected ProxyObjectReference(SerializationInfo info, StreamingContext context) { this.info = info; @@ -96,7 +90,7 @@ protected ProxyObjectReference(SerializationInfo info, StreamingContext context) baseType = DeserializeTypeFromString("__baseType"); - var _interfaceNames = (String[])info.GetValue("__interfaces", typeof(String[])); + var _interfaceNames = (string[])info.GetValue("__interfaces", typeof(string[])); interfaces = new Type[_interfaceNames.Length]; for (var i = 0; i < _interfaceNames.Length; i++) @@ -118,9 +112,6 @@ private Type DeserializeTypeFromString(string key) return Type.GetType(info.GetString(key), true, false); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif protected virtual object RecreateProxy() { var generatorType = GetValue("__proxyTypeId"); @@ -138,36 +129,30 @@ protected virtual object RecreateProxy() return RecreateInterfaceProxy(generatorType); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private object RecreateClassProxyWithTarget() { var generator = new ClassProxyWithTargetGenerator(scope, baseType, interfaces, proxyGenerationOptions); - var proxyType = generator.GetGeneratedType(); + var proxyType = generator.GetProxyType(); return InstantiateClassProxy(proxyType); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif public object RecreateInterfaceProxy(string generatorType) { var @interface = DeserializeTypeFromString("__theInterface"); var targetType = DeserializeTypeFromString("__targetFieldType"); - InterfaceProxyWithTargetGenerator generator; + BaseInterfaceProxyGenerator generator; if (generatorType == ProxyTypeConstants.InterfaceWithTarget) { - generator = new InterfaceProxyWithTargetGenerator(scope, @interface); + generator = new InterfaceProxyWithTargetGenerator(scope, @interface, interfaces, targetType, proxyGenerationOptions); } else if (generatorType == ProxyTypeConstants.InterfaceWithoutTarget) { - generator = new InterfaceProxyWithoutTargetGenerator(scope, @interface); + generator = new InterfaceProxyWithoutTargetGenerator(scope, @interface, interfaces, targetType, proxyGenerationOptions); } else if (generatorType == ProxyTypeConstants.InterfaceWithTargetInterface) { - generator = new InterfaceProxyWithTargetInterfaceGenerator(scope, @interface); + generator = new InterfaceProxyWithTargetInterfaceGenerator(scope, @interface, interfaces, targetType, proxyGenerationOptions); } else { @@ -177,23 +162,17 @@ public object RecreateInterfaceProxy(string generatorType) generatorType)); } - var proxyType = generator.GenerateCode(targetType, interfaces, proxyGenerationOptions); + var proxyType = generator.GetProxyType(); return FormatterServices.GetSafeUninitializedObject(proxyType); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif public object RecreateClassProxy() { - var generator = new ClassProxyGenerator(scope, baseType); - var proxyType = generator.GenerateCode(interfaces, proxyGenerationOptions); + var generator = new ClassProxyGenerator(scope, baseType, interfaces, proxyGenerationOptions); + var proxyType = generator.GetProxyType(); return InstantiateClassProxy(proxyType); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private object InstantiateClassProxy(Type proxy_type) { delegateToBase = GetValue("__delegateToBase"); @@ -215,26 +194,17 @@ protected void InvokeCallback(object target) } } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif public object GetRealObject(StreamingContext context) { return proxy; } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif public void GetObjectData(SerializationInfo info, StreamingContext context) { // There is no need to implement this method as // this class would never be serialized. } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecuritySafeCritical] -#endif public void OnDeserialization(object sender) { var interceptors = GetValue("__interceptors"); @@ -247,16 +217,13 @@ public void OnDeserialization(object sender) InvokeCallback(proxy); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private void DeserializeProxyMembers() { var proxyType = proxy.GetType(); var members = FormatterServices.GetSerializableMembers(proxyType); var deserializedMembers = new List(); - var deserializedValues = new List(); + var deserializedValues = new List(); for (var i = 0; i < members.Length; i++) { var member = members[i] as FieldInfo; @@ -274,9 +241,6 @@ private void DeserializeProxyMembers() FormatterServices.PopulateObjectMembers(proxy, deserializedMembers.ToArray(), deserializedValues.ToArray()); } -#if FEATURE_SECURITY_PERMISSIONS && DOTNET40 - [SecurityCritical] -#endif private void DeserializeProxyState() { if (isInterfaceProxy) diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyTypeConstants.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyTypeConstants.cs index 22d2c3b0..e8a71528 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyTypeConstants.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyTypeConstants.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/StandardInterceptor.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/StandardInterceptor.cs index 52e4c45c..008322c3 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/StandardInterceptor.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/StandardInterceptor.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -19,11 +19,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy #if FEATURE_SERIALIZATION [Serializable] #endif - internal class StandardInterceptor : -#if FEATURE_REMOTING - MarshalByRefObject, -#endif - IInterceptor + internal class StandardInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/DelegateMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/DelegateMethods.cs index 9aff309b..81ff3933 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/DelegateMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/DelegateMethods.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/FormatterServicesMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/FormatterServicesMethods.cs index 8c67c311..8945850f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/FormatterServicesMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/FormatterServicesMethods.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InterceptorSelectorMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InterceptorSelectorMethods.cs index 15ce2a76..c3a6b729 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InterceptorSelectorMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InterceptorSelectorMethods.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InvocationMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InvocationMethods.cs index 31c49f2c..dd881bea 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InvocationMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/InvocationMethods.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -36,7 +36,7 @@ internal static class InvocationMethods }, null); - public static readonly MethodInfo EnsureValidTarget = + public static readonly MethodInfo CompositionInvocationEnsureValidTarget = typeof(CompositionInvocation).GetMethod("EnsureValidTarget", BindingFlags.Instance | BindingFlags.NonPublic); public static readonly MethodInfo GetArgumentValue = @@ -89,10 +89,15 @@ internal static class InvocationMethods public static readonly MethodInfo SetReturnValue = typeof(AbstractInvocation).GetMethod("set_ReturnValue"); - public static readonly FieldInfo Target = + public static readonly FieldInfo CompositionInvocationTarget = typeof(CompositionInvocation).GetField("target", BindingFlags.Instance | BindingFlags.NonPublic); public static readonly MethodInfo ThrowOnNoTarget = typeof(AbstractInvocation).GetMethod("ThrowOnNoTarget", BindingFlags.Instance | BindingFlags.NonPublic); + + // The following two fields are not used internally, but kept for back-compatibility + // because we renamed the public fields `EnsureValidTarget` and `Target`: + public static readonly MethodInfo EnsureValidTarget = CompositionInvocationEnsureValidTarget; + public static readonly FieldInfo Target = CompositionInvocationTarget; } } \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/MethodBaseMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/MethodBaseMethods.cs index 878752f0..a299852a 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/MethodBaseMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/MethodBaseMethods.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/SerializationInfoMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/SerializationInfoMethods.cs index 60026a64..2f712f79 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/SerializationInfoMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/SerializationInfoMethods.cs @@ -1,4 +1,4 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -29,25 +29,25 @@ internal static class SerializationInfoMethods /// /// public static readonly MethodInfo AddValue_Bool = - typeof(SerializationInfo).GetMethod("AddValue", new[] { typeof(String), typeof(bool) }); + typeof(SerializationInfo).GetMethod("AddValue", new[] { typeof(string), typeof(bool) }); /// /// /// public static readonly MethodInfo AddValue_Int32 = - typeof(SerializationInfo).GetMethod("AddValue", new[] { typeof(String), typeof(int) }); + typeof(SerializationInfo).GetMethod("AddValue", new[] { typeof(string), typeof(int) }); /// /// /// public static readonly MethodInfo AddValue_Object = - typeof(SerializationInfo).GetMethod("AddValue", new[] { typeof(String), typeof(Object) }); + typeof(SerializationInfo).GetMethod("AddValue", new[] { typeof(string), typeof(object) }); /// /// /// public static readonly MethodInfo GetValue = - typeof(SerializationInfo).GetMethod("GetValue", new[] { typeof(String), typeof(Type) }); + typeof(SerializationInfo).GetMethod("GetValue", new[] { typeof(string), typeof(Type) }); /// /// diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeBuilderMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeBuilderMethods.cs deleted file mode 100644 index 83c07437..00000000 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeBuilderMethods.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.DynamicProxy.Tokens -{ - using System; - using System.Reflection; - using System.Reflection.Emit; - - internal static class TypeBuilderMethods - { - public static readonly MethodInfo DefineProperty = - typeof(TypeBuilder).GetMethod("DefineProperty", - new[] - { - typeof(string), typeof(PropertyAttributes), typeof(CallingConventions), typeof(Type), - typeof(Type[]), typeof(Type[]), typeof(Type[]), typeof(Type[][]), typeof(Type[][]) - }); - } -} \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeMethods.cs index f3db1ee4..108e88ce 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeMethods.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeUtilMethods.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeUtilMethods.cs index d36aa2a1..94c5fe72 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeUtilMethods.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Tokens/TypeUtilMethods.cs @@ -1,10 +1,10 @@ -// Copyright 2004-2012 Castle Project - http://www.castleproject.org/ +// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, diff --git a/Telerik.JustMock/Core/DynamicProxy/VERSION b/Telerik.JustMock/Core/DynamicProxy/VERSION new file mode 100644 index 00000000..3bff0591 --- /dev/null +++ b/Telerik.JustMock/Core/DynamicProxy/VERSION @@ -0,0 +1 @@ +5.1.1 \ No newline at end of file diff --git a/Telerik.JustMock/Core/DynamicProxyMockFactory.cs b/Telerik.JustMock/Core/DynamicProxyMockFactory.cs index f1b247d1..d8806137 100644 --- a/Telerik.JustMock/Core/DynamicProxyMockFactory.cs +++ b/Telerik.JustMock/Core/DynamicProxyMockFactory.cs @@ -50,8 +50,8 @@ internal static void SaveAssembly() public bool IsAccessible(Type type) { - return ProxyUtil.IsAccessibleType(type); - } + return ProxyUtil.IsAccessibleType(type); + } public object Create(Type type, MocksRepository repository, IMockMixin mockMixinImpl, MockCreationSettings settings, bool createTransparentProxy) { @@ -90,7 +90,7 @@ public object Create(Type type, MocksRepository repository, IMockMixin mockMixin { proxyFailure = ex; } - catch (GeneratorException ex) + catch (ArgumentException ex) { proxyFailure = ex; } @@ -129,15 +129,15 @@ public object Create(Type type, MocksRepository repository, IMockMixin mockMixin { proxyFailure = ex; } - catch (GeneratorException ex) - { - proxyFailure = ex; - } - catch (InvalidProxyConstructorArgumentsException ex) + catch (ArgumentException ex) { proxyFailure = ex; - if (!settings.MockConstructorCall) + if (ex.InnerException != null + && ex.InnerException is MissingMethodException + && !settings.MockConstructorCall) + { throw new MockException(ex.Message); + } } } if (proxyFailure != null) @@ -240,23 +240,23 @@ public void NonProxyableMemberNotification(Type type, MemberInfo memberInfo) { } - public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo) - { - if (Attribute.IsDefined(methodInfo.DeclaringType, typeof(MixinAttribute))) - { - return false; - } - - bool profilerCannotIntercept = methodInfo.IsAbstract || methodInfo.IsExtern() || !ProfilerInterceptor.TypeSupportsInstrumentation(methodInfo.DeclaringType); - - if (ProfilerInterceptor.IsProfilerAttached && !profilerCannotIntercept) - { - bool isDefaultMethodImplementation = !methodInfo.IsAbstract && methodInfo.DeclaringType.IsInterface; - if (type == methodInfo.DeclaringType && !isDefaultMethodImplementation) - { - return false; - } - } + public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo) + { + if (Attribute.IsDefined(methodInfo.DeclaringType, typeof(MixinAttribute))) + { + return false; + } + + bool profilerCannotIntercept = methodInfo.IsAbstract || methodInfo.IsExtern() || !ProfilerInterceptor.TypeSupportsInstrumentation(methodInfo.DeclaringType); + + if (ProfilerInterceptor.IsProfilerAttached && !profilerCannotIntercept) + { + bool isDefaultMethodImplementation = !methodInfo.IsAbstract && methodInfo.DeclaringType.IsInterface; + if (type == methodInfo.DeclaringType && !isDefaultMethodImplementation) + { + return false; + } + } return myInterceptorFilterImpl != null ? myInterceptorFilterImpl(methodInfo) : true; } diff --git a/Telerik.JustMock/Core/Internal/ILockHolder.cs b/Telerik.JustMock/Core/Internal/ILockHolder.cs new file mode 100644 index 00000000..1f3a485f --- /dev/null +++ b/Telerik.JustMock/Core/Internal/ILockHolder.cs @@ -0,0 +1,26 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + using System; + + internal interface ILockHolder:IDisposable + { + bool LockAcquired { get; } + } +} diff --git a/Telerik.JustMock/Core/Internal/IUpgradeableLockHolder.cs b/Telerik.JustMock/Core/Internal/IUpgradeableLockHolder.cs new file mode 100644 index 00000000..a4bf4bc0 --- /dev/null +++ b/Telerik.JustMock/Core/Internal/IUpgradeableLockHolder.cs @@ -0,0 +1,25 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + internal interface IUpgradeableLockHolder : ILockHolder + { + ILockHolder Upgrade(); + ILockHolder Upgrade(bool waitForLock); + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/Lock.cs b/Telerik.JustMock/Core/Internal/Lock.cs similarity index 50% rename from Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/Lock.cs rename to Telerik.JustMock/Core/Internal/Lock.cs index 4ffd21a9..9a81067e 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/Lock.cs +++ b/Telerik.JustMock/Core/Internal/Lock.cs @@ -1,18 +1,21 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation -namespace Telerik.JustMock.Core.Castle.Core.Internal + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal { internal abstract class Lock { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLock.cs b/Telerik.JustMock/Core/Internal/MonitorLock.cs similarity index 55% rename from Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLock.cs rename to Telerik.JustMock/Core/Internal/MonitorLock.cs index 435e7a8a..505951c0 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorLock.cs +++ b/Telerik.JustMock/Core/Internal/MonitorLock.cs @@ -1,18 +1,21 @@ -// Copyright 2004-2010 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal { #if COREFX internal class MonitorLock : Lock @@ -50,4 +53,4 @@ public override ILockHolder ForWriting(bool waitForLock) } } #endif -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/Internal/MonitorLockHolder.cs b/Telerik.JustMock/Core/Internal/MonitorLockHolder.cs new file mode 100644 index 00000000..550f8b04 --- /dev/null +++ b/Telerik.JustMock/Core/Internal/MonitorLockHolder.cs @@ -0,0 +1,52 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + using System.Threading; + + internal class MonitorLockHolder : ILockHolder + { + private readonly object locker; + private bool lockAcquired; + + public MonitorLockHolder(object locker, bool waitForLock) + { + this.locker = locker; + if(waitForLock) + { + Monitor.Enter(locker); + lockAcquired = true; + return; + } + + lockAcquired = Monitor.TryEnter(locker, 0); + } + + public void Dispose() + { + if (!LockAcquired) return; + Monitor.Exit(locker); + lockAcquired = false; + } + + public bool LockAcquired + { + get { return lockAcquired; } + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorUpgradeableLockHolder.cs b/Telerik.JustMock/Core/Internal/MonitorUpgradeableLockHolder.cs similarity index 54% rename from Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorUpgradeableLockHolder.cs rename to Telerik.JustMock/Core/Internal/MonitorUpgradeableLockHolder.cs index 8edf3508..46682ca9 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/MonitorUpgradeableLockHolder.cs +++ b/Telerik.JustMock/Core/Internal/MonitorUpgradeableLockHolder.cs @@ -1,18 +1,21 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal { using System.Threading; @@ -55,4 +58,4 @@ public bool LockAcquired get { return lockAcquired; } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/Internal/NoOpLock.cs b/Telerik.JustMock/Core/Internal/NoOpLock.cs new file mode 100644 index 00000000..b373972b --- /dev/null +++ b/Telerik.JustMock/Core/Internal/NoOpLock.cs @@ -0,0 +1,34 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + internal class NoOpLock : ILockHolder + { + public static readonly ILockHolder Lock = new NoOpLock(); + + public void Dispose() + { + + } + + public bool LockAcquired + { + get { return true; } + } + } +} diff --git a/Telerik.JustMock/Core/Internal/NoOpUpgradeableLock.cs b/Telerik.JustMock/Core/Internal/NoOpUpgradeableLock.cs new file mode 100644 index 00000000..a313e261 --- /dev/null +++ b/Telerik.JustMock/Core/Internal/NoOpUpgradeableLock.cs @@ -0,0 +1,44 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + internal class NoOpUpgradeableLock : IUpgradeableLockHolder + { + public static readonly IUpgradeableLockHolder Lock = new NoOpUpgradeableLock(); + + public void Dispose() + { + + } + + public bool LockAcquired + { + get { return true; } + } + + public ILockHolder Upgrade() + { + return NoOpLock.Lock; + } + + public ILockHolder Upgrade(bool waitForLock) + { + return NoOpLock.Lock; + } + } +} diff --git a/Telerik.JustMock/Core/Internal/SlimReadLockHolder.cs b/Telerik.JustMock/Core/Internal/SlimReadLockHolder.cs new file mode 100644 index 00000000..f185c51d --- /dev/null +++ b/Telerik.JustMock/Core/Internal/SlimReadLockHolder.cs @@ -0,0 +1,51 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + using System.Threading; + + internal class SlimReadLockHolder : ILockHolder + { + private readonly ReaderWriterLockSlim locker; + private bool lockAcquired; + + public SlimReadLockHolder(ReaderWriterLockSlim locker, bool waitForLock) + { + this.locker = locker; + if(waitForLock) + { + locker.EnterReadLock(); + lockAcquired = true; + return; + } + lockAcquired = locker.TryEnterReadLock(0); + } + + public void Dispose() + { + if (!LockAcquired) return; + locker.ExitReadLock(); + lockAcquired = false; + } + + public bool LockAcquired + { + get { return lockAcquired; } + } + } +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadWriteLock.cs b/Telerik.JustMock/Core/Internal/SlimReadWriteLock.cs similarity index 68% rename from Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadWriteLock.cs rename to Telerik.JustMock/Core/Internal/SlimReadWriteLock.cs index 9092f27e..a258ddc6 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimReadWriteLock.cs +++ b/Telerik.JustMock/Core/Internal/SlimReadWriteLock.cs @@ -1,18 +1,21 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace Telerik.JustMock.Core.Castle.Core.Internal +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal { using System.Threading; @@ -75,4 +78,4 @@ public bool IsWriteLockHeld get { return locker.IsWriteLockHeld; } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimUpgradeableReadLockHolder.cs b/Telerik.JustMock/Core/Internal/SlimUpgradeableReadLockHolder.cs similarity index 67% rename from Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimUpgradeableReadLockHolder.cs rename to Telerik.JustMock/Core/Internal/SlimUpgradeableReadLockHolder.cs index 946ae8cc..739fe66c 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.Core/Internal/SlimUpgradeableReadLockHolder.cs +++ b/Telerik.JustMock/Core/Internal/SlimUpgradeableReadLockHolder.cs @@ -1,18 +1,21 @@ -// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation -namespace Telerik.JustMock.Core.Castle.Core.Internal + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal { using System.Threading; @@ -80,4 +83,4 @@ public bool LockAcquired get { return lockAcquired; } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/Internal/SlimWriteLockHolder.cs b/Telerik.JustMock/Core/Internal/SlimWriteLockHolder.cs new file mode 100644 index 00000000..8713b2a5 --- /dev/null +++ b/Telerik.JustMock/Core/Internal/SlimWriteLockHolder.cs @@ -0,0 +1,52 @@ +/* + JustMock Lite + Copyright © 2023 Progress Software Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +namespace Telerik.JustMock.Core.Internal +{ + using System.Threading; + + internal class SlimWriteLockHolder : ILockHolder + { + private readonly ReaderWriterLockSlim locker; + + private bool lockAcquired; + + public SlimWriteLockHolder(ReaderWriterLockSlim locker, bool waitForLock) + { + this.locker = locker; + if(waitForLock) + { + locker.EnterWriteLock(); + lockAcquired = true; + return; + } + lockAcquired = locker.TryEnterWriteLock(0); + } + + public void Dispose() + { + if(!LockAcquired) return; + locker.ExitWriteLock(); + lockAcquired = false; + } + + public bool LockAcquired + { + get { return lockAcquired; } + } + } +} diff --git a/Telerik.JustMock/Core/MocksRepository.cs b/Telerik.JustMock/Core/MocksRepository.cs index 97f9b3ac..6f03bc96 100644 --- a/Telerik.JustMock/Core/MocksRepository.cs +++ b/Telerik.JustMock/Core/MocksRepository.cs @@ -142,7 +142,7 @@ static MocksRepository() }; foreach (var unmockableAttr in badApples.Where(t => t != null)) - AttributesToAvoidReplicating.Add(unmockableAttr); + Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(unmockableAttr); #endif #if !PORTABLE diff --git a/Telerik.JustMock/Core/TransparentProxy/ProxyInvocation.cs b/Telerik.JustMock/Core/TransparentProxy/ProxyInvocation.cs index 87dfebb2..a1e13e0e 100644 --- a/Telerik.JustMock/Core/TransparentProxy/ProxyInvocation.cs +++ b/Telerik.JustMock/Core/TransparentProxy/ProxyInvocation.cs @@ -117,7 +117,12 @@ public void SetArgumentValue(int index, object value) throw new NotSupportedException(); } - public Type TargetType + public IInvocationProceedInfo CaptureProceedInfo() + { + throw new NotSupportedException(); + } + + public Type TargetType { get { throw new NotSupportedException(); } } diff --git a/Telerik.JustMock/Telerik.JustMock.csproj b/Telerik.JustMock/Telerik.JustMock.csproj index b0395b0a..caabf301 100644 --- a/Telerik.JustMock/Telerik.JustMock.csproj +++ b/Telerik.JustMock/Telerik.JustMock.csproj @@ -10,7 +10,12 @@ false false - NO_EXCEPTION_SERIALIZATION;FEATURE_EMIT_CUSTOMMODIFIERS + NO_EXCEPTION_SERIALIZATION + Debug + AnyCPU + {0749EBC2-4E83-4960-BF28-1FF5C2DEB2B9} + Library + Properties $(NetCoreSupportedVersions);$(PreviewTargetFramework) @@ -55,35 +60,11 @@ MinimumRecommendedRules.ruleset - $(DefineConstants);FEATURE_REMOTING;FEATURE_APPDOMAIN;FEATURE_ASSEMBLYBUILDER_SAVE + $(DefineConstants);FEATURE_APPDOMAIN;FEATURE_ASSEMBLYBUILDER_SAVE $(DefineConstants);NETCORE;NO_APPDOMAIN_ISOLATION - - - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {0749EBC2-4E83-4960-BF28-1FF5C2DEB2B9} - Library - Properties - 512 - - - - - true - ..\Solution Items\snkey_lite.snk - - - - - @@ -173,7 +154,6 @@ TextTemplatingFileGenerator Args.Matching.cs - TextTemplatingFileGenerator IReturns.cs From ec22e7b6c9f80d1434ebbf2e043f417e1c5ba43f Mon Sep 17 00:00:00 2001 From: Ivo Stoilov Date: Wed, 13 Dec 2023 09:30:23 +0200 Subject: [PATCH 7/9] Fix public API namespace (#203) --- .../{Core => }/AttributesToAvoidReplicating.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename Telerik.JustMock/{Core => }/AttributesToAvoidReplicating.cs (79%) diff --git a/Telerik.JustMock/Core/AttributesToAvoidReplicating.cs b/Telerik.JustMock/AttributesToAvoidReplicating.cs similarity index 79% rename from Telerik.JustMock/Core/AttributesToAvoidReplicating.cs rename to Telerik.JustMock/AttributesToAvoidReplicating.cs index 7de242af..81ee5a9d 100644 --- a/Telerik.JustMock/Core/AttributesToAvoidReplicating.cs +++ b/Telerik.JustMock/AttributesToAvoidReplicating.cs @@ -17,7 +17,7 @@ limitations under the License. using System; -namespace Telerik.JustMock.Core +namespace Telerik.JustMock { /// /// A list of attributes that must not be replicated when building a proxy. JustMock @@ -26,16 +26,16 @@ namespace Telerik.JustMock.Core /// to this list that prevent the proxy from working correctly. /// #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public class AttributesToAvoidReplicating + public static class AttributesToAvoidReplicating { public static void Add(Type attribute) { - ProfilerInterceptor.GuardInternal(() => Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(attribute)); + Core.ProfilerInterceptor.GuardInternal(() => Core.Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(attribute)); } public static void Add() { - ProfilerInterceptor.GuardInternal(() => Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add()); + Core.ProfilerInterceptor.GuardInternal(() => Core.Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add()); } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member From e2974574095b1bb26a8537af6dd195ca0d3fcacf Mon Sep 17 00:00:00 2001 From: Ivo Stoilov Date: Fri, 15 Dec 2023 10:35:06 +0200 Subject: [PATCH 8/9] Update Ninject (#204) o closes #658 --- Telerik.JustMock/AutoMock/MockingContainer.cs | 34 +- .../Activation/Blocks/ActivationBlock.cs | 92 ++-- .../Activation/Blocks/IActivationBlock.cs | 41 +- .../Activation/Caching/ActivationCache.cs | 74 ++-- .../Ninject/Activation/Caching/Cache.cs | 55 ++- .../Caching/GarbageCollectionCachePruner.cs | 47 +- .../Activation/Caching/IActivationCache.cs | 25 +- .../Ninject/Activation/Caching/ICache.cs | 35 +- .../Activation/Caching/ICachePruner.cs | 35 +- .../Ninject/Activation/Caching/IPruneable.cs | 23 +- .../Caching/WeakReferenceEqualityComparer.cs | 30 +- .../AutoMock/Ninject/Activation/Context.cs | 263 +++++++---- .../AutoMock/Ninject/Activation/IContext.cs | 51 ++- .../AutoMock/Ninject/Activation/IPipeline.cs | 40 +- .../AutoMock/Ninject/Activation/IProvider.cs | 34 +- .../Ninject/Activation/IProvider{T}.cs | 14 +- .../AutoMock/Ninject/Activation/IRequest.cs | 55 ++- .../Ninject/Activation/InstanceReference.cs | 59 ++- .../AutoMock/Ninject/Activation/Pipeline.cs | 36 +- .../AutoMock/Ninject/Activation/Provider.cs | 31 +- .../Activation/Providers/CallbackProvider.cs | 54 ++- .../Activation/Providers/ConstantProvider.cs | 49 ++- .../Activation/Providers/StandardProvider.cs | 177 ++++---- .../AutoMock/Ninject/Activation/Request.cs | 161 ++++--- .../Strategies/ActivationCacheStrategy.cs | 40 +- .../Strategies/ActivationStrategy.cs | 43 +- .../Strategies/BindingActionStrategy.cs | 39 +- .../Strategies/DisposableStrategy.cs | 34 +- .../Strategies/IActivationStrategy.cs | 35 +- .../Strategies/InitializableStrategy.cs | 32 +- .../Strategies/MethodInjectionStrategy.cs | 41 +- .../Strategies/PropertyInjectionStrategy.cs | 97 ++-- .../Strategies/StartableStrategy.cs | 32 +- .../AutoMock/Ninject/ActivationException.cs | 65 +-- .../Ninject/Attributes/ConstraintAttribute.cs | 39 +- .../Ninject/Attributes/InjectAttribute.cs | 46 +- .../Ninject/Attributes/NamedAttribute.cs | 55 ++- .../Ninject/Attributes/OptionalAttribute.cs | 46 +- .../Ninject/Components/ComponentContainer.cs | 194 ++++---- .../Ninject/Components/IComponentContainer.cs | 54 ++- .../Ninject/Components/INinjectComponent.cs | 34 +- .../Ninject/Components/NinjectComponent.cs | 35 +- .../Ninject/GlobalKernelRegistration.cs | 75 ++-- .../Ninject/GlobalKernelRegistrationModule.cs | 16 +- .../Ninject/IHaveNinjectComponents.cs | 36 ++ .../AutoMock/Ninject/IHaveNinjectSettings.cs | 34 ++ .../AutoMock/Ninject/IInitializable.cs | 34 +- Telerik.JustMock/AutoMock/Ninject/IKernel.cs | 65 +-- .../AutoMock/Ninject/INinjectSettings.cs | 64 +-- .../AutoMock/Ninject/IStartable.cs | 34 +- .../Infrastructure/BaseWeakReference.cs | 60 --- .../Disposal/DisposableObject.cs | 67 +-- .../Disposal/IDisposableObject.cs | 34 +- .../Disposal/INotifyWhenDisposed.cs | 34 +- .../AutoMock/Ninject/Infrastructure/Ensure.cs | 61 ++- .../AutoMock/Ninject/Infrastructure/Future.cs | 67 --- .../IHaveBindingConfiguration.cs | 35 +- .../Ninject/Infrastructure/IHaveKernel.cs | 32 +- .../Introspection/ExceptionFormatter.cs | 56 ++- .../Introspection/FormatExtensions.cs | 111 +++-- .../Language/ExtensionsForAssembly.cs | 69 ++- .../ExtensionsForICustomAttributeProvider.cs | 51 ++- .../Language/ExtensionsForIEnumerable.cs | 73 ++- .../Language/ExtensionsForIEnumerableOfT.cs | 69 ++- .../Language/ExtensionsForMemberInfo.cs | 101 ++--- .../ExtensionsForTargetInvocationException.cs | 49 ++- .../Language/ExtensionsForType.cs | 16 +- .../Ninject/Infrastructure/Multimap.cs | 117 ++--- .../ReferenceEqualWeakReference.cs | 60 +-- .../Infrastructure/StandardScopeCallbacks.cs | 37 +- .../Threading/ReaderWriterLock.cs | 416 ------------------ .../Ninject/Injection/ConstructorInjector.cs | 33 +- .../Injection/DynamicMethodInjectorFactory.cs | 117 ++--- .../Ninject/Injection/IInjectorFactory.cs | 38 +- .../Ninject/Injection/MethodInjector.cs | 34 +- .../Ninject/Injection/PropertyInjector.cs | 34 +- .../Injection/ReflectionInjectorFactory.cs | 38 +- .../AutoMock/Ninject/KernelBase.cs | 306 ++++++------- .../Ninject/Modules/AssemblyNameRetriever.cs | 47 +- .../Modules/CompiledModuleLoaderPlugin.cs | 30 +- .../Ninject/Modules/IAssemblyNameRetriever.cs | 16 +- .../AutoMock/Ninject/Modules/IModuleLoader.cs | 42 +- .../Ninject/Modules/IModuleLoaderPlugin.cs | 42 +- .../Ninject/Modules/INinjectModule.cs | 36 +- .../AutoMock/Ninject/Modules/ModuleLoader.cs | 77 ++-- .../AutoMock/Ninject/Modules/NinjectModule.cs | 20 +- .../AutoMock/Ninject/NinjectSettings.cs | 111 +++-- .../Ninject/Parameters/ConstructorArgument.cs | 16 +- .../Parameters/IConstructorArgument.cs | 25 +- .../AutoMock/Ninject/Parameters/IParameter.cs | 36 +- .../Ninject/Parameters/IPropertyValue.cs | 14 +- .../AutoMock/Ninject/Parameters/Parameter.cs | 98 +++-- .../Ninject/Parameters/PropertyValue.cs | 51 ++- .../TypeMatchingConstructorArgument.cs | 144 ++++++ .../Parameters/WeakConstructorArgument.cs | 20 +- .../Ninject/Parameters/WeakPropertyValue.cs | 17 +- .../Ninject/Planning/Bindings/Binding.cs | 57 +-- .../Planning/Bindings/BindingBuilder.cs | 27 +- .../Bindings/BindingBuilder{T1,T2,T3,T4}.cs | 27 +- .../Bindings/BindingBuilder{T1,T2,T3}.cs | 29 +- .../Bindings/BindingBuilder{T1,T2}.cs | 29 +- .../Planning/Bindings/BindingBuilder{T1}.cs | 26 +- .../Planning/Bindings/BindingConfiguration.cs | 38 +- .../Bindings/BindingConfigurationBuilder.cs | 156 +++++-- .../Planning/Bindings/BindingMetadata.cs | 53 ++- .../Bindings/BindingPrecedenceComparer.cs | 67 +++ .../Planning/Bindings/BindingTarget.cs | 37 +- .../Ninject/Planning/Bindings/IBinding.cs | 37 +- .../Bindings/IBindingConfiguration.cs | 15 +- .../Bindings/IBindingConfigurationSyntax.cs | 37 ++ .../Planning/Bindings/IBindingMetadata.cs | 33 +- .../Bindings/IBindingPrecedenceComparer.cs | 34 ++ .../Planning/Bindings/IBindingSyntax.cs | 24 - .../Resolvers/DefaultValueBindingResolver.cs | 59 +-- .../Bindings/Resolvers/IBindingResolver.cs | 43 +- .../Resolvers/IMissingBindingResolver.cs | 49 ++- .../Resolvers/OpenGenericBindingResolver.cs | 48 +- .../Bindings/Resolvers/SelfBindingResolver.cs | 61 +-- .../Resolvers/StandardBindingResolver.cs | 44 +- .../ConstructorInjectionDirective.cs | 63 ++- .../Ninject/Planning/Directives/IDirective.cs | 36 +- .../Directives/MethodInjectionDirective.cs | 43 +- .../MethodInjectionDirectiveBase.cs | 72 +-- .../Directives/PropertyInjectionDirective.cs | 66 +-- .../AutoMock/Ninject/Planning/IPlan.cs | 54 ++- .../AutoMock/Ninject/Planning/IPlanner.cs | 41 +- .../AutoMock/Ninject/Planning/Plan.cs | 81 ++-- .../AutoMock/Ninject/Planning/Planner.cs | 37 +- .../ConstructorReflectionStrategy.cs | 91 ++-- .../Planning/Strategies/IPlanningStrategy.cs | 35 +- .../Strategies/MethodReflectionStrategy.cs | 76 ++-- .../Strategies/PropertyReflectionStrategy.cs | 76 ++-- .../Ninject/Planning/Targets/ITarget.cs | 41 +- .../Planning/Targets/ParameterTarget.cs | 70 +-- .../Planning/Targets/PropertyTarget.cs | 55 ++- .../Ninject/Planning/Targets/Target.cs | 133 +++--- .../Heuristics/IConstructorScorer.cs | 41 +- .../Heuristics/IInjectionHeuristic.cs | 38 +- .../Heuristics/SpecificConstructorSelector.cs | 19 +- .../Heuristics/StandardConstructorScorer.cs | 71 +-- .../Heuristics/StandardInjectionHeuristic.cs | 56 +-- .../AutoMock/Ninject/Selection/ISelector.cs | 47 +- .../AutoMock/Ninject/Selection/Selector.cs | 124 +++--- .../AutoMock/Ninject/StandardKernel.cs | 31 +- .../AutoMock/Ninject/Syntax/BindingRoot.cs | 66 ++- .../Syntax/IBindingInNamedWithOrOnSyntax.cs | 22 +- .../Ninject/Syntax/IBindingInSyntax.cs | 14 +- .../Ninject/Syntax/IBindingNamedSyntax.cs | 14 +- .../Syntax/IBindingNamedWithOrOnSyntax.cs | 14 +- .../Ninject/Syntax/IBindingOnSyntax.cs | 14 +- .../AutoMock/Ninject/Syntax/IBindingRoot.cs | 15 +- .../AutoMock/Ninject/Syntax/IBindingSyntax.cs | 14 +- .../Syntax/IBindingToSyntax{T1,T2,T3,T4}.cs | 28 +- .../Syntax/IBindingToSyntax{T1,T2,T3}.cs | 28 +- .../Ninject/Syntax/IBindingToSyntax{T1,T2}.cs | 28 +- .../Ninject/Syntax/IBindingToSyntax{T1}.cs | 25 +- .../IBindingWhenInNamedWithOrOnSyntax.cs | 14 +- .../Ninject/Syntax/IBindingWhenSyntax.cs | 31 +- .../Ninject/Syntax/IBindingWithOrOnSyntax.cs | 14 +- .../Ninject/Syntax/IBindingWithSyntax.cs | 62 ++- .../Syntax/IConstructorArgumentSyntax.cs | 12 +- .../AutoMock/Ninject/Syntax/IFluentSyntax.cs | 54 ++- .../Ninject/Syntax/IResolutionRoot.cs | 52 ++- .../Ninject/Syntax/ModuleLoadExtensions.cs | 44 +- .../Ninject/Syntax/ResolutionExtensions.cs | 140 ++++-- Telerik.JustMock/AutoMock/Ninject/VERSION | 1 + Telerik.JustMock/Telerik.JustMock.csproj | 18 +- 167 files changed, 5258 insertions(+), 3884 deletions(-) create mode 100644 Telerik.JustMock/AutoMock/Ninject/IHaveNinjectComponents.cs create mode 100644 Telerik.JustMock/AutoMock/Ninject/IHaveNinjectSettings.cs delete mode 100644 Telerik.JustMock/AutoMock/Ninject/Infrastructure/BaseWeakReference.cs delete mode 100644 Telerik.JustMock/AutoMock/Ninject/Infrastructure/Future.cs delete mode 100644 Telerik.JustMock/AutoMock/Ninject/Infrastructure/Threading/ReaderWriterLock.cs create mode 100644 Telerik.JustMock/AutoMock/Ninject/Parameters/TypeMatchingConstructorArgument.cs create mode 100644 Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingPrecedenceComparer.cs create mode 100644 Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfigurationSyntax.cs create mode 100644 Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingPrecedenceComparer.cs delete mode 100644 Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingSyntax.cs create mode 100644 Telerik.JustMock/AutoMock/Ninject/VERSION diff --git a/Telerik.JustMock/AutoMock/MockingContainer.cs b/Telerik.JustMock/AutoMock/MockingContainer.cs index f4b8f048..595f250b 100644 --- a/Telerik.JustMock/AutoMock/MockingContainer.cs +++ b/Telerik.JustMock/AutoMock/MockingContainer.cs @@ -54,23 +54,23 @@ public MockingContainer(AutoMockSettings settings = null) { } - /// - /// Implementation detail. - /// - protected override bool ShouldAddComponent(Type component, Type implementation) - { - if (implementation == typeof(SelfBindingResolver)) - { - return false; - } - - return base.ShouldAddComponent(component, implementation); - } - - /// - /// Implementation detail. - /// - protected override void AddComponents() + /// + /// Implementation detail. + /// + protected override bool ShouldAddComponent(Type component, Type implementation) + { + if (implementation == typeof(SelfBindingResolver)) + { + return false; + } + + return base.ShouldAddComponent(component, implementation); + } + + /// + /// Implementation detail. + /// + protected override void AddComponents() { base.AddComponents(); diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/ActivationBlock.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/ActivationBlock.cs index 3b109700..0bc6fe27 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/ActivationBlock.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/ActivationBlock.cs @@ -1,40 +1,41 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -using Telerik.JustMock.AutoMock.Ninject.Syntax; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Blocks { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Syntax; + /// /// A block used for deterministic disposal of activated instances. When the block is /// disposed, all instances activated via it will be deactivated. /// public class ActivationBlock : DisposableObject, IActivationBlock { - /// - /// Gets or sets the parent resolution root (usually the kernel). - /// - public IResolutionRoot Parent { get; private set; } - - /// - /// Occurs when the object is disposed. - /// - public event EventHandler Disposed; - /// /// Initializes a new instance of the class. /// @@ -42,25 +43,23 @@ public class ActivationBlock : DisposableObject, IActivationBlock public ActivationBlock(IResolutionRoot parent) { Ensure.ArgumentNotNull(parent, "parent"); - Parent = parent; + + this.Parent = parent; } /// - /// Releases resources held by the object. + /// Gets the parent resolution root (usually the kernel). /// - public override void Dispose(bool disposing) - { - lock (this) - { - if (disposing && !IsDisposed) - { - var evt = Disposed; - if (evt != null) evt(this, EventArgs.Empty); - Disposed = null; - } + public IResolutionRoot Parent { get; private set; } - base.Dispose(disposing); - } + /// + /// Injects the specified existing instance, without managing its lifecycle. + /// + /// The instance to inject. + /// The parameters to pass to the request. + public void Inject(object instance, params IParameter[] parameters) + { + this.Parent.Inject(instance, parameters); } /// @@ -71,6 +70,7 @@ public override void Dispose(bool disposing) public bool CanResolve(IRequest request) { Ensure.ArgumentNotNull(request, "request"); + return this.Parent.CanResolve(request); } @@ -85,6 +85,7 @@ public bool CanResolve(IRequest request) public bool CanResolve(IRequest request, bool ignoreImplicitBindings) { Ensure.ArgumentNotNull(request, "request"); + return this.Parent.CanResolve(request, ignoreImplicitBindings); } @@ -97,7 +98,8 @@ public bool CanResolve(IRequest request, bool ignoreImplicitBindings) public IEnumerable Resolve(IRequest request) { Ensure.ArgumentNotNull(request, "request"); - return Parent.Resolve(request); + + return this.Parent.Resolve(request); } /// @@ -113,6 +115,7 @@ public virtual IRequest CreateRequest(Type service, Func { Ensure.ArgumentNotNull(service, "service"); Ensure.ArgumentNotNull(parameters, "parameters"); + return new Request(service, constraint, parameters, () => this, isOptional, isUnique); } @@ -121,10 +124,9 @@ public virtual IRequest CreateRequest(Type service, Func /// /// The instance to release. /// if the instance was found and released; otherwise . - /// public bool Release(object instance) { - return Parent.Release(instance); + return this.Parent.Release(instance); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/IActivationBlock.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/IActivationBlock.cs index 7c229e91..6c09c50b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/IActivationBlock.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Blocks/IActivationBlock.cs @@ -1,23 +1,34 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; -using Telerik.JustMock.AutoMock.Ninject.Syntax; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Blocks { + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; + using Telerik.JustMock.AutoMock.Ninject.Syntax; + /// /// A block used for deterministic disposal of activated instances. When the block is /// disposed, all instances activated via it will be deactivated. /// - public interface IActivationBlock : IResolutionRoot, INotifyWhenDisposed { } + public interface IActivationBlock : IResolutionRoot, INotifyWhenDisposed + { + } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ActivationCache.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ActivationCache.cs index b4da23b1..22ad78d6 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ActivationCache.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ActivationCache.cs @@ -1,8 +1,28 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { - using System; using System.Collections.Generic; - using System.Linq; + using Telerik.JustMock.AutoMock.Ninject.Components; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; @@ -11,17 +31,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching /// public class ActivationCache : NinjectComponent, IActivationCache, IPruneable { -#if SILVERLIGHT_20 || SILVERLIGHT_30 || WINDOWS_PHONE || NETCF || MONO - /// - /// The objects that were activated as reference equal weak references. - /// - private readonly IDictionary activatedObjects = new Dictionary(new WeakReferenceEqualityComparer()); - - /// - /// The objects that were activated as reference equal weak references. - /// - private readonly IDictionary deactivatedObjects = new Dictionary(new WeakReferenceEqualityComparer()); -#else /// /// The objects that were activated as reference equal weak references. /// @@ -31,7 +40,6 @@ public class ActivationCache : NinjectComponent, IActivationCache, IPruneable /// The objects that were activated as reference equal weak references. /// private readonly HashSet deactivatedObjects = new HashSet(new WeakReferenceEqualityComparer()); -#endif /// /// Initializes a new instance of the class. @@ -39,9 +47,10 @@ public class ActivationCache : NinjectComponent, IActivationCache, IPruneable /// The cache pruner. public ActivationCache(ICachePruner cachePruner) { + Ensure.ArgumentNotNull(cachePruner, "cachePruner"); cachePruner.Start(this); } - + /// /// Gets the activated object count. /// @@ -65,7 +74,7 @@ public int DeactivatedObjectCount return this.deactivatedObjects.Count; } } - + /// /// Clears the cache. /// @@ -90,11 +99,7 @@ public void AddActivatedInstance(object instance) { lock (this.activatedObjects) { -#if SILVERLIGHT_20 || SILVERLIGHT_30 || WINDOWS_PHONE || NETCF || MONO - this.activatedObjects.Add(new ReferenceEqualWeakReference(instance), true); -#else this.activatedObjects.Add(new ReferenceEqualWeakReference(instance)); -#endif } } @@ -106,11 +111,7 @@ public void AddDeactivatedInstance(object instance) { lock (this.deactivatedObjects) { -#if SILVERLIGHT_20 || SILVERLIGHT_30 || WINDOWS_PHONE || NETCF || MONO - this.deactivatedObjects.Add(new ReferenceEqualWeakReference(instance), true); -#else this.deactivatedObjects.Add(new ReferenceEqualWeakReference(instance)); -#endif } } @@ -123,11 +124,7 @@ public void AddDeactivatedInstance(object instance) /// public bool IsActivated(object instance) { -#if SILVERLIGHT_20 || SILVERLIGHT_30 || WINDOWS_PHONE || NETCF || MONO - return this.activatedObjects.ContainsKey(instance); -#else return this.activatedObjects.Contains(instance); -#endif } /// @@ -139,11 +136,7 @@ public bool IsActivated(object instance) /// public bool IsDeactivated(object instance) { -#if SILVERLIGHT_20 || SILVERLIGHT_30 || WINDOWS_PHONE || NETCF || MONO - return this.deactivatedObjects.ContainsKey(instance); -#else return this.deactivatedObjects.Contains(instance); -#endif } /// @@ -162,20 +155,6 @@ public void Prune() } } -#if SILVERLIGHT_20 || SILVERLIGHT_30 || WINDOWS_PHONE || NETCF || MONO - /// - /// Removes all dead objects. - /// - /// The objects collection to be freed of dead objects. - private static void RemoveDeadObjects(IDictionary objects) - { - var deadObjects = objects.Where(entry => !((ReferenceEqualWeakReference)entry.Key).IsAlive).ToList(); - foreach (var deadObject in deadObjects) - { - objects.Remove(deadObject.Key); - } - } -#else /// /// Removes all dead objects. /// @@ -184,6 +163,5 @@ private static void RemoveDeadObjects(HashSet objects) { objects.RemoveWhere(reference => !((ReferenceEqualWeakReference)reference).IsAlive); } -#endif } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/Cache.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/Cache.cs index 25a0857c..c2f603a5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/Cache.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/Cache.cs @@ -1,12 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { @@ -60,10 +71,10 @@ public int Count /// /// Releases resources held by the object. /// - /// + /// True if called manually, otherwise by GC. public override void Dispose(bool disposing) { - if (disposing && !IsDisposed) + if (disposing && !this.IsDisposed) { this.Clear(); } @@ -89,8 +100,7 @@ public void Remember(IContext context, InstanceReference reference) if (!this.entries.ContainsKey(weakScopeReference)) { this.entries[weakScopeReference] = new Multimap(); - var notifyScope = scope as INotifyWhenDisposed; - if (notifyScope != null) + if (scope is INotifyWhenDisposed notifyScope) { notifyScope.Disposed += (o, e) => this.Clear(weakScopeReference); } @@ -108,6 +118,7 @@ public void Remember(IContext context, InstanceReference reference) public object TryGet(IContext context) { Ensure.ArgumentNotNull(context, "context"); + var scope = context.GetScope(); if (scope == null) { @@ -116,8 +127,7 @@ public object TryGet(IContext context) lock (this.entries) { - Multimap bindings; - if (!this.entries.TryGetValue(scope, out bindings)) + if (!this.entries.TryGetValue(scope, out Multimap bindings)) { return null; } @@ -149,7 +159,7 @@ public object TryGet(IContext context) /// if the instance was found and released; otherwise . public bool Release(object instance) { - lock(this.entries) + lock (this.entries) { var instanceFound = false; foreach (var bindingEntry in this.entries.Values.SelectMany(bindingEntries => bindingEntries.Values).ToList()) @@ -177,8 +187,8 @@ public void Prune() var disposedScopes = this.entries.Where(scope => !((ReferenceEqualWeakReference)scope.Key).IsAlive).Select(scope => scope).ToList(); foreach (var disposedScope in disposedScopes) { - this.Forget(GetAllBindingEntries(disposedScope.Value)); this.entries.Remove(disposedScope.Key); + this.Forget(GetAllBindingEntries(disposedScope.Value)); } } } @@ -192,11 +202,10 @@ public void Clear(object scope) { lock (this.entries) { - Multimap bindings; - if (this.entries.TryGetValue(scope, out bindings)) + if (this.entries.TryGetValue(scope, out Multimap bindings)) { - this.Forget(GetAllBindingEntries(bindings)); this.entries.Remove(scope); + this.Forget(GetAllBindingEntries(bindings)); } } } @@ -214,13 +223,13 @@ public void Clear() } /// - /// Gets all entries for a binding withing the selected scope. + /// Gets all entries for a binding within the selected scope. /// /// The bindings. /// All bindings of a binding. - private static IEnumerable GetAllBindingEntries(IEnumerable>> bindings) + private static IEnumerable GetAllBindingEntries(Multimap bindings) { - return bindings.SelectMany(bindingEntries => bindingEntries.Value); + return bindings.Values.SelectMany(bindingEntries => bindingEntries); } /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/GarbageCollectionCachePruner.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/GarbageCollectionCachePruner.cs index 60e4a588..a4f3b748 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/GarbageCollectionCachePruner.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/GarbageCollectionCachePruner.cs @@ -1,18 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { using System; using System.Collections.Generic; using System.Threading; + using Telerik.JustMock.AutoMock.Ninject.Components; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; @@ -27,25 +39,29 @@ public class GarbageCollectionCachePruner : NinjectComponent, ICachePruner /// indicator for if GC has been run. /// private readonly WeakReference indicator = new WeakReference(new object()); - + /// /// The caches that are being pruned. /// private readonly List caches = new List(); /// - /// The timer used to trigger the cache pruning + /// The timer used to trigger the cache pruning. /// private Timer timer; + /// + /// The flag to indicate whether the cache pruning is stopped or not. + /// private bool stop; /// /// Releases resources held by the object. /// + /// True if called manually, otherwise by GC. public override void Dispose(bool disposing) { - if (disposing && !IsDisposed && this.timer != null) + if (disposing && !this.IsDisposed && this.timer != null) { this.Stop(); } @@ -80,13 +96,8 @@ public void Stop() using (var signal = new ManualResetEvent(false)) { -#if !NETCF this.timer.Dispose(signal); signal.WaitOne(); -#else - this.timer.Dispose(); -#endif - this.timer = null; this.caches.Clear(); } @@ -120,7 +131,7 @@ private void PruneCacheIfGarbageCollectorHasRun(object state) private int GetTimeoutInMilliseconds() { - TimeSpan interval = Settings.CachePruningInterval; + var interval = this.Settings.CachePruningInterval; return interval == TimeSpan.MaxValue ? -1 : (int)interval.TotalMilliseconds; } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IActivationCache.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IActivationCache.cs index 728363ad..c1729b5e 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IActivationCache.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IActivationCache.cs @@ -1,4 +1,25 @@ -namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { using Telerik.JustMock.AutoMock.Ninject.Components; @@ -23,7 +44,7 @@ public interface IActivationCache : INinjectComponent /// /// The instance to be added. void AddDeactivatedInstance(object instance); - + /// /// Determines whether the specified instance is activated. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICache.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICache.cs index 2f74f6d0..83c0c24d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICache.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICache.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Tracks instances for re-use in certain scopes. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICachePruner.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICachePruner.cs index a3be302d..7d6b1349 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICachePruner.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/ICachePruner.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Prunes instances from an based on environmental information. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IPruneable.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IPruneable.cs index dc5e2fd0..df233b8f 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IPruneable.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/IPruneable.cs @@ -1,7 +1,28 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { /// - /// An object that is prunealble. + /// An object that is pruneable. /// public interface IPruneable { diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/WeakReferenceEqualityComparer.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/WeakReferenceEqualityComparer.cs index 865e002f..13e79874 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/WeakReferenceEqualityComparer.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Caching/WeakReferenceEqualityComparer.cs @@ -1,3 +1,24 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching { using System.Collections.Generic; @@ -11,7 +32,7 @@ namespace Telerik.JustMock.AutoMock.Ninject.Activation.Caching public class WeakReferenceEqualityComparer : IEqualityComparer { /// - /// Returns if the specifed objects are equal. + /// Returns if the specified objects are equal. /// /// The first object. /// The second object. @@ -29,12 +50,7 @@ public class WeakReferenceEqualityComparer : IEqualityComparer public int GetHashCode(object obj) { var weakReference = obj as ReferenceEqualWeakReference; - return weakReference != null ? weakReference.GetHashCode() : -#if !NETCF - RuntimeHelpers.GetHashCode(obj); -#else - obj.GetHashCode(); -#endif + return weakReference != null ? weakReference.GetHashCode() : RuntimeHelpers.GetHashCode(obj); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Context.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Context.cs index 7fe83c69..790c2099 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Context.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Context.cs @@ -1,45 +1,91 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Activation.Caching; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Activation.Caching; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + /// /// Contains information about the activation of a single instance. /// public class Context : IContext { - private WeakReference cachedScope; + private object cachedScope; + + /// + /// Initializes a new instance of the class. + /// + /// The kernel managing the resolution. + /// The context's request. + /// The context's binding. + /// The cache component. + /// The planner component. + /// The pipeline component. + public Context(IKernel kernel, IRequest request, IBinding binding, ICache cache, IPlanner planner, IPipeline pipeline) + { + Ensure.ArgumentNotNull(kernel, "kernel"); + Ensure.ArgumentNotNull(request, "request"); + Ensure.ArgumentNotNull(binding, "binding"); + Ensure.ArgumentNotNull(cache, "cache"); + Ensure.ArgumentNotNull(planner, "planner"); + Ensure.ArgumentNotNull(pipeline, "pipeline"); + + this.Kernel = kernel; + this.Request = request; + this.Binding = binding; + this.Parameters = request.Parameters.Union(binding.Parameters).ToList(); + + this.Cache = cache; + this.Planner = planner; + this.Pipeline = pipeline; + + if (binding.Service.IsGenericTypeDefinition) + { + this.HasInferredGenericArguments = true; + this.GenericArguments = request.Service.GenericTypeArguments; + } + } /// - /// Gets the kernel that is driving the activation. + /// Gets or sets the kernel that is driving the activation. /// public IKernel Kernel { get; set; } /// - /// Gets the request. + /// Gets or sets the request. /// public IRequest Request { get; set; } /// - /// Gets the binding. + /// Gets or sets the binding. /// public IBinding Binding { get; set; } @@ -49,7 +95,7 @@ public class Context : IContext public IPlan Plan { get; set; } /// - /// Gets the parameters that were passed to manipulate the activation process. + /// Gets or sets the parameters that were passed to manipulate the activation process. /// public ICollection Parameters { get; set; } @@ -64,67 +110,27 @@ public class Context : IContext public bool HasInferredGenericArguments { get; private set; } /// - /// Gets or sets the cache component. + /// Gets the cache component. /// public ICache Cache { get; private set; } /// - /// Gets or sets the planner component. + /// Gets the planner component. /// public IPlanner Planner { get; private set; } /// - /// Gets or sets the pipeline component. + /// Gets the pipeline component. /// public IPipeline Pipeline { get; private set; } - /// - /// Initializes a new instance of the class. - /// - /// The kernel managing the resolution. - /// The context's request. - /// The context's binding. - /// The cache component. - /// The planner component. - /// The pipeline component. - public Context(IKernel kernel, IRequest request, IBinding binding, ICache cache, IPlanner planner, IPipeline pipeline) - { - Ensure.ArgumentNotNull(kernel, "kernel"); - Ensure.ArgumentNotNull(request, "request"); - Ensure.ArgumentNotNull(binding, "binding"); - Ensure.ArgumentNotNull(cache, "cache"); - Ensure.ArgumentNotNull(planner, "planner"); - Ensure.ArgumentNotNull(pipeline, "pipeline"); - - Kernel = kernel; - Request = request; - Binding = binding; - Parameters = request.Parameters.Union(binding.Parameters).ToList(); - - Cache = cache; - Planner = planner; - Pipeline = pipeline; - - if (binding.Service.IsGenericTypeDefinition) - { - HasInferredGenericArguments = true; - GenericArguments = request.Service.GetGenericArguments(); - } - } - /// /// Gets the scope for the context that "owns" the instance activated therein. /// /// The object that acts as the scope. public object GetScope() { - if (this.cachedScope == null) - { - var scope = this.Request.GetScope() ?? this.Binding.GetScope(this); - this.cachedScope = new WeakReference(scope); - } - - return this.cachedScope.Target; + return this.cachedScope ?? this.Request.GetScope() ?? this.Binding.GetScope(this); } /// @@ -133,7 +139,7 @@ public object GetScope() /// The provider that should be used. public IProvider GetProvider() { - return Binding.GetProvider(this); + return this.Binding.GetProvider(this); } /// @@ -142,47 +148,112 @@ public IProvider GetProvider() /// The resolved instance. public object Resolve() { - lock (Binding) + if (this.Request.ActiveBindings.Contains(this.Binding) && + this.IsCyclical(this.Request.ParentContext)) + { + throw new ActivationException(ExceptionFormatter.CyclicalDependenciesDetected(this)); + } + + try + { + this.cachedScope = this.Request.GetScope() ?? this.Binding.GetScope(this); + + if (this.cachedScope != null) + { + lock (this.cachedScope) + { + return this.ResolveInternal(this.cachedScope); + } + } + else + { + return this.ResolveInternal(null); + } + } + finally { - if (Request.ActiveBindings.Contains(Binding)) - throw new ActivationException(ExceptionFormatter.CyclicalDependenciesDetected(this)); + this.cachedScope = null; + } + } - var cachedInstance = Cache.TryGet(this); + private object ResolveInternal(object scope) + { + var cachedInstance = this.Cache.TryGet(this); - if (cachedInstance != null) - return cachedInstance; + if (cachedInstance != null) + { + return cachedInstance; + } - Request.ActiveBindings.Push(Binding); + this.Request.ActiveBindings.Push(this.Binding); - var reference = new InstanceReference { Instance = GetProvider().Create(this) }; + var reference = new InstanceReference { Instance = this.GetProvider().Create(this) }; - Request.ActiveBindings.Pop(); + this.Request.ActiveBindings.Pop(); - if (reference.Instance == null) + if (reference.Instance == null) + { + if (!this.Kernel.Settings.AllowNullInjection) { - if (!this.Kernel.Settings.AllowNullInjection) - { - throw new ActivationException(ExceptionFormatter.ProviderReturnedNull(this)); - } + throw new ActivationException(ExceptionFormatter.ProviderReturnedNull(this)); + } - if (this.Plan == null) - { - this.Plan = this.Planner.GetPlan(this.Request.Service); - } + if (this.Plan == null) + { + this.Plan = this.Planner.GetPlan(this.Request.Service); + } + + return null; + } - return null; + if (scope != null) + { + this.Cache.Remember(this, reference); + } + + if (this.Plan == null) + { + this.Plan = this.Planner.GetPlan(reference.Instance.GetType()); + } + + try + { + this.Pipeline.Activate(this, reference); + } + catch (ActivationException) + { + if (scope != null) + { + this.Cache.Release(reference.Instance); } - if (GetScope() != null) - Cache.Remember(this, reference); + throw; + } + + return reference.Instance; + } - if (Plan == null) - Plan = Planner.GetPlan(reference.Instance.GetType()); + private bool IsCyclical(IContext targetContext) + { + if (targetContext == null) + { + return false; + } - Pipeline.Activate(this, reference); + if (targetContext.Request.Service == this.Request.Service) + { + if ((this.Request.Target is ParameterTarget && targetContext.Request.Target is ParameterTarget) || targetContext.GetScope() != this.GetScope() || this.GetScope() == null) + { + return true; + } + } - return reference.Instance; + if (this.IsCyclical(targetContext.Request.ParentContext)) + { + return true; } + + return false; } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/IContext.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/IContext.cs index e8d4a22c..e3577d3f 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/IContext.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/IContext.cs @@ -1,22 +1,34 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Activation.Caching; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Contains information about the activation of a single instance. /// @@ -42,6 +54,11 @@ public interface IContext /// IPlan Plan { get; set; } + /// + /// Gets the cache component. + /// + ICache Cache { get; } + /// /// Gets the parameters that were passed to manipulate the activation process. /// @@ -75,4 +92,4 @@ public interface IContext /// The resolved instance. object Resolve(); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/IPipeline.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/IPipeline.cs index 7205b292..c6f21dfe 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/IPipeline.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/IPipeline.cs @@ -1,21 +1,31 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation.Strategies; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Activation.Strategies; + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Drives the activation (injection, etc.) of an instance. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider.cs index b553fe3a..64dd4d5c 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider.cs @@ -1,18 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System; + /// /// Creates instances of services. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider{T}.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider{T}.cs index 4eb8ab7b..e4353729 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider{T}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/IProvider{T}.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { @@ -26,6 +26,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Activation /// /// The type provides by this implementation. public interface IProvider : IProvider - { + { } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/IRequest.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/IRequest.cs index eaeebfbf..bde0e574 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/IRequest.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/IRequest.cs @@ -1,23 +1,33 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -using Telerik.JustMock.AutoMock.Ninject.Syntax; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + /// /// Describes the request for a service resolution. /// @@ -64,15 +74,22 @@ public interface IRequest int Depth { get; } /// - /// Gets or sets value indicating whether the request is optional. + /// Gets or sets a value indicating whether the request is optional. /// bool IsOptional { get; set; } /// - /// Gets or sets value indicating whether the request should return a unique result. + /// Gets or sets a value indicating whether the request should return a unique result. /// bool IsUnique { get; set; } + /// + /// Gets or sets a value indicating whether the request should force to return a unique value even if the request is optional. + /// If this value is set true the request will throw an ActivationException if there are multiple satisfying bindings rather + /// than returning null for the request is optional. For none optional requests this parameter does not change anything. + /// + bool ForceUnique { get; set; } + /// /// Determines whether the specified binding satisfies the constraint defined on this request. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/InstanceReference.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/InstanceReference.cs index a94cfec9..4a732533 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/InstanceReference.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/InstanceReference.cs @@ -1,22 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System; + using System.Security; + /// /// Holds an instance during activation or after it has been cached. /// @@ -32,9 +39,17 @@ public class InstanceReference /// /// The type in question. /// if the instance is of the specified type, otherwise . + [SecuritySafeCritical] public bool Is() { - return Instance is T; +#if !NO_REMOTING + if (System.Runtime.Remoting.RemotingServices.IsTransparentProxy(this.Instance) + && System.Runtime.Remoting.RemotingServices.GetRealProxy(this.Instance).GetType().Name == "RemotingProxy") + { + return typeof(T).IsAssignableFrom(this.Instance.GetType()); + } +#endif + return this.Instance is T; } /// @@ -44,7 +59,7 @@ public bool Is() /// The instance. public T As() { - return (T)Instance; + return (T)this.Instance; } /// @@ -54,8 +69,10 @@ public T As() /// The action to execute. public void IfInstanceIs(Action action) { - if (Instance is T) - action((T)Instance); + if (this.Is()) + { + action((T)this.Instance); + } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Pipeline.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Pipeline.cs index fde8a8ae..13ca8a10 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Pipeline.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Pipeline.cs @@ -1,17 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { using System.Collections.Generic; using System.Linq; + using Telerik.JustMock.AutoMock.Ninject.Activation.Caching; using Telerik.JustMock.AutoMock.Ninject.Activation.Strategies; using Telerik.JustMock.AutoMock.Ninject.Components; @@ -36,6 +48,8 @@ public class Pipeline : NinjectComponent, IPipeline public Pipeline(IEnumerable strategies, IActivationCache activationCache) { Ensure.ArgumentNotNull(strategies, "strategies"); + Ensure.ArgumentNotNull(activationCache, "activationCache"); + this.Strategies = strategies.ToList(); this.activationCache = activationCache; } @@ -53,6 +67,8 @@ public Pipeline(IEnumerable strategies, IActivationCache ac public void Activate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); + Ensure.ArgumentNotNull(reference, "reference"); + if (!this.activationCache.IsActivated(reference.Instance)) { this.Strategies.Map(s => s.Activate(context, reference)); @@ -67,6 +83,8 @@ public void Activate(IContext context, InstanceReference reference) public void Deactivate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); + Ensure.ArgumentNotNull(reference, "reference"); + if (!this.activationCache.IsDeactivated(reference.Instance)) { this.Strategies.Map(s => s.Deactivate(context, reference)); diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Provider.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Provider.cs index a67889a1..6e61ac36 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Provider.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Provider.cs @@ -1,16 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { using System; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; /// @@ -35,6 +47,7 @@ public virtual Type Type public object Create(IContext context) { Ensure.ArgumentNotNull(context, "context"); + return this.CreateInstance(context); } diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/CallbackProvider.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/CallbackProvider.cs index 58cba4de..7b022b11 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/CallbackProvider.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/CallbackProvider.cs @@ -1,19 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Providers { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + /// /// A provider that delegates to a callback method to create instances. /// @@ -21,20 +32,21 @@ namespace Telerik.JustMock.AutoMock.Ninject.Activation.Providers public class CallbackProvider : Provider { /// - /// Gets the callback method used by the provider. - /// - public Func Method { get; private set; } - - /// - /// Initializes a new instance of the CallbackProvider<T> class. + /// Initializes a new instance of the class. /// /// The callback method that will be called to create instances. public CallbackProvider(Func method) { Ensure.ArgumentNotNull(method, "method"); - Method = method; + + this.Method = method; } + /// + /// Gets the callback method used by the provider. + /// + public Func Method { get; private set; } + /// /// Invokes the callback method to create an instance. /// @@ -42,7 +54,7 @@ public CallbackProvider(Func method) /// The created instance. protected override T CreateInstance(IContext context) { - return Method(context); + return this.Method(context); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/ConstantProvider.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/ConstantProvider.cs index 908a4ebf..ff6a4ec6 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/ConstantProvider.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/ConstantProvider.cs @@ -1,16 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Providers { @@ -21,19 +28,19 @@ namespace Telerik.JustMock.AutoMock.Ninject.Activation.Providers public class ConstantProvider : Provider { /// - /// Gets the value that the provider will return. - /// - public T Value { get; private set; } - - /// - /// Initializes a new instance of the ConstantProvider<T> class. + /// Initializes a new instance of the class. /// /// The value that the provider should return. public ConstantProvider(T value) { - Value = value; + this.Value = value; } + /// + /// Gets the value that the provider will return. + /// + public T Value { get; private set; } + /// /// Creates an instance within the specified context. /// @@ -41,7 +48,7 @@ public ConstantProvider(T value) /// The constant value this provider returns. protected override T CreateInstance(IContext context) { - return Value; + return this.Value; } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/StandardProvider.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/StandardProvider.cs index 90179d26..c5f963e3 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/StandardProvider.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Providers/StandardProvider.cs @@ -1,67 +1,103 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -using Telerik.JustMock.AutoMock.Ninject.Selection; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Providers { + using System; + using System.Linq; using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + using Telerik.JustMock.AutoMock.Ninject.Selection; using Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics; - using Telerik.JustMock.Core; + using Telerik.JustMock.Core; /// /// The standard provider for types, which activates instances via a . /// public class StandardProvider : IProvider { + /// + /// Initializes a new instance of the class. + /// + /// The type (or prototype) of instances the provider creates. + /// The planner component. + /// The constructor scorer component. + public StandardProvider(Type type, IPlanner planner, IConstructorScorer constructorScorer) + { + Ensure.ArgumentNotNull(type, "type"); + Ensure.ArgumentNotNull(planner, "planner"); + Ensure.ArgumentNotNull(constructorScorer, "constructorScorer"); + + this.Type = type; + this.Planner = planner; + this.ConstructorScorer = constructorScorer; + } + /// /// Gets the type (or prototype) of instances the provider creates. /// public Type Type { get; private set; } /// - /// Gets or sets the planner component. + /// Gets the planner component. /// public IPlanner Planner { get; private set; } /// - /// Gets or sets the selector component. + /// Gets the constructor scorer component. /// public IConstructorScorer ConstructorScorer { get; private set; } /// - /// Initializes a new instance of the class. + /// Gets a callback that creates an instance of the + /// for the specified type. /// - /// The type (or prototype) of instances the provider creates. - /// The planner component. - /// The constructor scorer component. - public StandardProvider(Type type, IPlanner planner, IConstructorScorer constructorScorer - ) + /// The prototype the provider instance will create. + /// The created callback. + public static Func GetCreationCallback(Type prototype) { - Ensure.ArgumentNotNull(type, "type"); - Ensure.ArgumentNotNull(planner, "planner"); - Ensure.ArgumentNotNull(constructorScorer, "constructorScorer"); + Ensure.ArgumentNotNull(prototype, "prototype"); - Type = type; - Planner = planner; - ConstructorScorer = constructorScorer; + return ctx => new StandardProvider(prototype, ctx.Kernel.Components.Get(), ctx.Kernel.Components.Get().ConstructorScorer); + } + + /// + /// Gets a callback that creates an instance of the + /// for the specified type and constructor. + /// + /// The prototype the provider instance will create. + /// The constructor. + /// The created callback. + public static Func GetCreationCallback(Type prototype, ConstructorInfo constructor) + { + Ensure.ArgumentNotNull(prototype, "prototype"); + + return ctx => new StandardProvider(prototype, ctx.Kernel.Components.Get(), new SpecificConstructorSelector(constructor)); } /// @@ -78,25 +114,18 @@ public virtual object Create(IContext context) context.Plan = this.Planner.GetPlan(this.GetImplementationType(context.Request.Service)); } - if (!context.Plan.Has()) - { - throw new ActivationException(ExceptionFormatter.NoConstructorsAvailable(context)); - } + var directive = this.DetermineConstructorInjectionDirective(context); + + var arguments = directive.Targets.Select(target => this.GetValue(context, target)).ToArray(); - var directives = context.Plan.GetAll(); - var bestDirectives = directives - .GroupBy(option => this.ConstructorScorer.Score(context, option)) - .OrderByDescending(g => g.Key) - .First(); - if (bestDirectives.Skip(1).Any()) + var cachedInstance = context.Cache.TryGet(context); + + if (cachedInstance != null) { - throw new ActivationException(ExceptionFormatter.ConstructorsAmbiguous(context, bestDirectives)); + return cachedInstance; } - var directive = bestDirectives.Single(); - var arguments = directive.Targets.Select(target => this.GetValue(context, target)).ToArray(); - var injector = directive.Injector; - return ProfilerInterceptor.GuardExternal(() => injector(arguments)); + return ProfilerInterceptor.GuardExternal(() => directive.Injector(arguments)); } /// @@ -112,7 +141,7 @@ public object GetValue(IContext context, ITarget target) var parameter = context .Parameters.OfType() - .Where(p => p.AppliesToTarget(context, target)).SingleOrDefault(); + .SingleOrDefault(p => p.AppliesToTarget(context, target)); return parameter != null ? parameter.GetValue(context, target) : target.ResolveWithin(context); } @@ -125,32 +154,30 @@ public object GetValue(IContext context, ITarget target) public Type GetImplementationType(Type service) { Ensure.ArgumentNotNull(service, "service"); - return Type.ContainsGenericParameters ? Type.MakeGenericType(service.GetGenericArguments()) : Type; - } - /// - /// Gets a callback that creates an instance of the - /// for the specified type. - /// - /// The prototype the provider instance will create. - /// The created callback. - public static Func GetCreationCallback(Type prototype) - { - Ensure.ArgumentNotNull(prototype, "prototype"); - return ctx => new StandardProvider(prototype, ctx.Kernel.Components.Get(), ctx.Kernel.Components.Get().ConstructorScorer); + return this.Type.ContainsGenericParameters ? this.Type.MakeGenericType(service.GetGenericArguments()) : this.Type; } - /// - /// Gets a callback that creates an instance of the - /// for the specified type and constructor. - /// - /// The prototype the provider instance will create. - /// The constructor. - /// The created callback. - public static Func GetCreationCallback(Type prototype, ConstructorInfo constructor) + private ConstructorInjectionDirective DetermineConstructorInjectionDirective(IContext context) { - Ensure.ArgumentNotNull(prototype, "prototype"); - return ctx => new StandardProvider(prototype, ctx.Kernel.Components.Get(), new SpecificConstructorSelector(constructor)); + var directives = context.Plan.ConstructorInjectionDirectives; + if (directives.Count == 1) + { + return directives[0]; + } + + var bestDirectives = + directives + .GroupBy(option => this.ConstructorScorer.Score(context, option)) + .OrderByDescending(g => g.Key) + .FirstOrDefault(); + if (bestDirectives == null) + { + throw new ActivationException(ExceptionFormatter.NoConstructorsAvailable(context)); + } + + return bestDirectives.SingleOrThrowException( + () => new ActivationException(ExceptionFormatter.ConstructorsAmbiguous(context, bestDirectives))); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Request.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Request.cs index 0330c786..0ab68685 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Request.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Request.cs @@ -1,29 +1,82 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation { + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + /// /// Describes the request for a service resolution. /// public class Request : IRequest { + /// + /// Initializes a new instance of the class. + /// + /// The service that was requested. + /// The constraint that will be applied to filter the bindings used for the request. + /// The parameters that affect the resolution. + /// The scope callback, if an external scope was specified. + /// True if the request is optional; otherwise, false. + /// True if the request should return a unique result; otherwise, false. + public Request(Type service, Func constraint, IEnumerable parameters, Func scopeCallback, bool isOptional, bool isUnique) + { + this.Service = service; + this.Constraint = constraint; + this.Parameters = parameters.ToList(); + this.ScopeCallback = scopeCallback; + this.ActiveBindings = new Stack(); + this.Depth = 0; + this.IsOptional = isOptional; + this.IsUnique = isUnique; + } + + /// + /// Initializes a new instance of the class. + /// + /// The parent context. + /// The service that was requested. + /// The target that will receive the injection. + /// The scope callback, if an external scope was specified. + public Request(IContext parentContext, Type service, ITarget target, Func scopeCallback) + { + this.ParentContext = parentContext; + this.ParentRequest = parentContext.Request; + this.Service = service; + this.Target = target; + this.Constraint = target.Constraint; + this.IsOptional = target.IsOptional; + this.Parameters = parentContext.Parameters.Where(p => p.ShouldInherit).ToList(); + this.ScopeCallback = scopeCallback; + this.ActiveBindings = new Stack(this.ParentRequest.ActiveBindings); + this.Depth = this.ParentRequest.Depth + 1; + } + /// /// Gets the service that was requested. /// @@ -65,12 +118,12 @@ public class Request : IRequest public int Depth { get; private set; } /// - /// Gets or sets value indicating whether the request is optional. + /// Gets or sets a value indicating whether the request is optional. /// public bool IsOptional { get; set; } /// - /// Gets or sets value indicating whether the request is for a single service. + /// Gets or sets a value indicating whether the request is for a single service. /// public bool IsUnique { @@ -78,58 +131,19 @@ public bool IsUnique } /// - /// Gets the callback that resolves the scope for the request, if an external scope was provided. + /// Gets or sets a value indicating whether the request should force to return a unique value even if the request is optional. + /// If this value is set true the request will throw an ActivationException if there are multiple satisfying bindings rather + /// than returning null for the request is optional. For none optional requests this parameter does not change anything. /// - public Func ScopeCallback { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - /// The service that was requested. - /// The constraint that will be applied to filter the bindings used for the request. - /// The parameters that affect the resolution. - /// The scope callback, if an external scope was specified. - /// True if the request is optional; otherwise, false. - /// True if the request should return a unique result; otherwise, false. - public Request(Type service, Func constraint, IEnumerable parameters, Func scopeCallback, bool isOptional, bool isUnique) + public bool ForceUnique { - Ensure.ArgumentNotNull(service, "service"); - Ensure.ArgumentNotNull(parameters, "parameters"); - - Service = service; - Constraint = constraint; - Parameters = parameters.ToList(); - ScopeCallback = scopeCallback; - ActiveBindings = new Stack(); - Depth = 0; - IsOptional = isOptional; - IsUnique = isUnique; + get; set; } /// - /// Initializes a new instance of the class. + /// Gets the callback that resolves the scope for the request, if an external scope was provided. /// - /// The parent context. - /// The service that was requested. - /// The target that will receive the injection. - /// The scope callback, if an external scope was specified. - public Request(IContext parentContext, Type service, ITarget target, Func scopeCallback) - { - Ensure.ArgumentNotNull(parentContext, "parentContext"); - Ensure.ArgumentNotNull(service, "service"); - Ensure.ArgumentNotNull(target, "target"); - - ParentContext = parentContext; - ParentRequest = parentContext.Request; - Service = service; - Target = target; - Constraint = target.Constraint; - IsOptional = target.IsOptional; - Parameters = parentContext.Parameters.Where(p => p.ShouldInherit).ToList(); - ScopeCallback = scopeCallback; - ActiveBindings = new Stack(ParentRequest.ActiveBindings); - Depth = ParentRequest.Depth + 1; - } + public Func ScopeCallback { get; private set; } /// /// Determines whether the specified binding satisfies the constraints defined on this request. @@ -138,7 +152,7 @@ public Request(IContext parentContext, Type service, ITarget target, FuncTrue if the binding satisfies the constraints; otherwise false. public bool Matches(IBinding binding) { - return Constraint == null || Constraint(binding.Metadata); + return this.Constraint == null || this.Constraint(binding.Metadata); } /// @@ -147,7 +161,7 @@ public bool Matches(IBinding binding) /// The object that acts as the scope. public object GetScope() { - return ScopeCallback == null ? null : ScopeCallback(); + return this.ScopeCallback == null ? null : this.ScopeCallback(); } /// @@ -159,7 +173,16 @@ public object GetScope() /// The child request. public IRequest CreateChild(Type service, IContext parentContext, ITarget target) { - return new Request(parentContext, service, target, ScopeCallback); + return new Request(parentContext, service, target, this.ScopeCallback); + } + + /// + /// Formats this object into a meaningful string representation. + /// + /// The request formatted as string. + public override string ToString() + { + return this.Format(); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationCacheStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationCacheStrategy.cs index 35a3e244..07ec230b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationCacheStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationCacheStrategy.cs @@ -1,11 +1,34 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { using Telerik.JustMock.AutoMock.Ninject.Activation.Caching; + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; /// /// Adds all activated instances to the activation cache. /// - public class ActivationCacheStrategy : IActivationStrategy + public class ActivationCacheStrategy : NinjectComponent, IActivationStrategy { /// /// The activation cache. @@ -18,20 +41,9 @@ public class ActivationCacheStrategy : IActivationStrategy /// The activation cache. public ActivationCacheStrategy(IActivationCache activationCache) { - this.activationCache = activationCache; - } + Ensure.ArgumentNotNull(activationCache, "activationCache"); - /// - /// Gets or sets the settings. - /// - /// The ninject settings. - public INinjectSettings Settings { get; set; } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { + this.activationCache = activationCache; } /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationStrategy.cs index 67d2dea8..f62ebc13 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/ActivationStrategy.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Contributes to a , and is called during the activation /// and deactivation of an instance. @@ -25,13 +34,17 @@ public abstract class ActivationStrategy : NinjectComponent, IActivationStrategy /// /// The context. /// A reference to the instance being activated. - public virtual void Activate(IContext context, InstanceReference reference) { } + public virtual void Activate(IContext context, InstanceReference reference) + { + } /// /// Contributes to the deactivation of the instance in the specified context. /// /// The context. /// A reference to the instance being deactivated. - public virtual void Deactivate(IContext context, InstanceReference reference) { } + public virtual void Deactivate(IContext context, InstanceReference reference) + { + } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/BindingActionStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/BindingActionStrategy.cs index a8c4d50a..4e9caabe 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/BindingActionStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/BindingActionStrategy.cs @@ -1,20 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + /// /// Executes actions defined on the binding during activation and deactivation. /// @@ -28,6 +37,7 @@ public class BindingActionStrategy : ActivationStrategy public override void Activate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); + context.Binding.ActivationActions.Map(action => action(context, reference.Instance)); } @@ -39,6 +49,7 @@ public override void Activate(IContext context, InstanceReference reference) public override void Deactivate(IContext context, InstanceReference reference) { Ensure.ArgumentNotNull(context, "context"); + context.Binding.DeactivationActions.Map(action => action(context, reference.Instance)); } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/DisposableStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/DisposableStrategy.cs index 66f70d61..7713f62d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/DisposableStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/DisposableStrategy.cs @@ -1,18 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { + using System; + /// /// During deactivation, disposes instances that implement . /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/IActivationStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/IActivationStrategy.cs index f2777588..032d052a 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/IActivationStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/IActivationStrategy.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Contributes to a , and is called during the activation /// and deactivation of an instance. diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/InitializableStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/InitializableStrategy.cs index a87a6f3c..51c05631 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/InitializableStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/InitializableStrategy.cs @@ -1,15 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/MethodInjectionStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/MethodInjectionStrategy.cs index 3f9a2eaa..c9098e66 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/MethodInjectionStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/MethodInjectionStrategy.cs @@ -1,22 +1,31 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Injection; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + /// /// Injects methods on an instance during activation. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/PropertyInjectionStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/PropertyInjectionStrategy.cs index e9be9bbf..309985e5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/PropertyInjectionStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/PropertyInjectionStrategy.cs @@ -1,28 +1,38 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; -using Telerik.JustMock.AutoMock.Ninject.Injection; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; + using Telerik.JustMock.AutoMock.Ninject.Injection; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + /// /// Injects properties on an instance during activation. /// @@ -30,30 +40,30 @@ public class PropertyInjectionStrategy : ActivationStrategy { private const BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Instance; - private BindingFlags Flags + /// + /// Initializes a new instance of the class. + /// + /// The injector factory component. + public PropertyInjectionStrategy(IInjectorFactory injectorFactory) { - get - { - #if !NO_LCG && !SILVERLIGHT - return Settings.InjectNonPublic ? (DefaultFlags | BindingFlags.NonPublic) : DefaultFlags; - #else - return DefaultFlags; - #endif - } + this.InjectorFactory = injectorFactory; } /// - /// Gets the injector factory component. + /// Gets or sets the injector factory component. /// public IInjectorFactory InjectorFactory { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// The injector factory component. - public PropertyInjectionStrategy(IInjectorFactory injectorFactory) + private BindingFlags Flags { - this.InjectorFactory = injectorFactory; + get + { +#if !NO_LCG + return this.Settings.InjectNonPublic ? (DefaultFlags | BindingFlags.NonPublic) : DefaultFlags; +#else + return DefaultFlags; +#endif + } } /// @@ -71,11 +81,11 @@ public override void Activate(IContext context, InstanceReference reference) foreach (var directive in context.Plan.GetAll()) { - object value = this.GetValue(context, directive.Target, propertyValues); + var value = this.GetValue(context, directive.Target, propertyValues); directive.Injector(reference.Instance, value); } - this.AssignProperyOverrides(context, reference, propertyValues); + this.AssignPropertyOverrides(context, reference, propertyValues); } /// @@ -84,12 +94,13 @@ public override void Activate(IContext context, InstanceReference reference) /// The context. /// A reference to the instance being activated. /// The parameter override value accessors. - private void AssignProperyOverrides(IContext context, InstanceReference reference, IList propertyValues) + private void AssignPropertyOverrides(IContext context, InstanceReference reference, IList propertyValues) { var properties = reference.Instance.GetType().GetProperties(this.Flags); + foreach (var propertyValue in propertyValues) { - string propertyName = propertyValue.Name; + var propertyName = propertyValue.Name; var propertyInfo = properties.FirstOrDefault(property => string.Equals(property.Name, propertyName, StringComparison.Ordinal)); if (propertyInfo == null) @@ -98,7 +109,7 @@ private void AssignProperyOverrides(IContext context, InstanceReference referenc } var target = new PropertyInjectionDirective(propertyInfo, this.InjectorFactory.Create(propertyInfo)); - object value = this.GetValue(context, target.Target, propertyValues); + var value = this.GetValue(context, target.Target, propertyValues); target.Injector(reference.Instance, value); } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/StartableStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/StartableStrategy.cs index d0b53fd2..da0eea35 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/StartableStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Activation/Strategies/StartableStrategy.cs @@ -1,15 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Activation.Strategies { diff --git a/Telerik.JustMock/AutoMock/Ninject/ActivationException.cs b/Telerik.JustMock/AutoMock/Ninject/ActivationException.cs index 20c1a37d..9129a1aa 100644 --- a/Telerik.JustMock/AutoMock/Ninject/ActivationException.cs +++ b/Telerik.JustMock/AutoMock/Ninject/ActivationException.cs @@ -1,54 +1,69 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#if !NO_EXCEPTION_SERIALIZATION -using System.Runtime.Serialization; -#endif -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + using System.Runtime.Serialization; + /// - /// Indicates that an error occured during activation of an instance. + /// Indicates that an error occurred during activation of an instance. /// - #if !NO_EXCEPTION_SERIALIZATION [Serializable] - #endif public class ActivationException : Exception { /// /// Initializes a new instance of the class. /// - public ActivationException() { } + public ActivationException() + { + } /// /// Initializes a new instance of the class. /// /// The exception message. - public ActivationException(string message) : base(message) { } + public ActivationException(string message) + : base(message) + { + } /// /// Initializes a new instance of the class. /// /// The exception message. /// The inner exception. - public ActivationException(string message, Exception innerException) : base(message, innerException) { } + public ActivationException(string message, Exception innerException) + : base(message, innerException) + { + } - #if !NO_EXCEPTION_SERIALIZATION /// /// Initializes a new instance of the class. /// /// The serialized object data. /// The serialization context. - protected ActivationException(SerializationInfo info, StreamingContext context) : base(info, context) { } - #endif + protected ActivationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Attributes/ConstraintAttribute.cs b/Telerik.JustMock/AutoMock/Ninject/Attributes/ConstraintAttribute.cs index 3910717e..08a98bca 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Attributes/ConstraintAttribute.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Attributes/ConstraintAttribute.cs @@ -1,19 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Defines a constraint on the decorated member. /// @@ -27,4 +38,4 @@ public abstract class ConstraintAttribute : Attribute /// True if the metadata matches; otherwise false. public abstract bool Matches(IBindingMetadata metadata); } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Attributes/InjectAttribute.cs b/Telerik.JustMock/AutoMock/Ninject/Attributes/InjectAttribute.cs index d15fe88a..d89cc870 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Attributes/InjectAttribute.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Attributes/InjectAttribute.cs @@ -1,22 +1,36 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + /// /// Indicates that the decorated member should be injected. /// - [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, - AllowMultiple = false, Inherited = true)] - public class InjectAttribute : Attribute { } -} + [AttributeUsage( + AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, + AllowMultiple = false, + Inherited = true)] + public class InjectAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Attributes/NamedAttribute.cs b/Telerik.JustMock/AutoMock/Ninject/Attributes/NamedAttribute.cs index f704bad7..c8e0a635 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Attributes/NamedAttribute.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Attributes/NamedAttribute.cs @@ -1,31 +1,35 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Indicates that the decorated member should only be injected using binding(s) registered /// with the specified name. /// public class NamedAttribute : ConstraintAttribute { - /// - /// Gets the binding name. - /// - public string Name { get; private set; } - /// /// Initializes a new instance of the class. /// @@ -33,9 +37,15 @@ public class NamedAttribute : ConstraintAttribute public NamedAttribute(string name) { Ensure.ArgumentNotNullOrEmpty(name, "name"); - Name = name; + + this.Name = name; } + /// + /// Gets the binding name. + /// + public string Name { get; private set; } + /// /// Determines whether the specified binding metadata matches the constraint. /// @@ -44,7 +54,8 @@ public NamedAttribute(string name) public override bool Matches(IBindingMetadata metadata) { Ensure.ArgumentNotNull(metadata, "metadata"); - return metadata.Name == Name; + + return metadata.Name == this.Name; } } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Attributes/OptionalAttribute.cs b/Telerik.JustMock/AutoMock/Ninject/Attributes/OptionalAttribute.cs index 9f7c63d2..aaf00a21 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Attributes/OptionalAttribute.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Attributes/OptionalAttribute.cs @@ -1,22 +1,36 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + /// /// Indicates that the decorated member represents an optional dependency. /// - [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, - AllowMultiple = false, Inherited = true)] - public class OptionalAttribute : Attribute { } -} + [AttributeUsage( + AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, + AllowMultiple = false, + Inherited = true)] + public class OptionalAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Components/ComponentContainer.cs b/Telerik.JustMock/AutoMock/Ninject/Components/ComponentContainer.cs index 90aed720..dc6bfac7 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Components/ComponentContainer.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Components/ComponentContainer.cs @@ -1,32 +1,43 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Components { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + /// /// An internal container that manages and resolves components that contribute to Ninject. /// public class ComponentContainer : DisposableObject, IComponentContainer { - private readonly Multimap _mappings = new Multimap(); - private readonly Dictionary _instances = new Dictionary(); + private readonly Multimap mappings = new Multimap(); + private readonly Dictionary instances = new Dictionary(); private readonly HashSet> transients = new HashSet>(); /// @@ -37,15 +48,18 @@ public class ComponentContainer : DisposableObject, IComponentContainer /// /// Releases resources held by the object. /// + /// True if called manually, otherwise by GC. public override void Dispose(bool disposing) { - if (disposing && !IsDisposed) + if (disposing && !this.IsDisposed) { - foreach (INinjectComponent instance in _instances.Values) + foreach (INinjectComponent instance in this.instances.Values) + { instance.Dispose(); + } - _mappings.Clear(); - _instances.Clear(); + this.mappings.Clear(); + this.instances.Clear(); } base.Dispose(disposing); @@ -60,7 +74,7 @@ public void Add() where TComponent : INinjectComponent where TImplementation : TComponent, INinjectComponent { - _mappings.Add(typeof(TComponent), typeof(TImplementation)); + this.mappings.Add(typeof(TComponent), typeof(TImplementation)); } /// @@ -75,7 +89,7 @@ public void AddTransient() this.Add(); this.transients.Add(new KeyValuePair(typeof(TComponent), typeof(TImplementation))); } - + /// /// Removes all registrations for the specified component. /// @@ -83,7 +97,27 @@ public void AddTransient() public void RemoveAll() where T : INinjectComponent { - RemoveAll(typeof(T)); + this.RemoveAll(typeof(T)); + } + + /// + /// Removes the specified registration. + /// + /// The component type. + /// The implementation type. + public void Remove() + where T : INinjectComponent + where TImplementation : T + { + var implementation = typeof(TImplementation); + if (this.instances.ContainsKey(implementation)) + { + this.instances[implementation].Dispose(); + } + + this.instances.Remove(implementation); + + this.mappings.Remove(typeof(T), typeof(TImplementation)); } /// @@ -94,15 +128,17 @@ public void RemoveAll(Type component) { Ensure.ArgumentNotNull(component, "component"); - foreach (Type implementation in _mappings[component]) + foreach (Type implementation in this.mappings[component]) { - if (_instances.ContainsKey(implementation)) - _instances[implementation].Dispose(); + if (this.instances.ContainsKey(implementation)) + { + this.instances[implementation].Dispose(); + } - _instances.Remove(implementation); + this.instances.Remove(implementation); } - _mappings.RemoveAll(component); + this.mappings.RemoveAll(component); } /// @@ -113,7 +149,7 @@ public void RemoveAll(Type component) public T Get() where T : INinjectComponent { - return (T) Get(typeof(T)); + return (T)this.Get(typeof(T)); } /// @@ -124,7 +160,7 @@ public T Get() public IEnumerable GetAll() where T : INinjectComponent { - return GetAll(typeof(T)).Cast(); + return this.GetAll(typeof(T)).Cast(); } /// @@ -137,29 +173,29 @@ public object Get(Type component) Ensure.ArgumentNotNull(component, "component"); if (component == typeof(IKernel)) - return Kernel; + { + return this.Kernel; + } if (component.IsGenericType) { - Type gtd = component.GetGenericTypeDefinition(); - Type argument = component.GetGenericArguments()[0]; - -#if WINDOWS_PHONE - Type discreteGenericType = - typeof (IEnumerable<>).MakeGenericType(argument); - if (gtd.IsInterface && discreteGenericType.IsAssignableFrom(component)) - return GetAll(argument).CastSlow(argument); -#else - if (gtd.IsInterface && typeof (IEnumerable<>).IsAssignableFrom(gtd)) - return GetAll(argument).CastSlow(argument); -#endif + var gtd = component.GetGenericTypeDefinition(); + var argument = component.GenericTypeArguments[0]; + + if (gtd.IsInterface && typeof(IEnumerable<>).IsAssignableFrom(gtd)) + { + return this.GetAll(argument).CastSlow(argument); + } } - Type implementation = _mappings[component].FirstOrDefault(); + + var implementation = this.mappings[component].FirstOrDefault(); if (implementation == null) + { throw new InvalidOperationException(ExceptionFormatter.NoSuchComponentRegistered(component)); + } - return ResolveInstance(component, implementation); + return this.ResolveInstance(component, implementation); } /// @@ -171,29 +207,44 @@ public IEnumerable GetAll(Type component) { Ensure.ArgumentNotNull(component, "component"); - return _mappings[component] - .Select(implementation => ResolveInstance(component, implementation)); + return this.mappings[component] + .Select(implementation => this.ResolveInstance(component, implementation)); + } + + private static ConstructorInfo SelectConstructor(Type component, Type implementation) + { + var constructor = implementation.GetConstructors().OrderByDescending(c => c.GetParameters().Length).FirstOrDefault(); + + if (constructor == null) + { + throw new InvalidOperationException(ExceptionFormatter.NoConstructorsAvailableForComponent(component, implementation)); + } + + return constructor; } private object ResolveInstance(Type component, Type implementation) { - lock (_instances) - return _instances.ContainsKey(implementation) ? _instances[implementation] : CreateNewInstance(component, implementation); + lock (this.instances) + { + return this.instances.ContainsKey(implementation) ? this.instances[implementation] : this.CreateNewInstance(component, implementation); + } } private object CreateNewInstance(Type component, Type implementation) { - ConstructorInfo constructor = SelectConstructor(component, implementation); - var arguments = constructor.GetParameters().Select(parameter => Get(parameter.ParameterType)).ToArray(); + var constructor = SelectConstructor(component, implementation); + var arguments = constructor.GetParameters().Select(parameter => this.Get(parameter.ParameterType)).ToArray(); try { var instance = constructor.Invoke(arguments) as INinjectComponent; - instance.Settings = Kernel.Settings; + + instance.Settings = this.Kernel.Settings; if (!this.transients.Contains(new KeyValuePair(component, implementation))) { - _instances.Add(implementation, instance); + this.instances.Add(implementation, instance); } return instance; @@ -204,32 +255,5 @@ private object CreateNewInstance(Type component, Type implementation) return null; } } - - private static ConstructorInfo SelectConstructor(Type component, Type implementation) - { - var constructor = implementation.GetConstructors().OrderByDescending(c => c.GetParameters().Length).FirstOrDefault(); - - if (constructor == null) - throw new InvalidOperationException(ExceptionFormatter.NoConstructorsAvailableForComponent(component, implementation)); - - return constructor; - } - -#if SILVERLIGHT_30 || SILVERLIGHT_20 || WINDOWS_PHONE || NETCF_35 - private class HashSet - { - private IDictionary data = new Dictionary(); - - public void Add(T o) - { - this.data.Add(o, null); - } - - public bool Contains(T o) - { - return this.data.ContainsKey(o); - } - } -#endif } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Components/IComponentContainer.cs b/Telerik.JustMock/AutoMock/Ninject/Components/IComponentContainer.cs index c5702614..077769e0 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Components/IComponentContainer.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Components/IComponentContainer.cs @@ -1,19 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Components { + using System; + using System.Collections.Generic; + /// /// An internal container that manages and resolves components that contribute to Ninject. /// @@ -37,7 +47,8 @@ void Add() /// Removes all registrations for the specified component. /// /// The component type. - void RemoveAll() where T : INinjectComponent; + void RemoveAll() + where T : INinjectComponent; /// /// Removes all registrations for the specified component. @@ -45,19 +56,30 @@ void Add() /// The component's type. void RemoveAll(Type component); + /// + /// Removes the specified registration. + /// + /// The component type. + /// The implementation type. + void Remove() + where T : INinjectComponent + where TImplementation : T; + /// /// Gets one instance of the specified component. /// /// The component type. /// The instance of the component. - T Get() where T : INinjectComponent; + T Get() + where T : INinjectComponent; /// /// Gets all available instances of the specified component. /// /// The component type. /// A series of instances of the specified component. - IEnumerable GetAll() where T : INinjectComponent; + IEnumerable GetAll() + where T : INinjectComponent; /// /// Gets one instance of the specified component. diff --git a/Telerik.JustMock/AutoMock/Ninject/Components/INinjectComponent.cs b/Telerik.JustMock/AutoMock/Ninject/Components/INinjectComponent.cs index cd9488c8..c54fcad4 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Components/INinjectComponent.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Components/INinjectComponent.cs @@ -1,18 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Components { + using System; + /// /// A component that contributes to the internals of Ninject. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Components/NinjectComponent.cs b/Telerik.JustMock/AutoMock/Ninject/Components/NinjectComponent.cs index efce03a4..2d2eb499 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Components/NinjectComponent.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Components/NinjectComponent.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Components { + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; + /// /// A component that contributes to the internals of Ninject. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistration.cs b/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistration.cs index 9796a5dd..e6a1e586 100644 --- a/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistration.cs +++ b/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistration.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { @@ -32,23 +32,36 @@ namespace Telerik.JustMock.AutoMock.Ninject /// public abstract class GlobalKernelRegistration { - private static readonly ReaderWriterLock kernelRegistrationsLock = new ReaderWriterLock(); - private static readonly IDictionary kernelRegistrations = new Dictionary(); + private static readonly ReaderWriterLockSlim KernelRegistrationsLock = new ReaderWriterLockSlim(); + + private static readonly IDictionary KernelRegistrations = new Dictionary(); + /// + /// Registers the kernel for the specified type. + /// + /// The . + /// The service type. internal static void RegisterKernelForType(IKernel kernel, Type type) { var registration = GetRegistrationForType(type); - registration.KernelLock.AcquireWriterLock(Timeout.Infinite); + + registration.KernelLock.EnterWriteLock(); + try { registration.Kernels.Add(new WeakReference(kernel)); } finally { - registration.KernelLock.ReleaseWriterLock(); + registration.KernelLock.ExitWriteLock(); } } + /// + /// Un-registers the kernel for the specified type. + /// + /// The . + /// The service type. internal static void UnregisterKernelForType(IKernel kernel, Type type) { var registration = GetRegistrationForType(type); @@ -61,16 +74,16 @@ internal static void UnregisterKernelForType(IKernel kernel, Type type) /// The action. protected void MapKernels(Action action) { - bool requiresCleanup = false; + var requiresCleanup = false; var registration = GetRegistrationForType(this.GetType()); - registration.KernelLock.AcquireReaderLock(Timeout.Infinite); + + registration.KernelLock.EnterReadLock(); try { foreach (var weakReference in registration.Kernels) { - var kernel = weakReference.Target as IKernel; - if (kernel != null) + if (weakReference.Target is IKernel kernel) { action(kernel); } @@ -82,7 +95,7 @@ protected void MapKernels(Action action) } finally { - registration.KernelLock.ReleaseReaderLock(); + registration.KernelLock.ExitReadLock(); } if (requiresCleanup) @@ -90,10 +103,11 @@ protected void MapKernels(Action action) RemoveKernels(registration, registration.Kernels.Where(reference => !reference.IsAlive)); } } - + private static void RemoveKernels(Registration registration, IEnumerable references) { - registration.KernelLock.AcquireWriterLock(Timeout.Infinite); + registration.KernelLock.EnterWriteLock(); + try { foreach (var reference in references.ToArray()) @@ -103,47 +117,46 @@ private static void RemoveKernels(Registration registration, IEnumerable(); } - public ReaderWriterLock KernelLock { get; private set; } + public ReaderWriterLockSlim KernelLock { get; private set; } + public IList Kernels { get; private set; } } } diff --git a/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistrationModule.cs b/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistrationModule.cs index 762fd133..571bbc18 100644 --- a/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistrationModule.cs +++ b/Telerik.JustMock/AutoMock/Ninject/GlobalKernelRegistrationModule.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,9 +17,8 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- -#if !SILVERLIGHT && !NETCF namespace Telerik.JustMock.AutoMock.Ninject { using Telerik.JustMock.AutoMock.Ninject.Modules; @@ -48,5 +47,4 @@ public override void Unload() GlobalKernelRegistration.UnregisterKernelForType(this.Kernel, typeof(TGlobalKernelRegistry)); } } -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/IHaveNinjectComponents.cs b/Telerik.JustMock/AutoMock/Ninject/IHaveNinjectComponents.cs new file mode 100644 index 00000000..4ed33210 --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/IHaveNinjectComponents.cs @@ -0,0 +1,36 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject +{ + using Telerik.JustMock.AutoMock.Ninject.Components; + + /// + /// Provides access to Ninject components. + /// + public interface IHaveNinjectComponents + { + /// + /// Gets the component container, which holds components that contribute to Ninject. + /// + IComponentContainer Components { get; } + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/IHaveNinjectSettings.cs b/Telerik.JustMock/AutoMock/Ninject/IHaveNinjectSettings.cs new file mode 100644 index 00000000..77762f26 --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/IHaveNinjectSettings.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject +{ + /// + /// Provides access to Ninject settings. + /// + public interface IHaveNinjectSettings + { + /// + /// Gets the kernel settings. + /// + INinjectSettings Settings { get; } + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/IInitializable.cs b/Telerik.JustMock/AutoMock/Ninject/IInitializable.cs index 9681d69a..f1e44495 100644 --- a/Telerik.JustMock/AutoMock/Ninject/IInitializable.cs +++ b/Telerik.JustMock/AutoMock/Ninject/IInitializable.cs @@ -1,15 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { @@ -23,4 +31,4 @@ public interface IInitializable /// void Initialize(); } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/IKernel.cs b/Telerik.JustMock/AutoMock/Ninject/IKernel.cs index 7a292017..c1372748 100644 --- a/Telerik.JustMock/AutoMock/Ninject/IKernel.cs +++ b/Telerik.JustMock/AutoMock/Ninject/IKernel.cs @@ -1,31 +1,41 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Activation.Blocks; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; -using Telerik.JustMock.AutoMock.Ninject.Modules; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -using Telerik.JustMock.AutoMock.Ninject.Syntax; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + using System.Collections.Generic; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Activation.Blocks; + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal; + using Telerik.JustMock.AutoMock.Ninject.Modules; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Syntax; + /// /// A super-factory that can create objects of all kinds, following hints provided by s. /// - public interface IKernel : IBindingRoot, IResolutionRoot, IServiceProvider, IDisposableObject + public interface IKernel : IBindingRoot, IResolutionRoot, IServiceProvider, IDisposableObject, INotifyWhenDisposed { /// /// Gets the kernel settings. @@ -56,7 +66,6 @@ public interface IKernel : IBindingRoot, IResolutionRoot, IServiceProvider, IDis /// The modules to load. void Load(IEnumerable m); - #if !NO_ASSEMBLY_SCANNING /// /// Loads modules from the files that match the specified pattern(s). /// @@ -68,7 +77,6 @@ public interface IKernel : IBindingRoot, IResolutionRoot, IServiceProvider, IDis /// /// The assemblies to search. void Load(IEnumerable assemblies); - #endif /// /// Unloads the plugin with the specified name. @@ -76,13 +84,6 @@ public interface IKernel : IBindingRoot, IResolutionRoot, IServiceProvider, IDis /// The plugin's name. void Unload(string name); - /// - /// Injects the specified existing instance, without managing its lifecycle. - /// - /// The instance to inject. - /// The parameters to pass to the request. - void Inject(object instance, params IParameter[] parameters); - /// /// Gets the bindings registered for the specified service. /// @@ -96,4 +97,4 @@ public interface IKernel : IBindingRoot, IResolutionRoot, IServiceProvider, IDis /// The new activation block. IActivationBlock BeginBlock(); } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/INinjectSettings.cs b/Telerik.JustMock/AutoMock/Ninject/INinjectSettings.cs index e2424c24..da8df5ef 100644 --- a/Telerik.JustMock/AutoMock/Ninject/INinjectSettings.cs +++ b/Telerik.JustMock/AutoMock/Ninject/INinjectSettings.cs @@ -1,20 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Activation; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + /// /// Contains configuration options for Ninject. /// @@ -35,7 +45,6 @@ public interface INinjectSettings /// Func DefaultScopeCallback { get; } - #if !NO_ASSEMBLY_SCANNING /// /// Gets a value indicating whether the kernel should automatically load extensions at startup. /// @@ -45,31 +54,28 @@ public interface INinjectSettings /// Gets the paths that should be searched for extensions. /// string[] ExtensionSearchPatterns { get; } - #endif //!NO_ASSEMBLY_SCANNING - #if !NO_LCG +#if !NO_LCG /// /// Gets a value indicating whether Ninject should use reflection-based injection instead of /// the (usually faster) lightweight code generation system. /// bool UseReflectionBasedInjection { get; } - #endif //!NO_LCG +#endif //!NO_LCG - #if !SILVERLIGHT /// - /// Gets a value indicating whether Ninject should inject non public members. + /// Gets or sets a value indicating whether Ninject should inject non public members. /// bool InjectNonPublic { get; set; } /// - /// Gets a value indicating whether Ninject should inject private properties of base classes. + /// Gets or sets a value indicating whether Ninject should inject private properties of base classes. /// /// - /// Activating this setting has an impact on the performance. It is recomended not + /// Activating this setting has an impact on the performance. It is recommended not /// to use this feature and use constructor injection instead. /// bool InjectParentPrivateProperties { get; set; } - #endif //!SILVERLIGHT /// /// Gets or sets a value indicating whether the activation cache is disabled. @@ -85,11 +91,19 @@ public interface INinjectSettings /// /// Gets or sets a value indicating whether Null is a valid value for injection. - /// By defuault this is disabled and whenever a provider returns null an exception is thrown. + /// By default this is disabled and whenever a provider returns null an exception is thrown. /// /// true if null is allowed as injected value otherwise false. bool AllowNullInjection { get; set; } + /// + /// Gets or sets a value indicating whether the old (<= 3.3.4) behavior of + /// should be used which throws an exception if the requested service cannot be found. Note that the documentation + /// of that method https://docs.microsoft.com/en-us/dotnet/api/system.iserviceprovider.getservice?view=netframework-4.6.2 + /// states that the method should return if there is no such service. + /// + bool ThrowOnGetServiceNotFound { get; set; } + /// /// Gets the value for the specified key. /// @@ -106,4 +120,4 @@ public interface INinjectSettings /// The setting's value. void Set(string key, object value); } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/IStartable.cs b/Telerik.JustMock/AutoMock/Ninject/IStartable.cs index ea172fd1..15ce53e5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/IStartable.cs +++ b/Telerik.JustMock/AutoMock/Ninject/IStartable.cs @@ -1,15 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { @@ -28,4 +36,4 @@ public interface IStartable /// void Stop(); } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/BaseWeakReference.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/BaseWeakReference.cs deleted file mode 100644 index 96d5c0f0..00000000 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/BaseWeakReference.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure -{ - using System; - - /// - /// Inheritable weak reference base class for Silverlight - /// - public abstract class BaseWeakReference - { - private readonly WeakReference innerWeakReference; - - /// - /// Initializes a new instance of the class. - /// - /// The target. - protected BaseWeakReference(object target) - { - this.innerWeakReference = new WeakReference(target); - } - - /// - /// Initializes a new instance of the class. - /// - /// The target. - /// if set to true [track resurrection]. - protected BaseWeakReference(object target, bool trackResurrection) - { - this.innerWeakReference = new WeakReference(target, trackResurrection); - } - - /// - /// Gets a value indicating whether this instance is alive. - /// - /// true if this instance is alive; otherwise, false. - public bool IsAlive - { - get - { - return this.innerWeakReference.IsAlive; - } - } - - /// - /// Gets or sets the target of this weak reference. - /// - /// The target of this weak reference. - public object Target - { - get - { - return this.innerWeakReference.Target; - } - - set - { - this.innerWeakReference.Target = value; - } - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/DisposableObject.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/DisposableObject.cs index ebe4f201..9505f21f 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/DisposableObject.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/DisposableObject.cs @@ -1,24 +1,46 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal { + using System; + /// /// An object that notifies when it is disposed. /// - public abstract class DisposableObject : IDisposableObject + public abstract class DisposableObject : IDisposableObject, INotifyWhenDisposed { + /// + /// Finalizes an instance of the class. + /// + ~DisposableObject() + { + this.Dispose(false); + } + + /// + /// Occurs when the object is disposed. + /// + public event EventHandler Disposed; + /// /// Gets a value indicating whether this instance is disposed. /// @@ -29,30 +51,25 @@ public abstract class DisposableObject : IDisposableObject /// public void Dispose() { - Dispose(true); + this.Dispose(true); } /// /// Releases resources held by the object. /// + /// True if called manually, otherwise by GC. public virtual void Dispose(bool disposing) { lock (this) { - if (disposing && !IsDisposed) + if (disposing && !this.IsDisposed) { - IsDisposed = true; + this.IsDisposed = true; + this.Disposed?.Invoke(this, EventArgs.Empty); + this.Disposed = null; GC.SuppressFinalize(this); } } } - - /// - /// Releases resources before the object is reclaimed by garbage collection. - /// - ~DisposableObject() - { - Dispose(false); - } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/IDisposableObject.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/IDisposableObject.cs index 07867e08..7dad029d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/IDisposableObject.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/IDisposableObject.cs @@ -1,18 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal { + using System; + /// /// An object that can report whether or not it is disposed. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/INotifyWhenDisposed.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/INotifyWhenDisposed.cs index ed991b0f..7c2d65f3 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/INotifyWhenDisposed.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Disposal/INotifyWhenDisposed.cs @@ -1,18 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Disposal { + using System; + /// /// An object that fires an event when it is disposed. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Ensure.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Ensure.cs index f1f876c6..0ccd6a21 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Ensure.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Ensure.cs @@ -1,28 +1,57 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure { + using System; + + /// + /// Argument guard. + /// internal static class Ensure { - public static void ArgumentNotNull(object argument, string name) + /// + /// Ensures the argument is not null. + /// + /// The argument value. + /// The argument name. + internal static void ArgumentNotNull(object argument, string name) { - if (argument == null) throw new ArgumentNullException(name, "Cannot be null"); + if (argument == null) + { + throw new ArgumentNullException(name, "Cannot be null"); + } } - public static void ArgumentNotNullOrEmpty(string argument, string name) + /// + /// Ensures the argument is not null or empty. + /// + /// The argument value. + /// The argument name. + internal static void ArgumentNotNullOrEmpty(string argument, string name) { - if (String.IsNullOrEmpty(argument)) throw new ArgumentException("Cannot be null or empty", name); + if (string.IsNullOrEmpty(argument)) + { + throw new ArgumentException("Cannot be null or empty", name); + } } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Future.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Future.cs deleted file mode 100644 index 4ceaafd6..00000000 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Future.cs +++ /dev/null @@ -1,67 +0,0 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion - -namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure -{ - /// - /// Represents a future value. - /// - /// The type of value. - public class Future - { - private bool _hasValue; - private T _value; - - /// - /// Gets the value, resolving it if necessary. - /// - public T Value - { - get - { - if (!_hasValue) - { - _value = Callback(); - _hasValue = true; - } - - return _value; - } - } - - /// - /// Gets the callback that will be called to resolve the value. - /// - public Func Callback { get; private set; } - - /// - /// Initializes a new instance of the Future<T> class. - /// - /// The callback that will be triggered to read the value. - public Future(Func callback) - { - Callback = callback; - } - - /// - /// Gets the value from the future. - /// - /// The future. - /// The future value. - public static implicit operator T(Future future) - { - return future.Value; - } - } -} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveBindingConfiguration.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveBindingConfiguration.cs index d2df576a..0c0394e0 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveBindingConfiguration.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveBindingConfiguration.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure { + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Indicates the object has a reference to a . /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveKernel.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveKernel.cs index f8fbeed3..2d52c8f5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveKernel.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/IHaveKernel.cs @@ -1,15 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure { diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Introspection/ExceptionFormatter.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Introspection/ExceptionFormatter.cs index 6482c953..211106bc 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Introspection/ExceptionFormatter.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Introspection/ExceptionFormatter.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection { @@ -50,6 +48,7 @@ public static string ModulesWithNullOrEmptyNamesAreNotSupported() /// /// Generates a message saying that modules without names are not supported. /// + /// The target. /// The exception message. public static string TargetDoesNotHaveADefaultValue(ITarget target) { @@ -71,10 +70,10 @@ public static string ModuleWithSameNameIsAlreadyLoaded(INinjectModule newModule, sw.WriteLine("Suggestions:"); sw.WriteLine(" 1) Ensure that you have not accidentally loaded the same module twice."); - #if !SILVERLIGHT +#if !NO_ASSEMBLY_SCANNING sw.WriteLine(" 2) If you are using automatic module loading, ensure you have not manually loaded a module"); sw.WriteLine(" that may be found by the module loader."); - #endif +#endif return sw.ToString(); } @@ -117,6 +116,7 @@ public static string CouldNotUniquelyResolveBinding(IRequest request, string[] f { sw.WriteLine(" {0}) {1}", i + 1, formattedMatchingBindings[i]); } + sw.WriteLine("Activation path:"); sw.WriteLine(request.FormatActivationPath()); @@ -147,9 +147,9 @@ public static string CouldNotResolveBinding(IRequest request) sw.WriteLine(" 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel."); sw.WriteLine(" 3) Ensure you have not accidentally created more than one kernel."); sw.WriteLine(" 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name."); - #if !SILVERLIGHT +#if !NO_ASSEMBLY_SCANNING sw.WriteLine(" 5) If you are using automatic module loading, ensure the search path and filters are correct."); - #endif +#endif return sw.ToString(); } @@ -229,7 +229,7 @@ public static string NoConstructorsAvailable(IContext context) return sw.ToString(); } } - + /// /// Generates a message saying that no constructors are available for the given component. /// @@ -297,6 +297,28 @@ public static string CouldNotResolvePropertyForValueInjection(IRequest request, } } + /// + /// Generates a message saying that the provider callback on the specified context is null. + /// + /// The context. + /// The exception message. + public static string ProviderCallbackIsNull(IContext context) + { + using (var sw = new StringWriter()) + { + sw.WriteLine("Error activating {0}", context.Request.Service.Format()); + sw.WriteLine("Provider callback is null."); + + sw.WriteLine("Activation path:"); + sw.WriteLine(context.Request.FormatActivationPath()); + + sw.WriteLine("Suggestions:"); + sw.WriteLine(" 1) Ensure that one of the 'To' methods is called after 'Bind' methond."); + + return sw.ToString(); + } + } + /// /// Generates a message saying that the provider on the specified context returned null. /// @@ -308,13 +330,13 @@ public static string ProviderReturnedNull(IContext context) { sw.WriteLine("Error activating {0} using {1}", context.Request.Service.Format(), context.Binding.Format(context)); sw.WriteLine("Provider returned null."); - + sw.WriteLine("Activation path:"); sw.WriteLine(context.Request.FormatActivationPath()); sw.WriteLine("Suggestions:"); sw.WriteLine(" 1) Ensure that the provider handles creation requests properly."); - + return sw.ToString(); } } @@ -332,7 +354,7 @@ public static string ConstructorsAmbiguous(IContext context, IGrouping -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.IO; -using System.Reflection; -using System.Text; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection { - using System.Globalization; + using System; + using System.IO; + using System.Reflection; + using System.Text; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; /// /// Provides extension methods for string formatting @@ -35,7 +44,7 @@ public static string FormatActivationPath(this IRequest request) { using (var sw = new StringWriter()) { - IRequest current = request; + var current = request; while (current != null) { @@ -48,7 +57,7 @@ public static string FormatActivationPath(this IRequest request) } /// - /// Formats the given binding into a meaningful string representation. + /// Formats the given binding into a meaningful string representation. /// /// The binding to be formatted. /// The context. @@ -58,12 +67,16 @@ public static string Format(this IBinding binding, IContext context) using (var sw = new StringWriter()) { if (binding.Condition != null) + { sw.Write("conditional "); + } if (binding.IsImplicit) + { sw.Write("implicit "); + } - IProvider provider = binding.GetProvider(context); + var provider = binding.GetProvider(context); switch (binding.Target) { @@ -76,8 +89,11 @@ public static string Format(this IBinding binding, IContext context) break; case BindingTarget.Provider: - sw.Write("provider binding from {0} to {1} (via {2})", binding.Service.Format(), - provider.Type.Format(), provider.GetType().Format()); + sw.Write( + "provider binding from {0} to {1} (via {2})", + binding.Service.Format(), + provider.Type.Format(), + provider.GetType().Format()); break; case BindingTarget.Method: @@ -106,9 +122,13 @@ public static string Format(this IRequest request) using (var sw = new StringWriter()) { if (request.Target == null) + { sw.Write("Request for {0}", request.Service.Format()); + } else + { sw.Write("Injection of dependency {0} into {1}", request.Service.Format(), request.Target.Format()); + } return sw.ToString(); } @@ -156,16 +176,12 @@ public static string Format(this Type type) { var friendlyName = GetFriendlyName(type); -#if !MONO if (friendlyName.Contains("AnonymousType")) + { return "AnonymousType"; -#else - - if (friendlyName.Contains("__AnonType")) - return "AnonymousType"; -#endif + } - switch (friendlyName.ToLower(CultureInfo.InvariantCulture)) + switch (friendlyName.ToLowerInvariant()) { case "int16": return "short"; case "int32": return "int"; @@ -186,9 +202,12 @@ public static string Format(this Type type) } var genericArguments = type.GetGenericArguments(); - if(genericArguments.Length > 0) + + if (genericArguments.Length > 0) + { return FormatGenericType(friendlyName, genericArguments); - + } + return friendlyName; } @@ -199,30 +218,29 @@ private static string GetFriendlyName(Type type) // remove generic arguments var firstBracket = friendlyName.IndexOf('['); if (firstBracket > 0) + { friendlyName = friendlyName.Substring(0, firstBracket); + } // remove assembly info var firstComma = friendlyName.IndexOf(','); if (firstComma > 0) + { friendlyName = friendlyName.Substring(0, firstComma); + } // remove namespace var lastPeriod = friendlyName.LastIndexOf('.'); if (lastPeriod >= 0) + { friendlyName = friendlyName.Substring(lastPeriod + 1); + } return friendlyName; } private static string FormatGenericType(string friendlyName, Type[] genericArguments) { - //var genericTag = "`" + genericArguments.Length; - //var genericArgumentNames = new string[genericArguments.Length]; - //for (int i = 0; i < genericArguments.Length; i++) - // genericArgumentNames[i] = genericArguments[i].Format(); - - //return friendlyName.Replace(genericTag, string.Join(", ", genericArgumentNames)); - var sb = new StringBuilder(friendlyName.Length + 10); var genericArgumentIndex = 0; @@ -231,8 +249,8 @@ private static string FormatGenericType(string friendlyName, Type[] genericArgum { if (friendlyName[index] == '`') { - var numArguments = friendlyName[index+1] - 48; - + var numArguments = friendlyName[index + 1] - 48; + sb.Append(friendlyName.Substring(startIndex, index - startIndex)); AppendGenericArguments(sb, genericArguments, genericArgumentIndex, numArguments); genericArgumentIndex += numArguments; @@ -240,8 +258,11 @@ private static string FormatGenericType(string friendlyName, Type[] genericArgum startIndex = index + 2; } } + if (startIndex < friendlyName.Length) + { sb.Append(friendlyName.Substring(startIndex)); + } return sb.ToString(); } @@ -250,14 +271,16 @@ private static void AppendGenericArguments(StringBuilder sb, Type[] genericArgum { sb.Append("{"); - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { if (i != 0) + { sb.Append(", "); + } sb.Append(genericArguments[start + i].Format()); } - + sb.Append("}"); } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForAssembly.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForAssembly.cs index e76d3afa..194c6a00 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForAssembly.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForAssembly.cs @@ -1,35 +1,59 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#if !NO_ASSEMBLY_SCANNING -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Modules; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Modules; + + /// + /// Provides extension methods for . + /// internal static class ExtensionsForAssembly { + /// + /// Determines whether the assembly has loadable . + /// + /// The . + /// True if there's any loadable , otherwise False. public static bool HasNinjectModules(this Assembly assembly) { - return assembly.GetExportedTypes().Any(IsLoadableModule); + return !assembly.IsDynamic && assembly.ExportedTypes.Any(IsLoadableModule); } + /// + /// Gets loadable s from the . + /// + /// The . + /// The loadable s public static IEnumerable GetNinjectModules(this Assembly assembly) { - return assembly.GetExportedTypes() - .Where(IsLoadableModule) - .Select(type => Activator.CreateInstance(type) as INinjectModule); + return assembly.IsDynamic ? + Enumerable.Empty() : + assembly.ExportedTypes.Where(IsLoadableModule) + .Select(type => Activator.CreateInstance(type) as INinjectModule); } private static bool IsLoadableModule(Type type) @@ -40,5 +64,4 @@ private static bool IsLoadableModule(Type type) && type.GetConstructor(Type.EmptyTypes) != null; } } -} -#endif //!NO_ASSEMBLY_SCANNING \ No newline at end of file +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForICustomAttributeProvider.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForICustomAttributeProvider.cs index b448aa80..c35944f5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForICustomAttributeProvider.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForICustomAttributeProvider.cs @@ -1,24 +1,43 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { using System; using System.Reflection; + /// + /// Provides extension methods for . + /// internal static class ExtensionsForICustomAttributeProvider { + /// + /// Determines if the has the specified attribute. + /// + /// The . + /// The attribute type. + /// True if the has the attribute, otherwise False. public static bool HasAttribute(this ICustomAttributeProvider member, Type type) { - var memberInfo = member as MemberInfo; - if (memberInfo != null) + if (member is MemberInfo memberInfo) { return memberInfo.HasAttribute(type); } @@ -26,10 +45,16 @@ public static bool HasAttribute(this ICustomAttributeProvider member, Type type) return member.IsDefined(type, true); } + /// + /// Gets custom attributes which supports and . + /// + /// The . + /// The attribute type. + /// When true, look up the hierarchy chain for the inherited custom attribute. + /// The attributes. public static object[] GetCustomAttributesExtended(this ICustomAttributeProvider member, Type attributeType, bool inherit) { - var memberInfo = member as MemberInfo; - if (memberInfo != null) + if (member is MemberInfo memberInfo) { return memberInfo.GetCustomAttributesExtended(attributeType, inherit); } diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerable.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerable.cs index 49562ab1..a2418cc5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerable.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerable.cs @@ -1,37 +1,76 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections; -using System.Linq; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { + using System; + using System.Collections; + using System.Linq; + using System.Reflection; + + /// + /// Provides extension methods for . + /// internal static class ExtensionsForIEnumerable { + private static readonly MethodInfo Cast = typeof(Enumerable).GetMethod(nameof(Cast)); + private static readonly MethodInfo ToArray = typeof(Enumerable).GetMethod(nameof(ToArray)); + private static readonly MethodInfo ToList = typeof(Enumerable).GetMethod(nameof(ToList)); + + /// + /// Casts the elements of an to the specified type using reflection. + /// + /// The that contains the elements to be cast. + /// The type to cast the elements of source to. + /// + /// An that contains each element of the + /// source sequence cast to the specified type. + /// public static IEnumerable CastSlow(this IEnumerable series, Type elementType) { - var method = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType); + var method = Cast.MakeGenericMethod(elementType); return method.Invoke(null, new[] { series }) as IEnumerable; } + /// + /// Creates an array from an . + /// + /// An to create an array from. + /// The type of the elements. + /// An array that contains the elements from the input sequence. public static Array ToArraySlow(this IEnumerable series, Type elementType) { - var method = typeof(Enumerable).GetMethod("ToArray").MakeGenericMethod(elementType); + var method = ToArray.MakeGenericMethod(elementType); return method.Invoke(null, new[] { series }) as Array; } + /// + /// Creates an from an . + /// + /// An to create an from. + /// The type of the elements. + /// An that contains the elements from the input sequence. public static IList ToListSlow(this IEnumerable series, Type elementType) { - var method = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(elementType); + var method = ToList.MakeGenericMethod(elementType); return method.Invoke(null, new[] { series }) as IList; } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerableOfT.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerableOfT.cs index 356b4d8c..9650ebac 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerableOfT.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForIEnumerableOfT.cs @@ -1,35 +1,47 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { + using System; + using System.Collections.Generic; + using System.Linq; + /// - /// Provides extension methods for see cref="IEnumerable{T}"/> + /// Provides extension methods for . /// public static class ExtensionsForIEnumerableOfT { /// /// Executes the given action for each of the elements in the enumerable. /// - /// + /// Type of the enumerable. /// The series. /// The action. public static void Map(this IEnumerable series, Action action) { foreach (T item in series) + { action(item); + } } /// @@ -42,5 +54,28 @@ public static IEnumerable ToEnumerable(this IEnumerable series) { return series.Select(x => x); } + + /// + /// Returns single element of enumerable or throws exception. + /// + /// The series. + /// The exception creator. + /// Type of the enumerable. + /// The single element of enumerable. + /// + /// Exception specified by exception creator. + /// + public static T SingleOrThrowException(this IEnumerable series, Func exceptionCreator) + { + var e = series.GetEnumerator(); + e.MoveNext(); + var result = e.Current; + if (e.MoveNext()) + { + throw exceptionCreator(); + } + + return result; + } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForMemberInfo.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForMemberInfo.cs index d542e8cb..e5f61d88 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForMemberInfo.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForMemberInfo.cs @@ -1,12 +1,23 @@ -#region License +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. // -// Author: Remo Gloor (remo.gloor@bbv.ch) -// Copyright (c) 2010, bbv Software Engineering AG. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { @@ -17,18 +28,17 @@ namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language using System.Reflection; /// - /// Extensions for MemberInfo + /// Provides extension methods for . /// public static class ExtensionsForMemberInfo { - const BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Instance; -#if !NO_LCG && !SILVERLIGHT - const BindingFlags Flags = DefaultFlags | BindingFlags.NonPublic; + private const BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Instance; +#if !NO_LCG + private const BindingFlags Flags = DefaultFlags | BindingFlags.NonPublic; #else - const BindingFlags Flags = DefaultFlags; + private const BindingFlags Flags = DefaultFlags; #endif -#if !MONO private static MethodInfo parentDefinitionMethodInfo; private static MethodInfo ParentDefinitionMethodInfo @@ -44,7 +54,6 @@ private static MethodInfo ParentDefinitionMethodInfo return parentDefinitionMethodInfo; } } -#endif /// /// Determines whether the specified member has attribute. @@ -52,7 +61,7 @@ private static MethodInfo ParentDefinitionMethodInfo /// The type of the attribute. /// The member. /// - /// true if the specified member has attribute; otherwise, false. + /// true if the specified member has attribute; otherwise, false. /// public static bool HasAttribute(this MemberInfo member) { @@ -65,26 +74,15 @@ public static bool HasAttribute(this MemberInfo member) /// The member. /// The type of the attribute. /// - /// true if the specified member has attribute; otherwise, false. + /// true if the specified member has attribute; otherwise, false. /// public static bool HasAttribute(this MemberInfo member, Type type) { - var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) + if (member is PropertyInfo propertyInfo) { return IsDefined(propertyInfo, type, true); } -#if NETCF - // Workaround for the CF bug that derived generic methods throw an exception for IsDefined - // This means that the Inject attribute can not be defined on base methods for CF framework - var methodInfo = member as MethodInfo; - if (methodInfo != null) - { - return methodInfo.IsDefined(type, false); - } -#endif - return member.IsDefined(type, true); } @@ -95,10 +93,7 @@ public static bool HasAttribute(this MemberInfo member, Type type) /// The property definition. /// The flags. /// The property info from the declared type of the property. - public static PropertyInfo GetPropertyFromDeclaredType( - this MemberInfo memberInfo, - PropertyInfo propertyDefinition, - BindingFlags flags) + public static PropertyInfo GetPropertyFromDeclaredType(this MemberInfo memberInfo, PropertyInfo propertyDefinition, BindingFlags flags) { return memberInfo.DeclaringType.GetProperty( propertyDefinition.Name, @@ -114,7 +109,7 @@ public static PropertyInfo GetPropertyFromDeclaredType( /// /// The property info. /// - /// true if the specified property info is private; otherwise, false. + /// true if the specified property info is private; otherwise, false. /// public static bool IsPrivate(this PropertyInfo propertyInfo) { @@ -125,25 +120,15 @@ public static bool IsPrivate(this PropertyInfo propertyInfo) /// /// Gets the custom attributes. - /// This version is able to get custom attributes for properties from base types even if the property is none public. + /// This version is able to get custom attributes for properties from base types even if the property is non-public. /// /// The member. /// Type of the attribute. /// if set to true [inherited]. - /// + /// The custom attributes. public static object[] GetCustomAttributesExtended(this MemberInfo member, Type attributeType, bool inherited) { -#if !NET_35 && !MONO_40 return Attribute.GetCustomAttributes(member, attributeType, inherited); -#else - var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) - { - return GetCustomAttributes(propertyInfo, attributeType, inherited); - } - - return member.GetCustomAttributes(attributeType, inherited); -#endif } private static PropertyInfo GetParentDefinition(PropertyInfo property) @@ -163,25 +148,12 @@ private static PropertyInfo GetParentDefinition(PropertyInfo property) private static MethodInfo GetParentDefinition(this MethodInfo method, BindingFlags flags) { -#if MEDIUM_TRUST || MONO - var baseDefinition = method.GetBaseDefinition(); - var type = method.DeclaringType.BaseType; - MethodInfo result = null; - while (result == null && type != null) - { - result = type.GetMethods(flags).Where(m => m.GetBaseDefinition().Equals(baseDefinition)).SingleOrDefault(); - type = type.BaseType; - } - - return result; -#else if (ParentDefinitionMethodInfo == null) { return null; } return (MethodInfo)ParentDefinitionMethodInfo.Invoke(method, flags, null, null, CultureInfo.InvariantCulture); -#endif } private static bool IsDefined(PropertyInfo element, Type attributeType, bool inherit) @@ -225,7 +197,7 @@ private static object[] GetCustomAttributes(PropertyInfo propertyInfo, Type attr info != null; info = GetParentDefinition(info)) { - object[] customAttributes = info.GetCustomAttributes(attributeType, false); + var customAttributes = info.GetCustomAttributes(attributeType, false); AddAttributes(attributes, customAttributes, attributeUsages); } @@ -240,9 +212,9 @@ private static object[] GetCustomAttributes(PropertyInfo propertyInfo, Type attr private static void AddAttributes(List attributes, object[] customAttributes, Dictionary attributeUsages) { - foreach (object attribute in customAttributes) + foreach (var attribute in customAttributes) { - Type type = attribute.GetType(); + var type = attribute.GetType(); if (!attributeUsages.ContainsKey(type)) { attributeUsages[type] = InternalGetAttributeUsage(type).Inherited; @@ -257,8 +229,7 @@ private static void AddAttributes(List attributes, object[] customAttrib private static AttributeUsageAttribute InternalGetAttributeUsage(Type type) { - object[] customAttributes = type.GetCustomAttributes(typeof(AttributeUsageAttribute), true); - return (AttributeUsageAttribute)customAttributes[0]; - } + return type.GetCustomAttribute(true); + } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForTargetInvocationException.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForTargetInvocationException.cs index ce2cf8b5..8663ad99 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForTargetInvocationException.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForTargetInvocationException.cs @@ -1,27 +1,42 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { + using System.Reflection; + using System.Runtime.ExceptionServices; + + /// + /// Provides extension methods for . + /// internal static class ExtensionsForTargetInvocationException { + /// + /// Re-throws inner exception. + /// + /// The . public static void RethrowInnerException(this TargetInvocationException exception) { - Exception innerException = exception.InnerException; - - FieldInfo stackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); - stackTraceField.SetValue(innerException, innerException.StackTrace); + var innerException = exception.InnerException; + ExceptionDispatchInfo.Capture(innerException).Throw(); throw innerException; } diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForType.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForType.cs index 3f4d6cce..2c74a481 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForType.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Language/ExtensionsForType.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language { @@ -25,9 +25,8 @@ namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language using System.Collections.Generic; /// - /// Extension methods for type + /// Extension methods for . /// - /// public static class ExtensionsForType { /// @@ -40,6 +39,7 @@ public static IEnumerable GetAllBaseTypes(this Type type) while (type != null) { yield return type; + type = type.BaseType; } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Multimap.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Multimap.cs index 9d8471ae..0d723fe1 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Multimap.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Multimap.cs @@ -1,60 +1,71 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections; -using System.Collections.Generic; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure { + using System.Collections; + using System.Collections.Generic; + /// /// A data structure that contains multiple values for a each key. /// - /// The type of key. - /// The type of value. - public class Multimap : IEnumerable>> + /// The type of key. + /// The type of value. + public class Multimap : IEnumerable>> { - private readonly Dictionary> _items = new Dictionary>(); + private readonly Dictionary> items = new Dictionary>(); /// - /// Gets the collection of values stored under the specified key. + /// Gets the collection of keys. /// - /// The key. - public ICollection this[K key] + public ICollection Keys { - get - { - Ensure.ArgumentNotNull(key, "key"); - - if (!_items.ContainsKey(key)) - _items[key] = new List(); - - return _items[key]; - } + get { return this.items.Keys; } } /// - /// Gets the collection of keys. + /// Gets the collection of collections of values. /// - public ICollection Keys + public ICollection> Values { - get { return _items.Keys; } + get { return this.items.Values; } } /// - /// Gets the collection of collections of values. + /// Gets the collection of values stored under the specified key. /// - public ICollection> Values + /// The key. + public ICollection this[TKey key] { - get { return _items.Values; } + get + { + Ensure.ArgumentNotNull(key, "key"); + + if (!this.items.ContainsKey(key)) + { + this.items[key] = new List(); + } + + return this.items[key]; + } } /// @@ -62,7 +73,7 @@ public ICollection> Values /// /// The key. /// The value. - public void Add(K key, V value) + public void Add(TKey key, TValue value) { Ensure.ArgumentNotNull(key, "key"); Ensure.ArgumentNotNull(value, "value"); @@ -76,15 +87,17 @@ public void Add(K key, V value) /// The key. /// The value. /// True if such a value existed and was removed; otherwise false. - public bool Remove(K key, V value) + public bool Remove(TKey key, TValue value) { Ensure.ArgumentNotNull(key, "key"); Ensure.ArgumentNotNull(value, "value"); - if (!_items.ContainsKey(key)) + if (!this.items.ContainsKey(key)) + { return false; + } - return _items[key].Remove(value); + return this.items[key].Remove(value); } /// @@ -92,10 +105,10 @@ public bool Remove(K key, V value) /// /// The key. /// True if any such values existed; otherwise false. - public bool RemoveAll(K key) + public bool RemoveAll(TKey key) { Ensure.ArgumentNotNull(key, "key"); - return _items.Remove(key); + return this.items.Remove(key); } /// @@ -103,7 +116,7 @@ public bool RemoveAll(K key) /// public void Clear() { - _items.Clear(); + this.items.Clear(); } /// @@ -111,10 +124,10 @@ public void Clear() /// /// The key. /// True if the multimap has one or more values for the specified key; otherwise, false. - public bool ContainsKey(K key) + public bool ContainsKey(TKey key) { Ensure.ArgumentNotNull(key, "key"); - return _items.ContainsKey(key); + return this.items.ContainsKey(key); } /// @@ -123,12 +136,12 @@ public bool ContainsKey(K key) /// The key. /// The value. /// True if the multimap contains such a value; otherwise, false. - public bool ContainsValue(K key, V value) + public bool ContainsValue(TKey key, TValue value) { Ensure.ArgumentNotNull(key, "key"); Ensure.ArgumentNotNull(value, "value"); - return _items.ContainsKey(key) && _items[key].Contains(value); + return this.items.ContainsKey(key) && this.items[key].Contains(value); } /// @@ -137,12 +150,16 @@ public bool ContainsValue(K key, V value) /// An object that can be used to iterate through the multimap. public IEnumerator GetEnumerator() { - return _items.GetEnumerator(); + return this.items.GetEnumerator(); } - IEnumerator>> IEnumerable>>.GetEnumerator() + /// + /// Returns an enumerator that iterates through a the multimap. + /// + /// An object that can be used to iterate through the multimap. + IEnumerator>> IEnumerable>>.GetEnumerator() { - return _items.GetEnumerator(); + return this.items.GetEnumerator(); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/ReferenceEqualWeakReference.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/ReferenceEqualWeakReference.cs index 9ed0bdee..1213802d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/ReferenceEqualWeakReference.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/ReferenceEqualWeakReference.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Remo Gloor (remo.gloor@bbv.ch) -// Copyright (c) 2010, bbv Software Services AG -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure { using System; using System.Runtime.CompilerServices; -#if SILVERLIGHT - using WeakReference = BaseWeakReference; -#endif /// /// Weak reference that can be used in collections. It is equal to the @@ -21,19 +30,16 @@ namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure /// public class ReferenceEqualWeakReference : WeakReference { - private readonly int cashedHashCode; + private readonly int cachedHashCode; /// /// Initializes a new instance of the class. /// /// The target. - public ReferenceEqualWeakReference(object target) : base(target) + public ReferenceEqualWeakReference(object target) + : base(target) { -#if !NETCF - this.cashedHashCode = RuntimeHelpers.GetHashCode(target); -#else - this.cashedHashCode = target.GetHashCode(); -#endif + this.cachedHashCode = RuntimeHelpers.GetHashCode(target); } /// @@ -41,13 +47,10 @@ public ReferenceEqualWeakReference(object target) : base(target) /// /// The target. /// if set to true [track resurrection]. - public ReferenceEqualWeakReference(object target, bool trackResurrection) : base(target, trackResurrection) + public ReferenceEqualWeakReference(object target, bool trackResurrection) + : base(target, trackResurrection) { -#if !NETCF - this.cashedHashCode = RuntimeHelpers.GetHashCode(target); -#else - this.cashedHashCode = target.GetHashCode(); -#endif + this.cachedHashCode = RuntimeHelpers.GetHashCode(target); } /// @@ -64,8 +67,7 @@ public override bool Equals(object obj) { var thisInstance = this.IsAlive ? this.Target : this; - var referenceEqualWeakReference = obj as WeakReference; - if (referenceEqualWeakReference != null && referenceEqualWeakReference.IsAlive) + if (obj is WeakReference referenceEqualWeakReference && referenceEqualWeakReference.IsAlive) { obj = referenceEqualWeakReference.Target; } @@ -77,11 +79,11 @@ public override bool Equals(object obj) /// Returns a hash code for this instance. /// /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// public override int GetHashCode() { - return this.cashedHashCode; + return this.cachedHashCode; } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/StandardScopeCallbacks.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/StandardScopeCallbacks.cs index d62a6bd8..153e1e21 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/StandardScopeCallbacks.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/StandardScopeCallbacks.cs @@ -1,19 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Activation; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Infrastructure { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + /// /// Scope callbacks for standard scopes. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Threading/ReaderWriterLock.cs b/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Threading/ReaderWriterLock.cs deleted file mode 100644 index 06cce2c9..00000000 --- a/Telerik.JustMock/AutoMock/Ninject/Infrastructure/Threading/ReaderWriterLock.cs +++ /dev/null @@ -1,416 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// -// -// -// A reader-writer lock implementation that is intended to be simple, yet very -// efficient. In particular only 1 interlocked operation is taken for any lock -// operation (we use spin locks to achieve this). The spin lock is never held -// for more than a few instructions (in particular, we never call event APIs -// or in fact any non-trivial API while holding the spin lock). -// Currently this ReaderWriterLock does not support recurision, however it is -// not hard to add -// -// -------------------------------------------------------------------------------------------------------------------- - -#if SILVERLIGHT || NETCF -namespace System.Threading -{ - using System.Diagnostics; - - /// - /// A reader-writer lock implementation that is intended to be simple, yet very - /// efficient. In particular only 1 interlocked operation is taken for any lock - /// operation (we use spin locks to achieve this). The spin lock is never held - /// for more than a few instructions (in particular, we never call event APIs - /// or in fact any non-trivial API while holding the spin lock). - /// - /// Currently this ReaderWriterLock does not support recurision, however it is - /// not hard to add - /// - /// - /// By Vance Morrison - /// Taken from - http://blogs.msdn.com/vancem/archive/2006/03/28/563180.aspx - /// Code at - http://blogs.msdn.com/vancem/attachment/563180.ashx - /// - public class ReaderWriterLock - { - // Lock specifiation for myLock: This lock protects exactly the local fields associted - // instance of MyReaderWriterLock. It does NOT protect the memory associted with the - // the events that hang off this lock (eg writeEvent, readEvent upgradeEvent). -#region Constants and Fields - - /// - /// The my lock. - /// - private int myLock; - - // Who owns the lock owners > 0 => readers - // owners = -1 means there is one writer. Owners must be >= -1. - - /// - /// The number read waiters. - /// - private uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent - - /// - /// The number upgrade waiters. - /// - private uint numUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1). - - /// - /// The number write waiters. - /// - private uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent - - /// - /// The owners. - /// - private int owners; - - // conditions we wait on. - - /// - /// The read event. - /// - private EventWaitHandle readEvent; // threads waiting to aquire a read lock go here (will be released in bulk) - - /// - /// The upgrade event. - /// - private EventWaitHandle upgradeEvent; // thread waiting to upgrade a read lock to a write lock go here (at most one) - - /// - /// The write event. - /// - private EventWaitHandle writeEvent; // threads waiting to aquire a write lock go here. - - #endregion - -#region Properties - - /// - /// Gets a value indicating whether MyLockHeld. - /// - private bool MyLockHeld - { - get - { - return this.myLock != 0; - } - } - - #endregion - -#region Public Methods - - /// - /// The acquire reader lock. - /// - /// - /// The milliseconds timeout. - /// - public void AcquireReaderLock(int millisecondsTimeout) - { - this.EnterMyLock(); - for (;;) - { - // We can enter a read lock if there are only read-locks have been given out - // and a writer is not trying to get in. - if (this.owners >= 0 && this.numWriteWaiters == 0) - { - // Good case, there is no contention, we are basically done - this.owners++; // Indicate we have another reader - break; - } - - // Drat, we need to wait. Mark that we have waiters and wait. - if (this.readEvent == null) - { - // Create the needed event - this.LazyCreateEvent(ref this.readEvent, false); - continue; // since we left the lock, start over. - } - - this.WaitOnEvent(this.readEvent, ref this.numReadWaiters, millisecondsTimeout); - } - - this.ExitMyLock(); - } - - /// - /// The acquire writer lock. - /// - /// - /// The milliseconds timeout. - /// - public void AcquireWriterLock(int millisecondsTimeout) - { - this.EnterMyLock(); - for (;;) - { - if (this.owners == 0) - { - // Good case, there is no contention, we are basically done - this.owners = -1; // indicate we have a writer. - break; - } - - // Drat, we need to wait. Mark that we have waiters and wait. - if (this.writeEvent == null) - { - // create the needed event. - this.LazyCreateEvent(ref this.writeEvent, true); - continue; // since we left the lock, start over. - } - - this.WaitOnEvent(this.writeEvent, ref this.numWriteWaiters, millisecondsTimeout); - } - - this.ExitMyLock(); - } - - /// - /// The downgrade to reader lock. - /// - /// The lock cookie. - public void DowngradeFromWriterLock(ref int lockCookie) - { - this.EnterMyLock(); - Debug.Assert(this.owners == -1, "Downgrading when no writer lock held"); - this.owners = 1; - this.ExitAndWakeUpAppropriateWaiters(); - } - - /// - /// The release reader lock. - /// - public void ReleaseReaderLock() - { - this.EnterMyLock(); - Debug.Assert(this.owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); - --this.owners; - this.ExitAndWakeUpAppropriateWaiters(); - } - - /// - /// The release writer lock. - /// - public void ReleaseWriterLock() - { - this.EnterMyLock(); - Debug.Assert(this.owners == -1, "Calling ReleaseWriterLock when no write lock is held"); - Debug.Assert(this.numUpgradeWaiters > 0); - this.owners++; - this.ExitAndWakeUpAppropriateWaiters(); - } - - /// - /// The upgrade to writer lock. - /// - /// - /// The milliseconds timeout. - /// - /// - /// - public int UpgradeToWriterLock(int millisecondsTimeout) - { - this.EnterMyLock(); - for (;;) - { - Debug.Assert(this.owners > 0, "Upgrading when no reader lock held"); - if (this.owners == 1) - { - // Good case, there is no contention, we are basically done - this.owners = -1; // inidicate we have a writer. - break; - } - - // Drat, we need to wait. Mark that we have waiters and wait. - if (this.upgradeEvent == null) - { - // Create the needed event - this.LazyCreateEvent(ref this.upgradeEvent, false); - continue; // since we left the lock, start over. - } - - if (this.numUpgradeWaiters > 0) - { - this.ExitMyLock(); - throw new InvalidOperationException("UpgradeToWriterLock already in process. Deadlock!"); - } - - this.WaitOnEvent(this.upgradeEvent, ref this.numUpgradeWaiters, millisecondsTimeout); - } - - this.ExitMyLock(); - return 0; - } - - #endregion - -#region Methods - - /// - /// The enter my lock. - /// - private void EnterMyLock() - { - if (Interlocked.CompareExchange(ref this.myLock, 1, 0) != 0) - { - this.EnterMyLockSpin(); - } - } - - /// - /// The enter my lock spin. - /// - private void EnterMyLockSpin() - { - for (int i = 0;; i++) - { -#if !NETCF - if (i < 3 && Environment.ProcessorCount > 1) - { - Thread.SpinWait(20); // Wait a few dozen instructions to let another processor release lock. - } - else - { - Thread.Sleep(0); // Give up my quantum. - } -#else - Thread.Sleep(0); // Give up my quantum. -#endif - - if (Interlocked.CompareExchange(ref this.myLock, 1, 0) == 0) - { - return; - } - } - } - - /// - /// Determines the appropriate events to set, leaves the locks, and sets the events. - /// - private void ExitAndWakeUpAppropriateWaiters() - { - Debug.Assert(this.MyLockHeld); - - if (this.owners == 0 && this.numWriteWaiters > 0) - { - this.ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - this.writeEvent.Set(); // release one writer. - } - else if (this.owners == 1 && this.numUpgradeWaiters != 0) - { - this.ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - this.upgradeEvent.Set(); // release all upgraders (however there can be at most one). - - // two threads upgrading is a guarenteed deadlock, so we throw in that case. - } - else if (this.owners >= 0 && this.numReadWaiters != 0) - { - this.ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - this.readEvent.Set(); // release all readers. - } - else - { - this.ExitMyLock(); - } - } - - /// - /// The exit my lock. - /// - private void ExitMyLock() - { - Debug.Assert(this.myLock != 0, "Exiting spin lock that is not held"); - this.myLock = 0; - } - - /// - /// A routine for lazily creating a event outside the lock (so if errors - /// happen they are outside the lock and that we don't do much work - /// while holding a spin lock). If all goes well, reenter the lock and - /// set 'waitEvent' - /// - /// - /// The wait Event. - /// - /// - /// The make Auto Reset Event. - /// - private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) - { - Debug.Assert(this.MyLockHeld); - Debug.Assert(waitEvent == null); - - this.ExitMyLock(); - EventWaitHandle newEvent; - if (makeAutoResetEvent) - { - newEvent = new AutoResetEvent(false); - } - else - { - newEvent = new ManualResetEvent(false); - } - - this.EnterMyLock(); - waitEvent = newEvent; - } - - /// - /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout. - /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine. - /// - /// - /// The wait Event. - /// - /// - /// The num Waiters. - /// - /// - /// The milliseconds Timeout. - /// - private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout) - { - Debug.Assert(this.MyLockHeld); - - waitEvent.Reset(); - numWaiters++; - - bool waitSuccessful = false; - this.ExitMyLock(); // Do the wait outside of any lock - try - { -#if !NETCF - if (!waitEvent.WaitOne(millisecondsTimeout)) - { - throw new InvalidOperationException("ReaderWriterLock timeout expired"); - } -#else - if (!waitEvent.WaitOne(millisecondsTimeout, false)) - { - throw new InvalidOperationException("ReaderWriterLock timeout expired"); - } -#endif - - waitSuccessful = true; - } - finally - { - this.EnterMyLock(); - --numWaiters; - if (!waitSuccessful) - { - // We are going to throw for some reason. Exit myLock. - this.ExitMyLock(); - } - } - } - -#endregion - } -} -#endif \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Injection/ConstructorInjector.cs b/Telerik.JustMock/AutoMock/Ninject/Injection/ConstructorInjector.cs index fa4f4a99..904e116e 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Injection/ConstructorInjector.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Injection/ConstructorInjector.cs @@ -1,17 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Injection { /// - /// A delegate that can inject values into a constructor. + /// Represents a delegate that can inject values into a constructor. /// + /// The arguments used for the constructor. + /// An object created from the constructor. public delegate object ConstructorInjector(params object[] arguments); } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Injection/DynamicMethodInjectorFactory.cs b/Telerik.JustMock/AutoMock/Ninject/Injection/DynamicMethodInjectorFactory.cs index 9a2050f6..272d2455 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Injection/DynamicMethodInjectorFactory.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Injection/DynamicMethodInjectorFactory.cs @@ -1,27 +1,40 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#if !NO_LCG -#region Using Directives -using System; -using System.Reflection; -using System.Reflection.Emit; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- +#if !NO_LCG namespace Telerik.JustMock.AutoMock.Ninject.Injection { + using System; + using System.Reflection; + using System.Reflection.Emit; + + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Creates injectors for members via s. /// public class DynamicMethodInjectorFactory : NinjectComponent, IInjectorFactory { + private static readonly MethodInfo UnboxPointer = typeof(Pointer).GetMethod("Unbox"); + /// /// Gets or creates an injector for the specified constructor. /// @@ -29,23 +42,21 @@ public class DynamicMethodInjectorFactory : NinjectComponent, IInjectorFactory /// The created injector. public ConstructorInjector Create(ConstructorInfo constructor) { - #if SILVERLIGHT - var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(object), new[] { typeof(object[]) }); - #else - var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(object), new[] { typeof(object[]) }, true); - #endif + var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(object), new[] { typeof(object[]) }, constructor.Module, true); - ILGenerator il = dynamicMethod.GetILGenerator(); + var il = dynamicMethod.GetILGenerator(); EmitLoadMethodArguments(il, constructor); il.Emit(OpCodes.Newobj, constructor); if (constructor.ReflectedType.IsValueType) + { il.Emit(OpCodes.Box, constructor.ReflectedType); + } il.Emit(OpCodes.Ret); - return (ConstructorInjector) dynamicMethod.CreateDelegate(typeof(ConstructorInjector)); + return (ConstructorInjector)dynamicMethod.CreateDelegate(typeof(ConstructorInjector)); } /// @@ -55,13 +66,13 @@ public ConstructorInjector Create(ConstructorInfo constructor) /// The created injector. public PropertyInjector Create(PropertyInfo property) { - #if NO_SKIP_VISIBILITY - var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }); - #else - var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }, true); - #endif - - ILGenerator il = dynamicMethod.GetILGenerator(); +#if NO_SKIP_VISIBILITY + var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object), property.Module }); +#else + var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }, property.Module, true); +#endif + + var il = dynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); EmitUnboxOrCast(il, property.DeclaringType); @@ -69,16 +80,12 @@ public PropertyInjector Create(PropertyInfo property) il.Emit(OpCodes.Ldarg_1); EmitUnboxOrCast(il, property.PropertyType); - #if !SILVERLIGHT - bool injectNonPublic = Settings.InjectNonPublic; - #else - const bool injectNonPublic = false; - #endif // !SILVERLIGHT + var injectNonPublic = this.Settings.InjectNonPublic; EmitMethodCall(il, property.GetSetMethod(injectNonPublic)); il.Emit(OpCodes.Ret); - return (PropertyInjector) dynamicMethod.CreateDelegate(typeof(PropertyInjector)); + return (PropertyInjector)dynamicMethod.CreateDelegate(typeof(PropertyInjector)); } /// @@ -88,13 +95,13 @@ public PropertyInjector Create(PropertyInfo property) /// The created injector. public MethodInjector Create(MethodInfo method) { - #if NO_SKIP_VISIBILITY - var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object[]) }); - #else - var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object[]) }, true); - #endif +#if NO_SKIP_VISIBILITY + var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object[]) }, method.Module); +#else + var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object[]) }, method.Module, true); +#endif - ILGenerator il = dynamicMethod.GetILGenerator(); + var il = dynamicMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); EmitUnboxOrCast(il, method.DeclaringType); @@ -103,18 +110,20 @@ public MethodInjector Create(MethodInfo method) EmitMethodCall(il, method); if (method.ReturnType != typeof(void)) + { il.Emit(OpCodes.Pop); + } il.Emit(OpCodes.Ret); - return (MethodInjector) dynamicMethod.CreateDelegate(typeof(MethodInjector)); + return (MethodInjector)dynamicMethod.CreateDelegate(typeof(MethodInjector)); } private static void EmitLoadMethodArguments(ILGenerator il, MethodBase targetMethod) { - ParameterInfo[] parameters = targetMethod.GetParameters(); - OpCode ldargOpcode = targetMethod is ConstructorInfo ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1; - + var parameters = targetMethod.GetParameters(); + var ldargOpcode = targetMethod is ConstructorInfo ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1; + for (int idx = 0; idx < parameters.Length; idx++) { il.Emit(ldargOpcode); @@ -127,14 +136,24 @@ private static void EmitLoadMethodArguments(ILGenerator il, MethodBase targetMet private static void EmitMethodCall(ILGenerator il, MethodInfo method) { - OpCode opCode = method.IsFinal ? OpCodes.Call : OpCodes.Callvirt; + var opCode = method.IsFinal ? OpCodes.Call : OpCodes.Callvirt; il.Emit(opCode, method); } private static void EmitUnboxOrCast(ILGenerator il, Type type) { - OpCode opCode = type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass; - il.Emit(opCode, type); + if (type.IsValueType) + { + il.Emit(OpCodes.Unbox_Any, type); + } + else if (type.IsPointer) + { + il.Emit(OpCodes.Call, UnboxPointer); + } + else + { + il.Emit(OpCodes.Castclass, type); + } } private static string GetAnonymousMethodName() diff --git a/Telerik.JustMock/AutoMock/Ninject/Injection/IInjectorFactory.cs b/Telerik.JustMock/AutoMock/Ninject/Injection/IInjectorFactory.cs index e8936929..b0c50c83 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Injection/IInjectorFactory.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Injection/IInjectorFactory.cs @@ -1,20 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Injection { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Creates injectors from members. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Injection/MethodInjector.cs b/Telerik.JustMock/AutoMock/Ninject/Injection/MethodInjector.cs index 98e54476..a419a377 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Injection/MethodInjector.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Injection/MethodInjector.cs @@ -1,16 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Injection { /// - /// A delegate that can inject values into a method. + /// Represents a delegate that can inject values into a method. /// + /// The method info. + /// The arguments used for the method. public delegate void MethodInjector(object target, params object[] arguments); } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Injection/PropertyInjector.cs b/Telerik.JustMock/AutoMock/Ninject/Injection/PropertyInjector.cs index 30fed456..368a38cb 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Injection/PropertyInjector.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Injection/PropertyInjector.cs @@ -1,16 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + namespace Telerik.JustMock.AutoMock.Ninject.Injection { /// - /// A delegate that can inject values into a property. + /// Represents a delegate that can inject values into a property. /// + /// The property info. + /// The value to be injected to the property. public delegate void PropertyInjector(object target, object value); } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Injection/ReflectionInjectorFactory.cs b/Telerik.JustMock/AutoMock/Ninject/Injection/ReflectionInjectorFactory.cs index d9e797b0..63ef58cd 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Injection/ReflectionInjectorFactory.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Injection/ReflectionInjectorFactory.cs @@ -1,20 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Injection { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Creates injectors from members via reflective invocation. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/KernelBase.cs b/Telerik.JustMock/AutoMock/Ninject/KernelBase.cs index a5432cee..0febf571 100644 --- a/Telerik.JustMock/AutoMock/Ninject/KernelBase.cs +++ b/Telerik.JustMock/AutoMock/Ninject/KernelBase.cs @@ -1,10 +1,23 @@ -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { @@ -12,6 +25,7 @@ namespace Telerik.JustMock.AutoMock.Ninject using System.Collections.Generic; using System.Linq; using System.Reflection; + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Activation.Blocks; using Telerik.JustMock.AutoMock.Ninject.Activation.Caching; @@ -31,17 +45,16 @@ namespace Telerik.JustMock.AutoMock.Ninject /// public abstract class KernelBase : BindingRoot, IKernel { - /// - /// Lock used when adding missing bindings. - /// - protected readonly object HandleMissingBindingLockObject = new object(); - + private readonly object handleMissingBindingLockObject = new object(); + private readonly Multimap bindings = new Multimap(); - private readonly Multimap bindingCache = new Multimap(); + private readonly Dictionary> bindingCache = new Dictionary>(); private readonly Dictionary modules = new Dictionary(); + private readonly IBindingPrecedenceComparer bindingPrecedenceComparer; + /// /// Initializes a new instance of the class. /// @@ -88,15 +101,16 @@ protected KernelBase(IComponentContainer components, INinjectSettings settings, this.AddComponents(); + this.bindingPrecedenceComparer = this.Components.Get(); + this.Bind().ToConstant(this).InTransientScope(); this.Bind().ToConstant(this).InTransientScope(); -#if !NO_ASSEMBLY_SCANNING if (this.Settings.LoadExtensions) { this.Load(this.Settings.ExtensionSearchPatterns); } -#endif + this.Load(modules); } @@ -113,9 +127,10 @@ protected KernelBase(IComponentContainer components, INinjectSettings settings, /// /// Releases resources held by the object. /// + /// True if called manually, otherwise by GC. public override void Dispose(bool disposing) { - if (disposing && !IsDisposed) + if (disposing && !this.IsDisposed) { if (this.Components != null) { @@ -168,7 +183,9 @@ public override void RemoveBinding(IBinding binding) this.bindings.Remove(binding.Service, binding); lock (this.bindingCache) + { this.bindingCache.Clear(); + } } /// @@ -206,10 +223,8 @@ public void Load(IEnumerable m) { throw new NotSupportedException(ExceptionFormatter.ModulesWithNullOrEmptyNamesAreNotSupported()); } - - INinjectModule existingModule; - if (this.modules.TryGetValue(module.Name, out existingModule)) + if (this.modules.TryGetValue(module.Name, out INinjectModule existingModule)) { throw new NotSupportedException(ExceptionFormatter.ModuleWithSameNameIsAlreadyLoaded(module, existingModule)); } @@ -225,7 +240,6 @@ public void Load(IEnumerable m) } } -#if !NO_ASSEMBLY_SCANNING /// /// Loads modules from the files that match the specified pattern(s). /// @@ -244,7 +258,6 @@ public void Load(IEnumerable assemblies) { this.Load(assemblies.SelectMany(asm => asm.GetNinjectModules())); } -#endif //!NO_ASSEMBLY_SCANNING /// /// Unloads the plugin with the specified name. @@ -254,9 +267,7 @@ public void Unload(string name) { Ensure.ArgumentNotNullOrEmpty(name, "name"); - INinjectModule module; - - if (!this.modules.TryGetValue(name, out module)) + if (!this.modules.TryGetValue(name, out INinjectModule module)) { throw new NotSupportedException(ExceptionFormatter.NoModuleLoadedWithTheSpecifiedName(name)); } @@ -337,57 +348,7 @@ public virtual bool CanResolve(IRequest request, bool ignoreImplicitBindings) /// An enumerator of instances that match the request. public virtual IEnumerable Resolve(IRequest request) { - Ensure.ArgumentNotNull(request, "request"); - - var bindingPrecedenceComparer = this.GetBindingPrecedenceComparer(); - var resolveBindings = Enumerable.Empty(); - - if (this.CanResolve(request) || this.HandleMissingBinding(request)) - { - resolveBindings = this.GetBindings(request.Service) - .Where(this.SatifiesRequest(request)); - - } - - if (!resolveBindings.Any()) - { - if (request.IsOptional) - { - return Enumerable.Empty(); - } - - throw new ActivationException(ExceptionFormatter.CouldNotResolveBinding(request)); - } - - if (request.IsUnique) - { - resolveBindings = resolveBindings.OrderByDescending(b => b, bindingPrecedenceComparer).ToList(); - var model = resolveBindings.First(); // the type (conditonal, implicit, etc) of binding we'll return - resolveBindings = - resolveBindings.TakeWhile(binding => bindingPrecedenceComparer.Compare(binding, model) == 0); - - if (resolveBindings.Count() > 1) - { - if (request.IsOptional) - { - return Enumerable.Empty(); - } - - var formattedBindings = - from binding in resolveBindings - let context = this.CreateContext(request, binding) - select binding.Format(context); - throw new ActivationException(ExceptionFormatter.CouldNotUniquelyResolveBinding(request, formattedBindings.ToArray())); - } - } - - if(resolveBindings.Any(binding => !binding.IsImplicit)) - { - resolveBindings = resolveBindings.Where(binding => !binding.IsImplicit); - } - - return resolveBindings - .Select(binding => this.CreateContext(request, binding).Resolve()); + return this.Resolve(request, true, false); } /// @@ -431,9 +392,12 @@ public virtual IEnumerable GetBindings(Type service) { var resolvers = this.Components.GetAll(); - resolvers + var compiledBindings = resolvers .SelectMany(resolver => resolver.Resolve(this.bindings, service)) - .Map(binding => this.bindingCache.Add(service, binding)); + .OrderByDescending(b => b, this.bindingPrecedenceComparer).ToList(); + this.bindingCache.Add(service, compiledBindings); + + return compiledBindings; } return this.bindingCache[service]; @@ -441,12 +405,15 @@ public virtual IEnumerable GetBindings(Type service) } /// - /// Returns an IComparer that is used to determine resolution precedence. + /// Gets the service object of the specified type. /// - /// An IComparer that is used to determine resolution precedence. - protected virtual IComparer GetBindingPrecedenceComparer() + /// The service type. + /// The service object + object IServiceProvider.GetService(Type service) { - return new BindingPrecedenceComparer(); + return this.Settings.ThrowOnGetServiceNotFound + ? this.Get(service) + : this.TryGet(service); } /// @@ -464,17 +431,6 @@ protected virtual Func SatifiesRequest(IRequest request) /// protected abstract void AddComponents(); - /// - /// Attempts to handle a missing binding for a service. - /// - /// The service. - /// True if the missing binding can be handled; otherwise false. - [Obsolete] - protected virtual bool HandleMissingBinding(Type service) - { - return false; - } - /// /// Attempts to handle a missing binding for a request. /// @@ -484,15 +440,8 @@ protected virtual bool HandleMissingBinding(IRequest request) { Ensure.ArgumentNotNull(request, "request"); -#pragma warning disable 612,618 - if (this.HandleMissingBinding(request.Service)) - { - return true; - } -#pragma warning restore 612,618 - var components = this.Components.GetAll(); - + // Take the first set of bindings that resolve. var bindings = components .Select(c => c.Resolve(this.bindings, request).ToList()) @@ -503,7 +452,7 @@ protected virtual bool HandleMissingBinding(IRequest request) return false; } - lock (this.HandleMissingBindingLockObject) + lock (this.handleMissingBindingLockObject) { if (!this.CanResolve(request)) { @@ -515,21 +464,6 @@ protected virtual bool HandleMissingBinding(IRequest request) return true; } - /// - /// Returns a value indicating whether the specified service is self-bindable. - /// - /// The service. - /// if the type is self-bindable; otherwise . - [Obsolete] - protected virtual bool TypeIsSelfBindable(Type service) - { - return !service.IsInterface - && !service.IsAbstract - && !service.IsValueType - && service != typeof(string) - && !service.ContainsGenericParameters; - } - /// /// Creates a context for the specified request and binding. /// @@ -544,46 +478,122 @@ protected virtual IContext CreateContext(IRequest request, IBinding binding) return new Context(this, request, binding, this.Components.Get(), this.Components.Get(), this.Components.Get()); } - private void AddBindings(IEnumerable bindings) + private IEnumerable Resolve(IRequest request, bool handleMissingBindings, bool filterImplicitBindings) { - bindings.Map(binding => this.bindings.Add(binding.Service, binding)); + void UpdateRequest(Type service) + { + if (request.ParentRequest == null) + { + request = this.CreateRequest(service, null, request.Parameters.Where(p => p.ShouldInherit), true, false); + } + else + { + request = request.ParentRequest.CreateChild(service, request.ParentContext, request.Target); + request.IsOptional = true; + } + } - lock (this.bindingCache) - this.bindingCache.Clear(); - } + if (request.Service.IsArray) + { + var service = request.Service.GetElementType(); - object IServiceProvider.GetService(Type service) - { - return this.Get(service); - } + UpdateRequest(service); - private class BindingPrecedenceComparer : IComparer - { - public int Compare(IBinding x, IBinding y) + return new[] { this.Resolve(request, false, true).CastSlow(service).ToArraySlow(service) }; + } + + if (request.Service.IsGenericType) + { + var gtd = request.Service.GetGenericTypeDefinition(); + + if (gtd == typeof(List<>) || gtd == typeof(IList<>) || gtd == typeof(ICollection<>)) + { + var service = request.Service.GenericTypeArguments[0]; + + UpdateRequest(service); + + return new[] { this.Resolve(request, false, true).CastSlow(service).ToListSlow(service) }; + } + + if (gtd == typeof(IEnumerable<>)) + { + var service = request.Service.GenericTypeArguments[0]; + + UpdateRequest(service); + + return new[] { this.Resolve(request, false, true).CastSlow(service) }; + } + } + + var satisfiedBindings = this.GetBindings(request.Service) + .Where(this.SatifiesRequest(request)); + + if (filterImplicitBindings) + { + satisfiedBindings = satisfiedBindings.Where(binding => binding.IsImplicit == false); + } + + var satisfiedBindingEnumerator = satisfiedBindings.GetEnumerator(); + + if (!satisfiedBindingEnumerator.MoveNext()) + { + if (handleMissingBindings && this.HandleMissingBinding(request)) + { + return this.Resolve(request, false, false); + } + + if (request.IsOptional) + { + return Enumerable.Empty(); + } + + throw new ActivationException(ExceptionFormatter.CouldNotResolveBinding(request)); + } + + if (request.IsUnique) { - if (x == y) + var selectedBinding = satisfiedBindingEnumerator.Current; + + if (satisfiedBindingEnumerator.MoveNext() && + this.bindingPrecedenceComparer.Compare(selectedBinding, satisfiedBindingEnumerator.Current) == 0) { - return 0; + if (request.IsOptional && !request.ForceUnique) + { + return Enumerable.Empty(); + } + + var formattedBindings = + from binding in satisfiedBindings + let context = this.CreateContext(request, binding) + select binding.Format(context); + + throw new ActivationException(ExceptionFormatter.CouldNotUniquelyResolveBinding( + request, + formattedBindings.ToArray())); + } + + return new[] { this.CreateContext(request, selectedBinding).Resolve() }; + } + else + { + if (satisfiedBindings.Any(binding => !binding.IsImplicit)) + { + satisfiedBindings = satisfiedBindings.Where(binding => !binding.IsImplicit); } - // Each function represents a level of precedence. - var funcs = new List> - { - b => b != null, // null bindings should never happen, but just in case - b => b.IsConditional, // conditional bindings > unconditional - b => !b.Service.ContainsGenericParameters, // closed generics > open generics - b => !b.IsImplicit, // explicit bindings > implicit - }; - - var q = from func in funcs - let xVal = func(x) - where xVal != func(y) - select xVal ? 1 : -1; - - // returns the value of the first function that represents a difference - // between the bindings, or else returns 0 (equal) - return q.FirstOrDefault(); + return satisfiedBindings + .Select(binding => this.CreateContext(request, binding).Resolve()); + } + } + + private void AddBindings(IEnumerable bindings) + { + bindings.Map(binding => this.bindings.Add(binding.Service, binding)); + + lock (this.bindingCache) + { + this.bindingCache.Clear(); } } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/AssemblyNameRetriever.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/AssemblyNameRetriever.cs index 56e1d835..ec4584f9 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/AssemblyNameRetriever.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/AssemblyNameRetriever.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,9 +17,8 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- -#if !NO_ASSEMBLY_SCANNING namespace Telerik.JustMock.AutoMock.Ninject.Modules { using System; @@ -43,7 +42,7 @@ public class AssemblyNameRetriever : NinjectComponent, IAssemblyNameRetriever /// All assembly names of the assemblies in the given files that match the filter. public IEnumerable GetAssemblyNames(IEnumerable filenames, Predicate filter) { -#if !NO_APPDOMAIN_ISOLATION +#if !NO_ASSEMBLY_SCANNING var assemblyCheckerType = typeof(AssemblyChecker); var temporaryDomain = CreateTemporaryAppDomain(); try @@ -60,10 +59,10 @@ public IEnumerable GetAssemblyNames(IEnumerable filenames, } #else return new AssemblyChecker().GetAssemblyNames(filenames, filter); -#endif // !NO_APPDOMAIN_ISOLATION +#endif } -#if !NO_APPDOMAIN_ISOLATION +#if !NO_ASSEMBLY_SCANNING /// /// Creates a temporary app domain. /// @@ -75,7 +74,7 @@ private static AppDomain CreateTemporaryAppDomain() AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation); } -#endif // !NO_APPDOMAIN_ISOLATION +#endif /// /// This class is loaded into the temporary appdomain to load and check if the assemblies match the filter. @@ -98,20 +97,33 @@ public IEnumerable GetAssemblyNames(IEnumerable filenames, { try { - // .NET Core -> creates a new (anonymous) load context to load the assembly into. - // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/assemblyloadcontext.md#assembly-load-apis-and-loadcontext - assembly = Assembly.LoadFile(filename); + assembly = Assembly.LoadFrom(filename); } catch (BadImageFormatException) { continue; } - - if (filter(assembly)) + } + else + { + try { - result.Add(assembly.GetName(false)); + assembly = Assembly.Load(filename); + } + catch (FileLoadException) + { + continue; + } + catch (FileNotFoundException) + { + continue; } } + + if (filter(assembly)) + { + result.Add(assembly.GetName(false)); + } } return result; @@ -119,4 +131,3 @@ public IEnumerable GetAssemblyNames(IEnumerable filenames, } } } -#endif diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/CompiledModuleLoaderPlugin.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/CompiledModuleLoaderPlugin.cs index fba18a39..1423c8b9 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/CompiledModuleLoaderPlugin.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/CompiledModuleLoaderPlugin.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,9 +17,8 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- -#if !NO_ASSEMBLY_SCANNING namespace Telerik.JustMock.AutoMock.Ninject.Modules { using System.Collections.Generic; @@ -31,21 +28,21 @@ namespace Telerik.JustMock.AutoMock.Ninject.Modules using Telerik.JustMock.AutoMock.Ninject.Components; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; - + /// /// Loads modules from compiled assemblies. /// public class CompiledModuleLoaderPlugin : NinjectComponent, IModuleLoaderPlugin { /// - /// The assembly name retriever. + /// The file extensions that are supported. /// - private readonly IAssemblyNameRetriever assemblyNameRetriever; + private static readonly string[] Extensions = { ".dll" }; /// - /// The file extensions that are supported. + /// The assembly name retriever. /// - private static readonly string[] Extensions = new[] { ".dll" }; + private readonly IAssemblyNameRetriever assemblyNameRetriever; /// /// Initializes a new instance of the class. @@ -55,6 +52,8 @@ public class CompiledModuleLoaderPlugin : NinjectComponent, IModuleLoaderPlugin public CompiledModuleLoaderPlugin(IKernel kernel, IAssemblyNameRetriever assemblyNameRetriever) { Ensure.ArgumentNotNull(kernel, "kernel"); + Ensure.ArgumentNotNull(assemblyNameRetriever, "assemblyNameRetriever"); + this.Kernel = kernel; this.assemblyNameRetriever = assemblyNameRetriever; } @@ -82,5 +81,4 @@ public void LoadModules(IEnumerable filenames) this.Kernel.Load(assembliesWithModules.Select(asm => Assembly.Load(asm))); } } -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/IAssemblyNameRetriever.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/IAssemblyNameRetriever.cs index f0615207..3201ba63 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/IAssemblyNameRetriever.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/IAssemblyNameRetriever.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,9 +17,8 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- -#if !NO_ASSEMBLY_SCANNING namespace Telerik.JustMock.AutoMock.Ninject.Modules { using System; @@ -41,5 +40,4 @@ public interface IAssemblyNameRetriever : INinjectComponent /// All assembly names of the assemblies in the given files that match the filter. IEnumerable GetAssemblyNames(IEnumerable filenames, Predicate filter); } -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoader.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoader.cs index ed7131a7..9142ebba 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoader.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoader.cs @@ -1,21 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#if !SILVERLIGHT -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Modules { + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Finds modules defined in external files. /// @@ -27,5 +36,4 @@ public interface IModuleLoader : INinjectComponent /// The patterns to search. void LoadModules(IEnumerable patterns); } -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoaderPlugin.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoaderPlugin.cs index c04f8c7b..b1044eca 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoaderPlugin.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/IModuleLoaderPlugin.cs @@ -1,21 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#if !SILVERLIGHT -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Modules { + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Loads modules at runtime by searching external files. /// @@ -32,5 +41,4 @@ public interface IModuleLoaderPlugin : INinjectComponent /// The names of the files to load modules from. void LoadModules(IEnumerable filenames); } -} -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/INinjectModule.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/INinjectModule.cs index d66516bc..b163b031 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/INinjectModule.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/INinjectModule.cs @@ -1,20 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Syntax; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Modules { + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + /// /// A pluggable unit that can be loaded into an . /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/ModuleLoader.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/ModuleLoader.cs index cf1f10d4..4c0e39a1 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/ModuleLoader.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/ModuleLoader.cs @@ -1,34 +1,39 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#if !NO_ASSEMBLY_SCANNING -#region Using Directives -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Modules { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + /// /// Automatically finds and loads modules from assemblies. /// public class ModuleLoader : NinjectComponent, IModuleLoader { - /// - /// Gets or sets the kernel into which modules will be loaded. - /// - public IKernel Kernel { get; private set; } - /// /// Initializes a new instance of the class. /// @@ -36,16 +41,22 @@ public class ModuleLoader : NinjectComponent, IModuleLoader public ModuleLoader(IKernel kernel) { Ensure.ArgumentNotNull(kernel, "kernel"); - Kernel = kernel; + + this.Kernel = kernel; } + /// + /// Gets the kernel into which modules will be loaded. + /// + public IKernel Kernel { get; private set; } + /// /// Loads any modules found in the files that match the specified patterns. /// /// The patterns to search. public void LoadModules(IEnumerable patterns) { - var plugins = Kernel.Components.GetAll(); + var plugins = this.Kernel.Components.GetAll(); var fileGroups = patterns .SelectMany(pattern => GetFilesMatchingPattern(pattern)) @@ -53,11 +64,13 @@ public void LoadModules(IEnumerable patterns) foreach (var fileGroup in fileGroups) { - string extension = fileGroup.Key; - IModuleLoaderPlugin plugin = plugins.Where(p => p.SupportedExtensions.Contains(extension)).FirstOrDefault(); + var extension = fileGroup.Key; + var plugin = plugins.Where(p => p.SupportedExtensions.Contains(extension)).FirstOrDefault(); if (plugin != null) + { plugin.LoadModules(fileGroup); + } } } @@ -71,7 +84,8 @@ private static IEnumerable NormalizePaths(string path) { return Path.IsPathRooted(path) ? new[] { Path.GetFullPath(path) } - : GetBaseDirectories().Select(baseDirectory => Path.Combine(baseDirectory, path)); + : GetBaseDirectories().Select(baseDirectory => Path.Combine(baseDirectory, path)) + .Where(Directory.Exists); } private static IEnumerable GetBaseDirectories() @@ -79,11 +93,10 @@ private static IEnumerable GetBaseDirectories() var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var searchPath = AppDomain.CurrentDomain.RelativeSearchPath; - return String.IsNullOrEmpty(searchPath) - ? new[] {baseDirectory} - : searchPath.Split(new[] {Path.PathSeparator}, StringSplitOptions.RemoveEmptyEntries) + return string.IsNullOrEmpty(searchPath) + ? new[] { baseDirectory } + : searchPath.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries) .Select(path => Path.Combine(baseDirectory, path)); } } } -#endif //!NO_ASSEMBLY_SCANNING \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Modules/NinjectModule.cs b/Telerik.JustMock/AutoMock/Ninject/Modules/NinjectModule.cs index c74859dd..a61bafde 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Modules/NinjectModule.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Modules/NinjectModule.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Modules { @@ -54,7 +52,7 @@ protected NinjectModule() /// public virtual string Name { - get { return GetType().FullName; } + get { return this.GetType().FullName; } } /// @@ -73,7 +71,7 @@ protected override IKernel KernelInstance return this.Kernel; } } - + /// /// Called when the module is loaded into a kernel. /// @@ -81,6 +79,7 @@ protected override IKernel KernelInstance public void OnLoad(IKernel kernel) { Ensure.ArgumentNotNull(kernel, "kernel"); + this.Kernel = kernel; this.Load(); } @@ -92,6 +91,7 @@ public void OnLoad(IKernel kernel) public void OnUnload(IKernel kernel) { Ensure.ArgumentNotNull(kernel, "kernel"); + this.Unload(); this.Bindings.Map(this.Kernel.RemoveBinding); this.Kernel = null; diff --git a/Telerik.JustMock/AutoMock/Ninject/NinjectSettings.cs b/Telerik.JustMock/AutoMock/Ninject/NinjectSettings.cs index 894c198e..478efbad 100644 --- a/Telerik.JustMock/AutoMock/Ninject/NinjectSettings.cs +++ b/Telerik.JustMock/AutoMock/Ninject/NinjectSettings.cs @@ -1,36 +1,46 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + /// /// Contains configuration options for Ninject. /// public class NinjectSettings : INinjectSettings { - private readonly Dictionary _values = new Dictionary(); + private readonly Dictionary values = new Dictionary(); /// /// Gets or sets the attribute that indicates that a member should be injected. /// public Type InjectAttribute { - get { return Get("InjectAttribute", typeof(InjectAttribute)); } - set { Set("InjectAttribute", value); } + get { return this.Get("InjectAttribute", typeof(InjectAttribute)); } + set { this.Set("InjectAttribute", value); } } /// @@ -38,8 +48,8 @@ public Type InjectAttribute /// public TimeSpan CachePruningInterval { - get { return Get("CachePruningInterval", TimeSpan.FromSeconds(30)); } - set { Set("CachePruningInterval", value); } + get { return this.Get("CachePruningInterval", TimeSpan.FromSeconds(30)); } + set { this.Set("CachePruningInterval", value); } } /// @@ -47,18 +57,17 @@ public TimeSpan CachePruningInterval /// public Func DefaultScopeCallback { - get { return Get("DefaultScopeCallback", StandardScopeCallbacks.Transient); } - set { Set("DefaultScopeCallback", value); } + get { return this.Get("DefaultScopeCallback", StandardScopeCallbacks.Transient); } + set { this.Set("DefaultScopeCallback", value); } } - #if !NO_ASSEMBLY_SCANNING /// /// Gets or sets a value indicating whether the kernel should automatically load extensions at startup. /// public bool LoadExtensions { - get { return Get("LoadExtensions", true); } - set { Set("LoadExtensions", value); } + get { return this.Get("LoadExtensions", true); } + set { this.Set("LoadExtensions", value); } } /// @@ -66,38 +75,36 @@ public bool LoadExtensions /// public string[] ExtensionSearchPatterns { - get { return Get("ExtensionSearchPatterns", new [] { "Ninject.Extensions.*.dll", "Ninject.Web*.dll" }); } - set { Set("ExtensionSearchPatterns", value); } + get { return this.Get("ExtensionSearchPatterns", new[] { "Ninject.Extensions.*.dll", "Ninject.Web*.dll" }); } + set { this.Set("ExtensionSearchPatterns", value); } } - #endif //!NO_ASSEMBLY_SCANNING - #if !NO_LCG +#if !NO_LCG /// - /// Gets a value indicating whether Ninject should use reflection-based injection instead of + /// Gets or sets a value indicating whether Ninject should use reflection-based injection instead of /// the (usually faster) lightweight code generation system. /// public bool UseReflectionBasedInjection { - get { return Get("UseReflectionBasedInjection", false); } - set { Set("UseReflectionBasedInjection", value); } + get { return this.Get("UseReflectionBasedInjection", false); } + set { this.Set("UseReflectionBasedInjection", value); } } - #endif //!NO_LCG +#endif //!NO_LCG - #if !SILVERLIGHT /// - /// Gets a value indicating whether Ninject should inject non public members. + /// Gets or sets a value indicating whether Ninject should inject non public members. /// public bool InjectNonPublic { - get { return Get("InjectNonPublic", false); } - set { Set("InjectNonPublic", value); } + get { return this.Get("InjectNonPublic", false); } + set { this.Set("InjectNonPublic", value); } } /// - /// Gets a value indicating whether Ninject should inject private properties of base classes. + /// Gets or sets a value indicating whether Ninject should inject private properties of base classes. /// /// - /// Activating this setting has an impact on the performance. It is recomended not + /// Activating this setting has an impact on the performance. It is recommended not /// to use this feature and use constructor injection instead. /// public bool InjectParentPrivateProperties @@ -105,7 +112,6 @@ public bool InjectParentPrivateProperties get { return this.Get("InjectParentPrivateProperties", false); } set { this.Set("InjectParentPrivateProperties", value); } } - #endif //!SILVERLIGHT /// /// Gets or sets a value indicating whether the activation cache is disabled. @@ -115,7 +121,7 @@ public bool InjectParentPrivateProperties /// Bind{IA}().ToMethod(ctx => kernel.Get{IA}(); /// /// - /// true if activation cache is disabled; otherwise, false. + /// true if activation cache is disabled; otherwise, false. /// public bool ActivationCacheDisabled { @@ -128,7 +134,7 @@ public bool ActivationCacheDisabled /// By default this is disabled and whenever a provider returns null an exception is thrown. /// /// - /// true if null is allowed as injected value otherwise false. + /// true if null is allowed as injected value otherwise false. /// public bool AllowNullInjection { @@ -136,6 +142,18 @@ public bool AllowNullInjection set { this.Set("AllowNullInjection", value); } } + /// + /// Gets or sets a value indicating whether the old (<= 3.3.4) behavior of + /// should be used which throws an exception if the requested service cannot be found. Note that the documentation + /// of that method https://docs.microsoft.com/en-us/dotnet/api/system.iserviceprovider.getservice?view=netframework-4.6.2 + /// states that the method should return if there is no such service. + /// + public bool ThrowOnGetServiceNotFound + { + get { return this.Get("ThrowOnGetServiceNotFound", false); } + set { this.Set("ThrowOnGetServiceNotFound", value); } + } + /// /// Gets the value for the specified key. /// @@ -145,8 +163,7 @@ public bool AllowNullInjection /// The value, or the default value if none was found. public T Get(string key, T defaultValue) { - object value; - return _values.TryGetValue(key, out value) ? (T)value : defaultValue; + return this.values.TryGetValue(key, out object value) ? (T)value : defaultValue; } /// @@ -156,7 +173,7 @@ public T Get(string key, T defaultValue) /// The setting's value. public void Set(string key, object value) { - _values[key] = value; + this.values[key] = value; } } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/ConstructorArgument.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/ConstructorArgument.cs index 0a853c79..3b07f685 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/ConstructorArgument.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/ConstructorArgument.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { @@ -102,7 +100,7 @@ public ConstructorArgument(string name, Func valueCal /// The context. /// The target. /// - /// Tre if the parameter applies in the specified context to the specified target. + /// True if the parameter applies in the specified context to the specified target. /// /// /// Only one parameter may return true. diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/IConstructorArgument.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/IConstructorArgument.cs index 38c2c6e0..bc2f09cc 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/IConstructorArgument.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/IConstructorArgument.cs @@ -1,4 +1,25 @@ -namespace Telerik.JustMock.AutoMock.Ninject.Parameters +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject.Parameters { using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; @@ -16,7 +37,7 @@ public interface IConstructorArgument : IParameter /// /// The context. /// The target. - /// Tre if the parameter applies in the specified context to the specified target. + /// True if the parameter applies in the specified context to the specified target. bool AppliesToTarget(IContext context, ITarget target); } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/IParameter.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/IParameter.cs index 741271f9..09a0bbe7 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/IParameter.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/IParameter.cs @@ -1,19 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Activation; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/IPropertyValue.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/IPropertyValue.cs index d7436908..3f698ec9 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/IPropertyValue.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/IPropertyValue.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2013 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { @@ -25,6 +25,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Parameters /// Overrides the injected value of a property. /// public interface IPropertyValue : IParameter - { + { } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/Parameter.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/Parameter.cs index 942919b0..f942a5c1 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/Parameter.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/Parameter.cs @@ -1,20 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; /// @@ -22,28 +32,16 @@ namespace Telerik.JustMock.AutoMock.Ninject.Parameters /// public class Parameter : IParameter { - /// - /// Gets the name of the parameter. - /// - public string Name { get; private set; } - - /// - /// Gets a value indicating whether the parameter should be inherited into child requests. - /// - public bool ShouldInherit { get; private set; } - - /// - /// Gets or sets the callback that will be triggered to get the parameter's value. - /// - public Func ValueCallback { get; internal set; } - /// /// Initializes a new instance of the class. /// /// The name of the parameter. /// The value of the parameter. /// Whether the parameter should be inherited into child requests. - public Parameter(string name, object value, bool shouldInherit) : this(name, (ctx, target) => value, shouldInherit) { } + public Parameter(string name, object value, bool shouldInherit) + : this(name, (ctx, target) => value, shouldInherit) + { + } /// /// Initializes a new instance of the class. @@ -56,9 +54,9 @@ public Parameter(string name, Func valueCallback, bool shouldI Ensure.ArgumentNotNullOrEmpty(name, "name"); Ensure.ArgumentNotNull(valueCallback, "valueCallback"); - Name = name; - ValueCallback = (ctx, target) => valueCallback(ctx); - ShouldInherit = shouldInherit; + this.Name = name; + this.ValueCallback = (ctx, target) => valueCallback(ctx); + this.ShouldInherit = shouldInherit; } /// @@ -72,11 +70,26 @@ public Parameter(string name, Func valueCallback, boo Ensure.ArgumentNotNullOrEmpty(name, "name"); Ensure.ArgumentNotNull(valueCallback, "valueCallback"); - Name = name; - ValueCallback = valueCallback; - ShouldInherit = shouldInherit; + this.Name = name; + this.ValueCallback = valueCallback; + this.ShouldInherit = shouldInherit; } - + + /// + /// Gets the name of the parameter. + /// + public string Name { get; private set; } + + /// + /// Gets a value indicating whether the parameter should be inherited into child requests. + /// + public bool ShouldInherit { get; private set; } + + /// + /// Gets the callback that will be triggered to get the parameter's value. + /// + public Func ValueCallback { get; internal set; } + /// /// Gets the value for the parameter within the specified context. /// @@ -86,7 +99,8 @@ public Parameter(string name, Func valueCallback, boo public object GetValue(IContext context, ITarget target) { Ensure.ArgumentNotNull(context, "context"); - return ValueCallback(context, target); + + return this.ValueCallback(context, target); } /// @@ -97,7 +111,7 @@ public object GetValue(IContext context, ITarget target) public override bool Equals(object obj) { var parameter = obj as IParameter; - return parameter != null ? Equals(parameter) : base.Equals(obj); + return parameter != null ? this.Equals(parameter) : base.Equals(obj); } /// @@ -106,7 +120,7 @@ public override bool Equals(object obj) /// A hash code for the object. public override int GetHashCode() { - return GetType().GetHashCode() ^ Name.GetHashCode(); + return this.GetType().GetHashCode() ^ this.Name.GetHashCode(); } /// @@ -116,7 +130,7 @@ public override int GetHashCode() /// True if the objects are equal; otherwise false public bool Equals(IParameter other) { - return other.GetType() == GetType() && other.Name.Equals(Name); + return other.GetType() == this.GetType() && other.Name.Equals(this.Name); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/PropertyValue.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/PropertyValue.cs index b0905048..2ac164d5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/PropertyValue.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/PropertyValue.cs @@ -1,19 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Activation; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { + using System; + + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; /// @@ -26,20 +36,29 @@ public class PropertyValue : Parameter, IPropertyValue /// /// The name of the property to override. /// The value to inject into the property. - public PropertyValue(string name, object value) : base(name, value, false) { } + public PropertyValue(string name, object value) + : base(name, value, false) + { + } /// /// Initializes a new instance of the class. /// /// The name of the property to override. /// The callback to invoke to get the value that should be injected. - public PropertyValue(string name, Func valueCallback) : base(name, valueCallback, false) { } + public PropertyValue(string name, Func valueCallback) + : base(name, valueCallback, false) + { + } /// /// Initializes a new instance of the class. /// /// The name of the property to override. /// The callback to invoke to get the value that should be injected. - public PropertyValue(string name, Func valueCallback) : base(name, valueCallback, false) { } + public PropertyValue(string name, Func valueCallback) + : base(name, valueCallback, false) + { + } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/TypeMatchingConstructorArgument.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/TypeMatchingConstructorArgument.cs new file mode 100644 index 00000000..81d1d13a --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/TypeMatchingConstructorArgument.cs @@ -0,0 +1,144 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject.Parameters +{ + using System; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + + /// + /// Overrides the injected value of a constructor argument. + /// + public class TypeMatchingConstructorArgument : IConstructorArgument + { + private readonly Type type; + + /// + /// Initializes a new instance of the class. + /// + /// The type of the argument to override. + /// The callback that will be triggered to get the parameter's value. + public TypeMatchingConstructorArgument(Type type, Func valueCallback) + : this(type, valueCallback, false) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The type of the argument to override. + /// The callback that will be triggered to get the parameter's value. + /// Whether the parameter should be inherited into child requests. + public TypeMatchingConstructorArgument(Type type, Func valueCallback, bool shouldInherit) + { + Ensure.ArgumentNotNull(type, "type"); + Ensure.ArgumentNotNull(valueCallback, "valueCallback"); + + this.ValueCallback = valueCallback; + this.ShouldInherit = shouldInherit; + this.type = type; + } + + /// + /// Gets the name of the parameter. + /// + public string Name + { + get + { + throw new NotImplementedException(); + } + } + + /// + /// Gets a value indicating whether the parameter should be inherited into child requests. + /// + public bool ShouldInherit { get; private set; } + + /// + /// Gets or sets the callback that will be triggered to get the parameter's value. + /// + private Func ValueCallback { get; set; } + + /// + /// Determines if the parameter applies to the given target. + /// + /// The context. + /// The target. + /// + /// True if the parameter applies in the specified context to the specified target. + /// + /// + /// Only one parameter may return true. + /// + public bool AppliesToTarget(IContext context, ITarget target) + { + return target.Type == this.type; + } + + /// + /// Gets the value for the parameter within the specified context. + /// + /// The context. + /// The target. + /// The value for the parameter. + public object GetValue(IContext context, ITarget target) + { + Ensure.ArgumentNotNull(context, "context"); + + return this.ValueCallback(context, target); + } + + /// + /// Indicates whether the current object is equal to another object of the same type. + /// + /// An object to compare with this object. + /// True if the objects are equal; otherwise false + public bool Equals(IParameter other) + { + var argument = other as TypeMatchingConstructorArgument; + return argument != null && argument.type == this.type; + } + + /// + /// Determines whether the object equals the specified object. + /// + /// An object to compare with this object. + /// True if the objects are equal; otherwise false + public override bool Equals(object obj) + { + var parameter = obj as IParameter; + return parameter != null ? this.Equals(parameter) : ReferenceEquals(this, obj); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// A hash code for the object. + public override int GetHashCode() + { + return this.GetType().GetHashCode() ^ this.type.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakConstructorArgument.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakConstructorArgument.cs index 5c3ffac1..862e70f2 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakConstructorArgument.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakConstructorArgument.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2013 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { @@ -37,7 +37,7 @@ public class WeakConstructorArgument : Parameter, IConstructorArgument private readonly WeakReference weakReference; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The name of the argument to override. /// The value to inject into the property. @@ -47,7 +47,7 @@ public WeakConstructorArgument(string name, object value) } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The name of the argument to override. /// The value to inject into the property. @@ -65,7 +65,7 @@ public WeakConstructorArgument(string name, object value, bool shouldInherit) /// The context. /// The target. /// - /// Tre if the parameter applies in the specified context to the specified target. + /// True if the parameter applies in the specified context to the specified target. /// /// /// Only one parameter may return true. @@ -75,4 +75,4 @@ public bool AppliesToTarget(IContext context, ITarget target) return string.Equals(this.Name, target.Name); } } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakPropertyValue.cs b/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakPropertyValue.cs index ca5d2fb2..f404e716 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakPropertyValue.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Parameters/WeakPropertyValue.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2013 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Parameters { @@ -40,8 +40,7 @@ public WeakPropertyValue(string name, object value) : base(name, (object)null, false) { this.weakReference = new WeakReference(value); - this.ValueCallback = (ctx, target) => this.weakReference.Target; + this.ValueCallback = (ctx, target) => this.weakReference.Target; } - } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Binding.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Binding.cs index e4707d31..b8244963 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Binding.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Binding.cs @@ -1,22 +1,33 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + /// /// Contains information about a service registration. /// @@ -49,7 +60,7 @@ public Binding(Type service, IBindingConfiguration configuration) } /// - /// Gets or sets the binding configuration. + /// Gets the binding configuration. /// /// The binding configuration. public IBindingConfiguration BindingConfiguration { get; private set; } @@ -62,7 +73,6 @@ public Binding(Type service, IBindingConfiguration configuration) /// /// Gets the binding's metadata. /// - /// public IBindingMetadata Metadata { get @@ -74,7 +84,6 @@ public IBindingMetadata Metadata /// /// Gets or sets the type of target for the binding. /// - /// public BindingTarget Target { get @@ -91,7 +100,6 @@ public BindingTarget Target /// /// Gets or sets a value indicating whether the binding was implicitly registered. /// - /// public bool IsImplicit { get @@ -108,7 +116,6 @@ public bool IsImplicit /// /// Gets a value indicating whether the binding has a condition associated with it. /// - /// public bool IsConditional { get @@ -120,13 +127,13 @@ public bool IsConditional /// /// Gets or sets the condition defined for the binding. /// - /// public Func Condition { get { return this.BindingConfiguration.Condition; } + set { this.BindingConfiguration.Condition = value; @@ -136,7 +143,6 @@ public Func Condition /// /// Gets or sets the callback that returns the provider that should be used by the binding. /// - /// public Func ProviderCallback { get @@ -153,13 +159,13 @@ public Func ProviderCallback /// /// Gets or sets the callback that returns the object that will act as the binding's scope. /// - /// public Func ScopeCallback { get { return this.BindingConfiguration.ScopeCallback; } + set { this.BindingConfiguration.ScopeCallback = value; @@ -169,7 +175,6 @@ public Func ScopeCallback /// /// Gets the parameters defined for the binding. /// - /// public ICollection Parameters { get @@ -181,7 +186,6 @@ public ICollection Parameters /// /// Gets the actions that should be called after instances are activated via the binding. /// - /// public ICollection> ActivationActions { get @@ -193,7 +197,6 @@ public ICollection> ActivationActions /// /// Gets the actions that should be called before instances are deactivated via the binding. /// - /// public ICollection> DeactivationActions { get diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder.cs index 784bdfd8..52567a70 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Activation.Providers; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; @@ -93,14 +90,14 @@ protected IBindingWhenInNamedWithOrOnSyntax InternalTo(Type implementation return new BindingConfigurationBuilder(this.BindingConfiguration, this.ServiceNames, this.Kernel); } - + /// /// Indicates that the service should be bound to the specified constant value. /// /// The type of the implementation. /// The constant value. /// The fluent syntax. - protected IBindingWhenInNamedWithOrOnSyntax InternalToConfiguration(TImplementation value) + protected IBindingWhenInNamedWithOrOnSyntax InternalToConfiguration(TImplementation value) { this.BindingConfiguration.ProviderCallback = ctx => new ConstantProvider(value); this.BindingConfiguration.Target = BindingTarget.Constant; @@ -157,7 +154,7 @@ protected IBindingWhenInNamedWithOrOnSyntax ToProviderInternal< /// Indicates that the service should be bound to an instance of the specified provider type. /// The instance will be activated via the kernel when an instance of the service is activated. /// - /// The type of the returned fleunt syntax + /// The type of the returned fluent syntax /// The type of provider to activate. /// The fluent syntax. protected IBindingWhenInNamedWithOrOnSyntax ToProviderInternal(Type providerType) @@ -168,9 +165,8 @@ protected IBindingWhenInNamedWithOrOnSyntax ToProviderInternal(Type provid return new BindingConfigurationBuilder(this.BindingConfiguration, this.ServiceNames, this.Kernel); } -#if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -263,6 +259,5 @@ public T1 Inject() throw new InvalidOperationException("This method is for declaration that a parameter shall be injected only! Never call it directly."); } } -#endif } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3,T4}.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3,T4}.cs index 5855d344..72918baa 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3,T4}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3,T4}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Syntax; @@ -39,7 +36,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings /// The fourth service type. public class BindingBuilder : BindingBuilder, IBindingToSyntax { -#pragma warning disable 1584 //mono compiler bug /// /// Initializes a new instance of the class. /// @@ -50,7 +46,6 @@ public BindingBuilder(IBindingConfiguration bindingConfigurationConfiguration, I : base(bindingConfigurationConfiguration, kernel, serviceNames) { } -#pragma warning restore 1584 /// /// Indicates that the service should be bound to the specified implementation type. @@ -73,9 +68,8 @@ public IBindingWhenInNamedWithOrOnSyntax To(Type implementation) return this.InternalTo(implementation); } - #if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -86,7 +80,6 @@ public IBindingWhenInNamedWithOrOnSyntax ToConstructor /// Indicates that the service should be bound to an instance of the specified provider type. @@ -107,8 +100,8 @@ public IBindingWhenInNamedWithOrOnSyntax ToProvider() /// The type of provider to activate. /// The type of the implementation. /// The fluent syntax. - public IBindingWhenInNamedWithOrOnSyntax ToProvider() - where TProvider : IProvider + public IBindingWhenInNamedWithOrOnSyntax ToProvider() + where TProvider : IProvider where TImplementation : T1, T2, T3, T4 { return this.ToProviderInternal(); diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3}.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3}.cs index 24a16e39..634337dc 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2,T3}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Syntax; @@ -38,7 +35,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings /// The third service type. public class BindingBuilder : BindingBuilder, IBindingToSyntax { -#pragma warning disable 1584 //mono compiler bug /// /// Initializes a new instance of the class. /// @@ -49,7 +45,6 @@ public BindingBuilder(IBindingConfiguration bindingConfigurationConfiguration, I : base(bindingConfigurationConfiguration, kernel, serviceNames) { } -#pragma warning restore 1584 /// /// Indicates that the service should be bound to the specified implementation type. @@ -72,9 +67,8 @@ public IBindingWhenInNamedWithOrOnSyntax To(Type implementation) return this.InternalTo(implementation); } - #if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -85,7 +79,6 @@ public IBindingWhenInNamedWithOrOnSyntax ToConstructor /// Indicates that the service should be bound to an instance of the specified provider type. @@ -106,13 +99,13 @@ public IBindingWhenInNamedWithOrOnSyntax ToProvider() /// The type of provider to activate. /// The type of the implementation. /// The fluent syntax. - public IBindingWhenInNamedWithOrOnSyntax ToProvider() - where TProvider : IProvider + public IBindingWhenInNamedWithOrOnSyntax ToProvider() + where TProvider : IProvider where TImplementation : T1, T2, T3 { return this.ToProviderInternal(); } - + /// /// Indicates that the service should be bound to an instance of the specified provider type. /// The instance will be activated via the kernel when an instance of the service is activated. diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2}.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2}.cs index 8cecdf2a..6eb3ad4a 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1,T2}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Syntax; @@ -37,7 +34,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings /// The second service type. public class BindingBuilder : BindingBuilder, IBindingToSyntax { -#pragma warning disable 1584 //mono compiler bug /// /// Initializes a new instance of the class. /// @@ -48,7 +44,6 @@ public BindingBuilder(IBindingConfiguration bindingConfigurationConfiguration, I : base(bindingConfigurationConfiguration, kernel, serviceNames) { } -#pragma warning restore 1584 /// /// Indicates that the service should be bound to the specified implementation type. @@ -71,9 +66,8 @@ public IBindingWhenInNamedWithOrOnSyntax To(Type implementation) return this.InternalTo(implementation); } -#if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -84,7 +78,6 @@ public IBindingWhenInNamedWithOrOnSyntax ToConstructor /// Indicates that the service should be bound to an instance of the specified provider type. @@ -105,13 +98,13 @@ public IBindingWhenInNamedWithOrOnSyntax ToProvider() /// The type of provider to activate. /// The type of the implementation. /// The fluent syntax. - public IBindingWhenInNamedWithOrOnSyntax ToProvider() - where TProvider : IProvider + public IBindingWhenInNamedWithOrOnSyntax ToProvider() + where TProvider : IProvider where TImplementation : T1, T2 { return this.ToProviderInternal(); } - + /// /// Indicates that the service should be bound to an instance of the specified provider type. /// The instance will be activated via the kernel when an instance of the service is activated. diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1}.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1}.cs index aa289bd1..89fb9bc7 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingBuilder{T1}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Activation.Providers; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; @@ -38,7 +35,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings /// The service type. public class BindingBuilder : BindingBuilder, IBindingToSyntax { -#pragma warning disable 1584 //mono compiler bug /// /// Initializes a new instance of the class. /// @@ -50,15 +46,15 @@ public BindingBuilder(IBinding binding, IKernel kernel, string serviceNames) { Ensure.ArgumentNotNull(binding, "binding"); Ensure.ArgumentNotNull(kernel, "kernel"); + this.Binding = binding; } -#pragma warning restore 1584 /// /// Gets the binding being built. /// public IBinding Binding { get; private set; } - + /// /// Indicates that the service should be self-bound. /// @@ -92,9 +88,8 @@ public IBindingWhenInNamedWithOrOnSyntax To(Type implementation) return this.InternalTo(implementation); } -#if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -105,7 +100,6 @@ public IBindingWhenInNamedWithOrOnSyntax ToConstructor /// Indicates that the service should be bound to an instance of the specified provider type. diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfiguration.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfiguration.cs index 422b7de1..d16efb1d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfiguration.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfiguration.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,14 +17,16 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; using System.Collections.Generic; + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; using Telerik.JustMock.AutoMock.Ninject.Parameters; /// @@ -32,8 +34,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings /// public class BindingConfiguration : IBindingConfiguration { - private IBindingMetadata metadata; - /// /// Initializes a new instance of the class. /// @@ -49,17 +49,7 @@ public BindingConfiguration() /// /// Gets the binding's metadata. /// - public IBindingMetadata Metadata - { - get - { - return this.metadata; - } - private set - { - this.metadata = value; - } - } + public IBindingMetadata Metadata { get; private set; } /// /// Gets or sets a value indicating whether the binding was implicitly registered. @@ -117,6 +107,12 @@ public bool IsConditional public IProvider GetProvider(IContext context) { Ensure.ArgumentNotNull(context, "context"); + + if (this.ProviderCallback == null) + { + throw new ActivationException(ExceptionFormatter.ProviderCallbackIsNull(context)); + } + return this.ProviderCallback(context); } @@ -128,6 +124,7 @@ public IProvider GetProvider(IContext context) public object GetScope(IContext context) { Ensure.ArgumentNotNull(context, "context"); + return this.ScopeCallback(context); } @@ -139,7 +136,8 @@ public object GetScope(IContext context) public bool Matches(IRequest request) { Ensure.ArgumentNotNull(request, "request"); + return this.Condition == null || this.Condition(request); - } + } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfigurationBuilder.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfigurationBuilder.cs index 8854be13..2ba9ef6c 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfigurationBuilder.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingConfigurationBuilder.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { @@ -46,17 +44,7 @@ public class BindingConfigurationBuilder : IBindingConfigurationSyntax private readonly string serviceNames; /// - /// Gets the binding being built. - /// - public IBindingConfiguration BindingConfiguration { get; private set; } - - /// - /// Gets the kernel. - /// - public IKernel Kernel { get; private set; } - - /// - /// Initializes a new instance of the BindingBuilder<T> class. + /// Initializes a new instance of the class. /// /// The binding configuration to build. /// The names of the configured services. @@ -65,11 +53,22 @@ public BindingConfigurationBuilder(IBindingConfiguration bindingConfiguration, s { Ensure.ArgumentNotNull(bindingConfiguration, "bindingConfiguration"); Ensure.ArgumentNotNull(kernel, "kernel"); + this.BindingConfiguration = bindingConfiguration; this.Kernel = kernel; this.serviceNames = serviceNames; } + /// + /// Gets the binding being built. + /// + public IBindingConfiguration BindingConfiguration { get; private set; } + + /// + /// Gets the kernel. + /// + public IKernel Kernel { get; private set; } + /// /// Indicates that the binding should be used only for requests that support the specified condition. /// @@ -89,7 +88,7 @@ public IBindingInNamedWithOrOnSyntax When(Func condition) /// The fluent syntax. public IBindingInNamedWithOrOnSyntax WhenInjectedInto() { - return WhenInjectedInto(typeof(TParent)); + return this.WhenInjectedInto(typeof(TParent)); } /// @@ -106,13 +105,13 @@ public IBindingInNamedWithOrOnSyntax WhenInjectedInto(Type parent) { this.BindingConfiguration.Condition = r => r.Target != null && - r.Target.Member.ReflectedType.GetInterfaces().Any(i => + r.Target.Member.ReflectedType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == parent); } else { - this.BindingConfiguration.Condition = r => + this.BindingConfiguration.Condition = r => r.Target != null && r.Target.Member.ReflectedType.GetAllBaseTypes().Any(i => i.IsGenericType && @@ -164,7 +163,10 @@ public IBindingInNamedWithOrOnSyntax WhenInjectedInto(params Type[] parents) matches = r.Target != null && parent.IsAssignableFrom(r.Target.Member.ReflectedType); } - if (matches) return true; + if (matches) + { + return true; + } } return false; @@ -176,19 +178,19 @@ public IBindingInNamedWithOrOnSyntax WhenInjectedInto(params Type[] parents) /// /// Indicates that the binding should be used only for injections on the specified type. /// The type must match exactly the specified type. Types that derive from the specified type - /// will not be considered as valid target. + /// will not be considered as valid target. /// /// The type. /// The fluent syntax. public IBindingInNamedWithOrOnSyntax WhenInjectedExactlyInto() { - return WhenInjectedExactlyInto(typeof(TParent)); + return this.WhenInjectedExactlyInto(typeof(TParent)); } /// /// Indicates that the binding should be used only for injections on the specified type. /// The type must match exactly the specified type. Types that derive from the specified type - /// will not be considered as valid target. + /// will not be considered as valid target. /// /// The type. /// The fluent syntax. @@ -205,20 +207,22 @@ public IBindingInNamedWithOrOnSyntax WhenInjectedExactlyInto(Type parent) { this.BindingConfiguration.Condition = r => r.Target != null && r.Target.Member.ReflectedType == parent; } + return this; } /// /// Indicates that the binding should be used only for injections on the specified type. /// The type must match exactly the specified type. Types that derive from the specified type - /// will not be considered as valid target. + /// will not be considered as valid target. /// Should match at least one of the specified targets /// /// The types. /// The fluent syntax. public IBindingInNamedWithOrOnSyntax WhenInjectedExactlyInto(params Type[] parents) { - this.BindingConfiguration.Condition = r => { + this.BindingConfiguration.Condition = r => + { foreach (var parent in parents) { bool matches = false; @@ -234,7 +238,10 @@ public IBindingInNamedWithOrOnSyntax WhenInjectedExactlyInto(params Type[] pa matches = r.Target != null && r.Target.Member.ReflectedType == parent; } - if(matches) return true; + if (matches) + { + return true; + } } return false; @@ -249,9 +256,10 @@ public IBindingInNamedWithOrOnSyntax WhenInjectedExactlyInto(params Type[] pa /// /// The type of attribute. /// The fluent syntax. - public IBindingInNamedWithOrOnSyntax WhenClassHas() where TAttribute : Attribute + public IBindingInNamedWithOrOnSyntax WhenClassHas() + where TAttribute : Attribute { - return WhenClassHas(typeof(TAttribute)); + return this.WhenClassHas(typeof(TAttribute)); } /// @@ -260,9 +268,10 @@ public IBindingInNamedWithOrOnSyntax WhenClassHas() where TAttrib /// /// The type of attribute. /// The fluent syntax. - public IBindingInNamedWithOrOnSyntax WhenMemberHas() where TAttribute : Attribute + public IBindingInNamedWithOrOnSyntax WhenMemberHas() + where TAttribute : Attribute { - return WhenMemberHas(typeof(TAttribute)); + return this.WhenMemberHas(typeof(TAttribute)); } /// @@ -271,9 +280,10 @@ public IBindingInNamedWithOrOnSyntax WhenMemberHas() where TAttri /// /// The type of attribute. /// The fluent syntax. - public IBindingInNamedWithOrOnSyntax WhenTargetHas() where TAttribute : Attribute + public IBindingInNamedWithOrOnSyntax WhenTargetHas() + where TAttribute : Attribute { - return WhenTargetHas(typeof(TAttribute)); + return this.WhenTargetHas(typeof(TAttribute)); } /// @@ -322,7 +332,7 @@ public IBindingInNamedWithOrOnSyntax WhenTargetHas(Type attributeType) { if (!typeof(Attribute).IsAssignableFrom(attributeType)) { - throw new InvalidOperationException(ExceptionFormatter.InvalidAttributeTypeUsedInBindingCondition(this.serviceNames, "WhenTargetHas", attributeType)); + throw new InvalidOperationException(ExceptionFormatter.InvalidAttributeTypeUsedInBindingCondition(this.serviceNames, "WhenTargetHas", attributeType)); } this.BindingConfiguration.Condition = r => r.Target != null && r.Target.HasAttribute(attributeType); @@ -338,7 +348,7 @@ public IBindingInNamedWithOrOnSyntax WhenTargetHas(Type attributeType) /// The fluent syntax. public IBindingInNamedWithOrOnSyntax WhenParentNamed(string name) { - String.Intern(name); + string.Intern(name); this.BindingConfiguration.Condition = r => r.ParentContext != null && string.Equals(r.ParentContext.Binding.Metadata.Name, name, StringComparison.Ordinal); return this; } @@ -488,7 +498,75 @@ public IBindingWithOrOnSyntax WithConstructorArgument(string name, Func + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// Specifies the argument type to override. + /// The value for the argument. + /// The fluent syntax. + public IBindingWithOrOnSyntax WithConstructorArgument(TValue value) + { + return this.WithConstructorArgument(typeof(TValue), (context, target) => value); + } + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The value for the argument. + /// The fluent syntax. + public IBindingWithOrOnSyntax WithConstructorArgument(Type type, object value) + { + return this.WithConstructorArgument(type, (context, target) => value); + } + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + public IBindingWithOrOnSyntax WithConstructorArgument(Type type, Func callback) + { + return this.WithConstructorArgument(type, (context, target) => callback(context)); + } + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument type to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + public IBindingWithOrOnSyntax WithConstructorArgument(Func callback) + { + return this.WithConstructorArgument(typeof(TValue), (context, target) => callback(context)); + } + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + public IBindingWithOrOnSyntax WithConstructorArgument(Type type, Func callback) + { + this.BindingConfiguration.Parameters.Add(new TypeMatchingConstructorArgument(type, callback)); + return this; + } + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument type to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + public IBindingWithOrOnSyntax WithConstructorArgument(Func callback) + { + this.WithConstructorArgument(typeof(TValue), callback); + return this; + } + /// /// Indicates that the specified property should be injected with the specified value. /// @@ -524,7 +602,7 @@ public IBindingWithOrOnSyntax WithPropertyValue(string name, Func /// Adds a custom parameter to the binding. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingMetadata.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingMetadata.cs index 28c0cd75..56c921be 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingMetadata.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingMetadata.cs @@ -1,27 +1,37 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + /// /// Additional information available about a binding, which can be used in constraints /// to select bindings to use in activation. /// public class BindingMetadata : IBindingMetadata { - private readonly Dictionary _values = new Dictionary(); + private readonly Dictionary values = new Dictionary(); /// /// Gets or sets the binding's name. @@ -36,7 +46,8 @@ public class BindingMetadata : IBindingMetadata public bool Has(string key) { Ensure.ArgumentNotNullOrEmpty(key, "key"); - return _values.ContainsKey(key); + + return this.values.ContainsKey(key); } /// @@ -48,19 +59,22 @@ public bool Has(string key) public T Get(string key) { Ensure.ArgumentNotNullOrEmpty(key, "key"); - return Get(key, default(T)); + + return this.Get(key, default(T)); } /// /// Gets the value of metadata defined with the specified key. /// + /// The type of value to expect. /// The metadata key. /// The value to return if the binding has no metadata set with the specified key. /// The metadata value, or the default value if none was set. public T Get(string key, T defaultValue) { Ensure.ArgumentNotNullOrEmpty(key, "key"); - return _values.ContainsKey(key) ? (T)_values[key] : defaultValue; + + return this.values.ContainsKey(key) ? (T)this.values[key] : defaultValue; } /// @@ -71,7 +85,8 @@ public T Get(string key, T defaultValue) public void Set(string key, object value) { Ensure.ArgumentNotNullOrEmpty(key, "key"); - _values[key] = value; + + this.values[key] = value; } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingPrecedenceComparer.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingPrecedenceComparer.cs new file mode 100644 index 00000000..a2aea777 --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingPrecedenceComparer.cs @@ -0,0 +1,67 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings +{ + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Components; + + /// + /// Implements the binding precedence comparer interface + /// + public class BindingPrecedenceComparer : NinjectComponent, IBindingPrecedenceComparer + { + /// + /// Compares the two bindings. + /// + /// The first binding. + /// The second binding. + /// Less than zero if x is less than y; Zero is x equals y; Greater than zero if x is greater than y. + public int Compare(IBinding x, IBinding y) + { + if (x == y) + { + return 0; + } + + // Each function represents a level of precedence. + var funcs = new List> + { + b => b != null, // null bindings should never happen, but just in case + b => b.IsConditional, // conditional bindings > unconditional + b => !b.Service.ContainsGenericParameters, // closed generics > open generics + b => !b.IsImplicit, // explicit bindings > implicit + }; + + var q = from func in funcs + let xVal = func(x) + where xVal != func(y) + select xVal ? 1 : -1; + + // returns the value of the first function that represents a difference + // between the bindings, or else returns 0 (equal) + return q.FirstOrDefault(); + } + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingTarget.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingTarget.cs index 5352f483..ca28a7fd 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingTarget.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/BindingTarget.cs @@ -1,18 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { @@ -44,6 +49,6 @@ public enum BindingTarget /// /// Indicates that the binding is from a type to a constant value. /// - Constant + Constant, } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBinding.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBinding.cs index 2a389baf..7c28eb35 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBinding.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBinding.cs @@ -1,21 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { + using System; + /// /// Contains information about a service registration. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfiguration.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfiguration.cs index aec66f4c..fb188c3d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfiguration.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfiguration.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,12 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { using System; using System.Collections.Generic; + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Parameters; @@ -101,6 +102,6 @@ public interface IBindingConfiguration /// /// The request. /// True if the request satisfies the condition; otherwise false. - bool Matches(IRequest request); + bool Matches(IRequest request); } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfigurationSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfigurationSyntax.cs new file mode 100644 index 00000000..21fa80fe --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingConfigurationSyntax.cs @@ -0,0 +1,37 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings +{ + using Telerik.JustMock.AutoMock.Ninject.Syntax; + + /// + /// The syntax to define bindings. + /// + /// The type of the service. + public interface IBindingConfigurationSyntax : + IBindingWhenInNamedWithOrOnSyntax, + IBindingInNamedWithOrOnSyntax, + IBindingNamedWithOrOnSyntax, + IBindingWithOrOnSyntax + { + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingMetadata.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingMetadata.cs index 3a0f235d..0cf75d30 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingMetadata.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingMetadata.cs @@ -1,15 +1,23 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings { @@ -42,6 +50,7 @@ public interface IBindingMetadata /// /// Gets the value of metadata defined with the specified key. /// + /// The type of value to expect. /// The metadata key. /// The value to return if the binding has no metadata set with the specified key. /// The metadata value, or the default value if none was set. diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingPrecedenceComparer.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingPrecedenceComparer.cs new file mode 100644 index 00000000..bf6987c7 --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingPrecedenceComparer.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- + +namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings +{ + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Components; + + /// + /// The binding precedence comparer interface + /// + public interface IBindingPrecedenceComparer : INinjectComponent, IComparer + { + } +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingSyntax.cs deleted file mode 100644 index 07294829..00000000 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/IBindingSyntax.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// - -namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings -{ - using Telerik.JustMock.AutoMock.Ninject.Syntax; - - /// - /// The syntax to define bindings. - /// - /// The type of the service. - public interface IBindingConfigurationSyntax : - IBindingWhenInNamedWithOrOnSyntax, - IBindingInNamedWithOrOnSyntax, - IBindingNamedWithOrOnSyntax, - IBindingWithOrOnSyntax - { - } -} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/DefaultValueBindingResolver.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/DefaultValueBindingResolver.cs index edf3bddb..2fad3835 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/DefaultValueBindingResolver.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/DefaultValueBindingResolver.cs @@ -1,29 +1,38 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives - -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers { + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; - /// - /// + /// + /// Represents a binding resolver that takes the target default value as the resolved object. + /// public class DefaultValueBindingResolver : NinjectComponent, IMissingBindingResolver { /// @@ -42,7 +51,7 @@ public IEnumerable Resolve(Multimap bindings, IRequest { Condition = r => HasDefaultValue(r.Target), ProviderCallback = _ => new DefaultParameterValueProvider(service), - } + }, } : Enumerable.Empty(); } @@ -56,7 +65,7 @@ private class DefaultParameterValueProvider : IProvider { public DefaultParameterValueProvider(Type type) { - Type = type; + this.Type = type; } public Type Type { get; private set; } @@ -64,7 +73,7 @@ public DefaultParameterValueProvider(Type type) public object Create(IContext context) { var target = context.Request.Target; - return (target == null) ? null : target.DefaultValue; + return target?.DefaultValue; } } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IBindingResolver.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IBindingResolver.cs index 07be3cae..7ce0630e 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IBindingResolver.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IBindingResolver.cs @@ -1,23 +1,32 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + /// /// Contains logic about which bindings to use for a given service request. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IMissingBindingResolver.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IMissingBindingResolver.cs index b7fa47b0..1727a201 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IMissingBindingResolver.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/IMissingBindingResolver.cs @@ -1,28 +1,37 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives - -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers { - /// + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + + /// /// Contains logic about which bindings to use for a given service request /// when other attempts have failed. - /// + /// public interface IMissingBindingResolver : INinjectComponent { /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/OpenGenericBindingResolver.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/OpenGenericBindingResolver.cs index 27ffeb45..3d416e46 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/OpenGenericBindingResolver.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/OpenGenericBindingResolver.cs @@ -1,24 +1,34 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers { + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + /// /// Resolves bindings for open generic types. /// @@ -33,7 +43,9 @@ public class OpenGenericBindingResolver : NinjectComponent, IBindingResolver public IEnumerable Resolve(Multimap bindings, Type service) { if (!service.IsGenericType || service.IsGenericTypeDefinition || !bindings.ContainsKey(service.GetGenericTypeDefinition())) + { return Enumerable.Empty(); + } return bindings[service.GetGenericTypeDefinition()].ToEnumerable(); } diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/SelfBindingResolver.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/SelfBindingResolver.cs index efb03e34..300280fd 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/SelfBindingResolver.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/SelfBindingResolver.cs @@ -1,28 +1,38 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives - -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Activation.Providers; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers { - /// - /// + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Activation.Providers; + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + + /// + /// Represents a binding resolver that use the service in question itself as the target to activate. + /// public class SelfBindingResolver : NinjectComponent, IMissingBindingResolver { /// @@ -34,16 +44,17 @@ public class SelfBindingResolver : NinjectComponent, IMissingBindingResolver public IEnumerable Resolve(Multimap bindings, IRequest request) { var service = request.Service; - if (!TypeIsSelfBindable(service)) + if (!this.TypeIsSelfBindable(service)) { return Enumerable.Empty(); } + return new[] { new Binding(service) { - ProviderCallback = StandardProvider.GetCreationCallback(service) - } + ProviderCallback = StandardProvider.GetCreationCallback(service), + }, }; } diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/StandardBindingResolver.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/StandardBindingResolver.cs index d8a933d3..01b5aa14 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/StandardBindingResolver.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Bindings/Resolvers/StandardBindingResolver.cs @@ -1,23 +1,33 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + /// /// Resolves bindings that have been registered directly for the service. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/ConstructorInjectionDirective.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/ConstructorInjectionDirective.cs index 1e069ffe..e2472404 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/ConstructorInjectionDirective.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/ConstructorInjectionDirective.cs @@ -1,31 +1,35 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Injection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Directives { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Injection; + /// /// Describes the injection of a constructor. /// public class ConstructorInjectionDirective : MethodInjectionDirectiveBase { - /// - /// The base .ctor definition. - /// - public ConstructorInfo Constructor { get; set; } - /// /// Initializes a new instance of the class. /// @@ -34,7 +38,24 @@ public class ConstructorInjectionDirective : MethodInjectionDirectiveBase + /// Gets or sets the base .ctor definition. + /// + public ConstructorInfo Constructor { get; set; } + + /// + /// Gets or sets a value indicating whether this constructor has an inject attribute. + /// + /// true if this constructor has an inject attribute; otherwise, false. + public bool HasInjectAttribute { get; set; } + + /// + /// Gets or sets a value indicating whether this contructor has an obsolete attribute. + /// + /// true if this constructor has an obsolete attribute; otherwise, false. + public bool HasObsoleteAttribute { get; set; } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/IDirective.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/IDirective.cs index ea2e127d..ae5a6e7b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/IDirective.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/IDirective.cs @@ -1,20 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Directives { /// /// A piece of information used in an . (Just a marker.) /// - public interface IDirective { } + public interface IDirective + { + } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirective.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirective.cs index 144081fd..ffbe2351 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirective.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirective.cs @@ -1,21 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Injection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Directives { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Injection; + /// /// Describes the injection of a method. /// @@ -27,6 +36,8 @@ public class MethodInjectionDirective : MethodInjectionDirectiveBaseThe method described by the directive. /// The injector that will be triggered. public MethodInjectionDirective(MethodInfo method, MethodInjector injector) - : base(method, injector) { } + : base(method, injector) + { + } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirectiveBase.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirectiveBase.cs index b706f286..4b0899dc 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirectiveBase.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/MethodInjectionDirectiveBase.cs @@ -1,40 +1,42 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Linq; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Directives { + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + /// /// Describes the injection of a method or constructor. /// + /// The method info. + /// The injector. public abstract class MethodInjectionDirectiveBase : IDirective where TMethod : MethodBase { /// - /// Gets or sets the injector that will be triggered. - /// - public TInjector Injector { get; private set; } - - /// - /// Gets or sets the targets for the directive. - /// - public ITarget[] Targets { get; private set; } - - /// - /// Initializes a new instance of the MethodInjectionDirectiveBase<TMethod, TInjector> class. + /// Initializes a new instance of the class. /// /// The method this directive represents. /// The injector that will be triggered. @@ -43,10 +45,20 @@ protected MethodInjectionDirectiveBase(TMethod method, TInjector injector) Ensure.ArgumentNotNull(method, "method"); Ensure.ArgumentNotNull(injector, "injector"); - Injector = injector; - Targets = CreateTargetsFromParameters(method); + this.Injector = injector; + this.Targets = this.CreateTargetsFromParameters(method); } + /// + /// Gets the injector that will be triggered. + /// + public TInjector Injector { get; private set; } + + /// + /// Gets the targets for the directive. + /// + public ITarget[] Targets { get; private set; } + /// /// Creates targets for the parameters of the method. /// @@ -57,4 +69,4 @@ protected virtual ITarget[] CreateTargetsFromParameters(TMethod method) return method.GetParameters().Select(parameter => new ParameterTarget(method, parameter)).ToArray(); } } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/PropertyInjectionDirective.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/PropertyInjectionDirective.cs index 442406de..3eb52252 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/PropertyInjectionDirective.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Directives/PropertyInjectionDirective.cs @@ -1,36 +1,36 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Injection; -using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Directives { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Injection; + using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; + /// /// Describes the injection of a property. /// public class PropertyInjectionDirective : IDirective { - /// - /// Gets or sets the injector that will be triggered. - /// - public PropertyInjector Injector { get; private set; } - - /// - /// Gets or sets the injection target for the directive. - /// - public ITarget Target { get; private set; } - /// /// Initializes a new instance of the class. /// @@ -38,10 +38,20 @@ public class PropertyInjectionDirective : IDirective /// The injector that will be triggered. public PropertyInjectionDirective(PropertyInfo member, PropertyInjector injector) { - Injector = injector; - Target = CreateTarget(member); + this.Injector = injector; + this.Target = this.CreateTarget(member); } + /// + /// Gets the injector that will be triggered. + /// + public PropertyInjector Injector { get; private set; } + + /// + /// Gets the injection target for the directive. + /// + public ITarget Target { get; private set; } + /// /// Creates a target for the property. /// @@ -52,4 +62,4 @@ protected virtual ITarget CreateTarget(PropertyInfo propertyInfo) return new PropertyTarget(propertyInfo); } } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/IPlan.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/IPlan.cs index a7e103de..327afe80 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/IPlan.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/IPlan.cs @@ -1,20 +1,31 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + /// /// Describes the means by which a type should be activated. /// @@ -25,6 +36,12 @@ public interface IPlan /// Type Type { get; } + /// + /// Gets the constructor injection directives. + /// + /// The constructor injection directives. + IList ConstructorInjectionDirectives { get; } + /// /// Adds the specified directive to the plan. /// @@ -36,20 +53,23 @@ public interface IPlan /// /// The type of directive. /// True if the plan has one or more directives of the type; otherwise, false. - bool Has() where TDirective : IDirective; + bool Has() + where TDirective : IDirective; /// /// Gets the first directive of the specified type from the plan. /// /// The type of directive. /// The first directive, or if no matching directives exist. - TDirective GetOne() where TDirective : IDirective; + TDirective GetOne() + where TDirective : IDirective; /// /// Gets all directives of the specified type that exist in the plan. /// /// The type of directive. /// A series of directives of the specified type. - IEnumerable GetAll() where TDirective : IDirective; + IEnumerable GetAll() + where TDirective : IDirective; } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/IPlanner.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/IPlanner.cs index 7c87b549..5b26a4b8 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/IPlanner.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/IPlanner.cs @@ -1,21 +1,32 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Planning.Strategies; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Planning.Strategies; + /// /// Generates plans for how to activate instances. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Plan.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Plan.cs index ae2dfd20..677d5145 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Plan.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Plan.cs @@ -1,27 +1,51 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning { + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + /// /// Describes the means by which a type should be activated. /// public class Plan : IPlan { + /// + /// Initializes a new instance of the class. + /// + /// The type the plan describes. + public Plan(Type type) + { + Ensure.ArgumentNotNull(type, "type"); + + this.Type = type; + this.Directives = new List(); + this.ConstructorInjectionDirectives = new List(); + } + /// /// Gets the type that the plan describes. /// @@ -33,16 +57,9 @@ public class Plan : IPlan public ICollection Directives { get; private set; } /// - /// Initializes a new instance of the class. + /// Gets the constructor injection directives defined in the plan. /// - /// The type the plan describes. - public Plan(Type type) - { - Ensure.ArgumentNotNull(type, "type"); - - Type = type; - Directives = new List(); - } + public IList ConstructorInjectionDirectives { get; private set; } /// /// Adds the specified directive to the plan. @@ -51,7 +68,13 @@ public Plan(Type type) public void Add(IDirective directive) { Ensure.ArgumentNotNull(directive, "directive"); - Directives.Add(directive); + + if (directive is ConstructorInjectionDirective constructorInjectionDirective) + { + this.ConstructorInjectionDirectives.Add(constructorInjectionDirective); + } + + this.Directives.Add(directive); } /// @@ -62,7 +85,7 @@ public void Add(IDirective directive) public bool Has() where TDirective : IDirective { - return GetAll().Count() > 0; + return this.GetAll().Any(); } /// @@ -73,7 +96,7 @@ public bool Has() public TDirective GetOne() where TDirective : IDirective { - return GetAll().SingleOrDefault(); + return this.GetAll().SingleOrDefault(); } /// @@ -84,7 +107,7 @@ public TDirective GetOne() public IEnumerable GetAll() where TDirective : IDirective { - return Directives.OfType(); + return this.Directives.OfType(); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Planner.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Planner.cs index 406c7db9..e7cf6018 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Planner.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Planner.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning { @@ -27,6 +25,7 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning using System.Collections.Generic; using System.Linq; using System.Threading; + using Telerik.JustMock.AutoMock.Ninject.Components; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; @@ -37,7 +36,7 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning /// public class Planner : NinjectComponent, IPlanner { - private readonly ReaderWriterLock plannerLock = new ReaderWriterLock(); + private readonly ReaderWriterLockSlim plannerLock = new ReaderWriterLockSlim(); private readonly Dictionary plans = new Dictionary(); /// @@ -47,6 +46,7 @@ public class Planner : NinjectComponent, IPlanner public Planner(IEnumerable strategies) { Ensure.ArgumentNotNull(strategies, "strategies"); + this.Strategies = strategies.ToList(); } @@ -54,7 +54,7 @@ public Planner(IEnumerable strategies) /// Gets the strategies that contribute to the planning process. /// public IList Strategies { get; private set; } - + /// /// Gets or creates an activation plan for the specified type. /// @@ -64,15 +64,15 @@ public IPlan GetPlan(Type type) { Ensure.ArgumentNotNull(type, "type"); - this.plannerLock.AcquireReaderLock(Timeout.Infinite); + this.plannerLock.EnterUpgradeableReadLock(); + try { - IPlan plan; - return this.plans.TryGetValue(type, out plan) ? plan : this.CreateNewPlan(type); + return this.plans.TryGetValue(type, out IPlan plan) ? plan : this.CreateNewPlan(type); } finally { - this.plannerLock.ReleaseReaderLock(); + this.plannerLock.ExitUpgradeableReadLock(); } } @@ -84,6 +84,7 @@ public IPlan GetPlan(Type type) protected virtual IPlan CreateEmptyPlan(Type type) { Ensure.ArgumentNotNull(type, "type"); + return new Plan(type); } @@ -95,11 +96,11 @@ protected virtual IPlan CreateEmptyPlan(Type type) /// The newly created plan. private IPlan CreateNewPlan(Type type) { - var lockCooki = this.plannerLock.UpgradeToWriterLock(Timeout.Infinite); + this.plannerLock.EnterWriteLock(); + try { - IPlan plan; - if (this.plans.TryGetValue(type, out plan)) + if (this.plans.TryGetValue(type, out IPlan plan)) { return plan; } @@ -112,7 +113,7 @@ private IPlan CreateNewPlan(Type type) } finally { - this.plannerLock.DowngradeFromWriterLock(ref lockCooki); + this.plannerLock.ExitWriteLock(); } } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/ConstructorReflectionStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/ConstructorReflectionStrategy.cs index ae487e86..77ee90c5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/ConstructorReflectionStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/ConstructorReflectionStrategy.cs @@ -1,40 +1,41 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Injection; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -using Telerik.JustMock.AutoMock.Ninject.Selection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Strategies { + using System; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + using Telerik.JustMock.AutoMock.Ninject.Injection; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + using Telerik.JustMock.AutoMock.Ninject.Selection; + /// /// Adds a directive to plans indicating which constructor should be injected during activation. /// public class ConstructorReflectionStrategy : NinjectComponent, IPlanningStrategy { - /// - /// Gets the selector component. - /// - public ISelector Selector { get; private set; } - - /// - /// Gets the injector factory component. - /// - public IInjectorFactory InjectorFactory { get; set; } - /// /// Initializes a new instance of the class. /// @@ -45,10 +46,20 @@ public ConstructorReflectionStrategy(ISelector selector, IInjectorFactory inject Ensure.ArgumentNotNull(selector, "selector"); Ensure.ArgumentNotNull(injectorFactory, "injectorFactory"); - Selector = selector; - InjectorFactory = injectorFactory; + this.Selector = selector; + this.InjectorFactory = injectorFactory; } + /// + /// Gets the selector component. + /// + public ISelector Selector { get; private set; } + + /// + /// Gets or sets the injector factory component. + /// + public IInjectorFactory InjectorFactory { get; set; } + /// /// Adds a to the plan for the constructor /// that should be injected. @@ -58,13 +69,23 @@ public void Execute(IPlan plan) { Ensure.ArgumentNotNull(plan, "plan"); - IEnumerable constructors = Selector.SelectConstructorsForInjection(plan.Type); - if(constructors == null) + var constructors = this.Selector.SelectConstructorsForInjection(plan.Type); + if (constructors == null) + { return; + } - foreach(ConstructorInfo constructor in constructors) + foreach (ConstructorInfo constructor in constructors) { - plan.Add(new ConstructorInjectionDirective(constructor, InjectorFactory.Create(constructor))); + var hasInjectAttribute = constructor.HasAttribute(this.Settings.InjectAttribute); + var hasObsoleteAttribute = constructor.HasAttribute(typeof(ObsoleteAttribute)); + var directive = new ConstructorInjectionDirective(constructor, this.InjectorFactory.Create(constructor)) + { + HasInjectAttribute = hasInjectAttribute, + HasObsoleteAttribute = hasObsoleteAttribute, + }; + + plan.Add(directive); } } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/IPlanningStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/IPlanningStrategy.cs index 797614c3..68ba81c3 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/IPlanningStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/IPlanningStrategy.cs @@ -1,19 +1,28 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Strategies { + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Contributes to the generation of a . /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/MethodReflectionStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/MethodReflectionStrategy.cs index de31cc9a..966f247a 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/MethodReflectionStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/MethodReflectionStrategy.cs @@ -1,39 +1,39 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Injection; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -using Telerik.JustMock.AutoMock.Ninject.Selection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Strategies { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Injection; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + using Telerik.JustMock.AutoMock.Ninject.Selection; + /// /// Adds directives to plans indicating which methods should be injected during activation. /// public class MethodReflectionStrategy : NinjectComponent, IPlanningStrategy { - /// - /// Gets the selector component. - /// - public ISelector Selector { get; private set; } - - /// - /// Gets the injector factory component. - /// - public IInjectorFactory InjectorFactory { get; set; } - /// /// Initializes a new instance of the class. /// @@ -44,10 +44,20 @@ public MethodReflectionStrategy(ISelector selector, IInjectorFactory injectorFac Ensure.ArgumentNotNull(selector, "selector"); Ensure.ArgumentNotNull(injectorFactory, "injectorFactory"); - Selector = selector; - InjectorFactory = injectorFactory; + this.Selector = selector; + this.InjectorFactory = injectorFactory; } + /// + /// Gets the selector component. + /// + public ISelector Selector { get; private set; } + + /// + /// Gets or sets the injector factory component. + /// + public IInjectorFactory InjectorFactory { get; set; } + /// /// Adds a to the plan for each method /// that should be injected. @@ -57,8 +67,10 @@ public void Execute(IPlan plan) { Ensure.ArgumentNotNull(plan, "plan"); - foreach (MethodInfo method in Selector.SelectMethodsForInjection(plan.Type)) - plan.Add(new MethodInjectionDirective(method, InjectorFactory.Create(method))); + foreach (MethodInfo method in this.Selector.SelectMethodsForInjection(plan.Type)) + { + plan.Add(new MethodInjectionDirective(method, this.InjectorFactory.Create(method))); + } } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/PropertyReflectionStrategy.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/PropertyReflectionStrategy.cs index 31ac72a4..fa1605e9 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/PropertyReflectionStrategy.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Strategies/PropertyReflectionStrategy.cs @@ -1,39 +1,39 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Injection; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; -using Telerik.JustMock.AutoMock.Ninject.Selection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Strategies { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Injection; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + using Telerik.JustMock.AutoMock.Ninject.Selection; + /// /// Adds directives to plans indicating which properties should be injected during activation. /// public class PropertyReflectionStrategy : NinjectComponent, IPlanningStrategy { - /// - /// Gets the selector component. - /// - public ISelector Selector { get; private set; } - - /// - /// Gets the injector factory component. - /// - public IInjectorFactory InjectorFactory { get; set; } - /// /// Initializes a new instance of the class. /// @@ -44,10 +44,20 @@ public PropertyReflectionStrategy(ISelector selector, IInjectorFactory injectorF Ensure.ArgumentNotNull(selector, "selector"); Ensure.ArgumentNotNull(injectorFactory, "injectorFactory"); - Selector = selector; - InjectorFactory = injectorFactory; + this.Selector = selector; + this.InjectorFactory = injectorFactory; } + /// + /// Gets the selector component. + /// + public ISelector Selector { get; private set; } + + /// + /// Gets or sets the injector factory component. + /// + public IInjectorFactory InjectorFactory { get; set; } + /// /// Adds a to the plan for each property /// that should be injected. @@ -57,8 +67,10 @@ public void Execute(IPlan plan) { Ensure.ArgumentNotNull(plan, "plan"); - foreach (PropertyInfo property in Selector.SelectPropertiesForInjection(plan.Type)) - plan.Add(new PropertyInjectionDirective(property, InjectorFactory.Create(property))); + foreach (PropertyInfo property in this.Selector.SelectPropertiesForInjection(plan.Type)) + { + plan.Add(new PropertyInjectionDirective(property, this.InjectorFactory.Create(property))); + } } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ITarget.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ITarget.cs index 3d8ba6c0..b6113e3b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ITarget.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ITarget.cs @@ -1,21 +1,32 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Targets { + using System; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Represents a site on a type where a value will be injected. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ParameterTarget.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ParameterTarget.cs index 806e2650..c560a5c2 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ParameterTarget.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/ParameterTarget.cs @@ -1,33 +1,50 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Targets { + using System; + using System.Reflection; + /// /// Represents an injection target for a . /// public class ParameterTarget : Target { - private readonly Future defaultValue; + /// + /// Initializes a new instance of the class. + /// + /// The method that defines the parameter. + /// The parameter that this target represents. + public ParameterTarget(MethodBase method, ParameterInfo site) + : base(method, site) + { + } /// /// Gets the name of the target. /// public override string Name { - get { return Site.Name; } + get { return this.Site.Name; } } /// @@ -35,37 +52,24 @@ public override string Name /// public override Type Type { - get { return Site.ParameterType; } + get { return this.Site.ParameterType; } } -// Windows Phone doesn't support default values and returns null instead of DBNull. -#if !WINDOWS_PHONE /// /// Gets a value indicating whether the target has a default value. /// public override bool HasDefaultValue { - get { return defaultValue.Value != DBNull.Value; } + get { return this.Site.HasDefaultValue; } } /// /// Gets the default value for the target. /// - /// If the item does not have a default value. + /// If the item does not have a default value. public override object DefaultValue { - get { return HasDefaultValue ? defaultValue.Value : base.DefaultValue; } - } -#endif - - /// - /// Initializes a new instance of the class. - /// - /// The method that defines the parameter. - /// The parameter that this target represents. - public ParameterTarget(MethodBase method, ParameterInfo site) : base(method, site) - { - defaultValue = new Future(() => site.DefaultValue); + get { return this.HasDefaultValue ? this.Site.DefaultValue : base.DefaultValue; } } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/PropertyTarget.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/PropertyTarget.cs index 34a34fa8..4ac0ab3c 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/PropertyTarget.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/PropertyTarget.cs @@ -1,30 +1,49 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Targets { + using System; + using System.Reflection; + /// /// Represents an injection target for a . /// public class PropertyTarget : Target { + /// + /// Initializes a new instance of the class. + /// + /// The property that this target represents. + public PropertyTarget(PropertyInfo site) + : base(site, site) + { + } + /// /// Gets the name of the target. /// public override string Name { - get { return Site.Name; } + get { return this.Site.Name; } } /// @@ -32,13 +51,7 @@ public override string Name /// public override Type Type { - get { return Site.PropertyType; } + get { return this.Site.PropertyType; } } - - /// - /// Initializes a new instance of the class. - /// - /// The property that this target represents. - public PropertyTarget(PropertyInfo site) : base(site, site) { } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/Target.cs b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/Target.cs index f6584c2d..107e950a 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/Target.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Planning/Targets/Target.cs @@ -1,26 +1,37 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Planning.Targets { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Introspection; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Represents a site on a type where a value can be injected. /// @@ -28,8 +39,25 @@ namespace Telerik.JustMock.AutoMock.Ninject.Planning.Targets public abstract class Target : ITarget where T : ICustomAttributeProvider { - private readonly Future> _constraint; - private readonly Future _isOptional; + private readonly Lazy> constraint; + private readonly Lazy isOptional; + + /// + /// Initializes a new instance of the class. + /// + /// The member that contains the target. + /// The site represented by the target. + protected Target(MemberInfo member, T site) + { + Ensure.ArgumentNotNull(member, "member"); + Ensure.ArgumentNotNull(site, "site"); + + this.Member = member; + this.Site = site; + + this.constraint = new Lazy>(this.ReadConstraintFromTarget); + this.isOptional = new Lazy(this.ReadOptionalFromTarget); + } /// /// Gets the member that contains the target. @@ -37,7 +65,7 @@ public abstract class Target : ITarget public MemberInfo Member { get; private set; } /// - /// Gets or sets the site (property, parameter, etc.) represented by the target. + /// Gets the site (property, parameter, etc.) represented by the target. /// public T Site { get; private set; } @@ -56,7 +84,7 @@ public abstract class Target : ITarget /// public Func Constraint { - get { return _constraint; } + get { return this.constraint.Value; } } /// @@ -64,7 +92,7 @@ public Func Constraint /// public bool IsOptional { - get { return _isOptional; } + get { return this.isOptional.Value; } } /// @@ -84,23 +112,6 @@ public virtual object DefaultValue get { throw new InvalidOperationException(ExceptionFormatter.TargetDoesNotHaveADefaultValue(this)); } } - /// - /// Initializes a new instance of the Target<T> class. - /// - /// The member that contains the target. - /// The site represented by the target. - protected Target(MemberInfo member, T site) - { - Ensure.ArgumentNotNull(member, "member"); - Ensure.ArgumentNotNull(site, "site"); - - Member = member; - Site = site; - - _constraint = new Future>(ReadConstraintFromTarget); - _isOptional = new Future(ReadOptionalFromTarget); - } - /// /// Returns an array of custom attributes of a specified type defined on the target. /// @@ -110,7 +121,8 @@ protected Target(MemberInfo member, T site) public object[] GetCustomAttributes(Type attributeType, bool inherit) { Ensure.ArgumentNotNull(attributeType, "attributeType"); - return Site.GetCustomAttributesExtended(attributeType, inherit); + + return this.Site.GetCustomAttributesExtended(attributeType, inherit); } /// @@ -120,7 +132,7 @@ public object[] GetCustomAttributes(Type attributeType, bool inherit) /// An array of custom attributes. public object[] GetCustomAttributes(bool inherit) { - return Site.GetCustomAttributes(inherit); + return this.Site.GetCustomAttributes(inherit); } /// @@ -132,7 +144,8 @@ public object[] GetCustomAttributes(bool inherit) public bool IsDefined(Type attributeType, bool inherit) { Ensure.ArgumentNotNull(attributeType, "attributeType"); - return Site.IsDefined(attributeType, inherit); + + return this.Site.IsDefined(attributeType, inherit); } /// @@ -144,25 +157,9 @@ public object ResolveWithin(IContext parent) { Ensure.ArgumentNotNull(parent, "parent"); - if (Type.IsArray) - { - Type service = Type.GetElementType(); - return GetValues(service, parent).CastSlow(service).ToArraySlow(service); - } - - if (Type.IsGenericType) - { - Type gtd = Type.GetGenericTypeDefinition(); - Type service = Type.GetGenericArguments()[0]; - - if (gtd == typeof(List<>) || gtd == typeof(IList<>) || gtd == typeof(ICollection<>)) - return GetValues(service, parent).CastSlow(service).ToListSlow(service); - - if (gtd == typeof(IEnumerable<>)) - return GetValues(service, parent).CastSlow(service); - } - - return GetValue(Type, parent); + var request = parent.Request.CreateChild(this.Type, parent, this); + request.IsUnique = true; + return parent.Kernel.Resolve(request).SingleOrDefault(); } /// @@ -171,6 +168,7 @@ public object ResolveWithin(IContext parent) /// The service that the target is requesting. /// The parent context in which the target is being injected. /// A series of values that are available for injection. + [Obsolete] protected virtual IEnumerable GetValues(Type service, IContext parent) { Ensure.ArgumentNotNull(service, "service"); @@ -187,6 +185,7 @@ protected virtual IEnumerable GetValues(Type service, IContext parent) /// The service that the target is requesting. /// The parent context in which the target is being injected. /// The value that is to be injected. + [Obsolete] protected virtual object GetValue(Type service, IContext parent) { Ensure.ArgumentNotNull(service, "service"); @@ -203,7 +202,7 @@ protected virtual object GetValue(Type service, IContext parent) /// if it is optional; otherwise . protected virtual bool ReadOptionalFromTarget() { - return Site.HasAttribute(typeof(OptionalAttribute)); + return this.Site.HasAttribute(typeof(OptionalAttribute)); } /// @@ -215,10 +214,14 @@ protected virtual Func ReadConstraintFromTarget() var attributes = this.GetCustomAttributes(typeof(ConstraintAttribute), true) as ConstraintAttribute[]; if (attributes == null || attributes.Length == 0) + { return null; + } if (attributes.Length == 1) + { return attributes[0].Matches; + } return metadata => attributes.All(attribute => attribute.Matches(metadata)); } diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IConstructorScorer.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IConstructorScorer.cs index aaf63c70..511ba632 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IConstructorScorer.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IConstructorScorer.cs @@ -1,23 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; - -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics { + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; + /// /// Generates scores for constructors, to determine which is the best one to call during activation. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IInjectionHeuristic.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IInjectionHeuristic.cs index 92a81d72..6e3c5a42 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IInjectionHeuristic.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/IInjectionHeuristic.cs @@ -1,20 +1,30 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + /// /// Determines whether members should be injected during activation. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/SpecificConstructorSelector.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/SpecificConstructorSelector.cs index 54fbebe7..9406aa68 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/SpecificConstructorSelector.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/SpecificConstructorSelector.cs @@ -1,13 +1,15 @@ -//------------------------------------------------------------------------------- -// -// Copyright (c) 2011 Ninject Project Contributors -// Author: Remo Gloor (remo.gloor@gmail.com) +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,11 +17,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics { using System.Reflection; + using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Components; using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; @@ -48,7 +51,7 @@ public SpecificConstructorSelector(ConstructorInfo constructorInfo) /// The constructor's score. public virtual int Score(IContext context, ConstructorInjectionDirective directive) { - return directive.Constructor.Equals(constructorInfo) ? 1 : 0; + return directive.Constructor.Equals(this.constructorInfo) ? 1 : 0; } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardConstructorScorer.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardConstructorScorer.cs index 9161a108..5612f829 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardConstructorScorer.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardConstructorScorer.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics { @@ -30,7 +28,6 @@ namespace Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics using Telerik.JustMock.AutoMock.Ninject.Activation; using Telerik.JustMock.AutoMock.Ninject.Components; using Telerik.JustMock.AutoMock.Ninject.Infrastructure; - using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; using Telerik.JustMock.AutoMock.Ninject.Parameters; using Telerik.JustMock.AutoMock.Ninject.Planning.Directives; using Telerik.JustMock.AutoMock.Ninject.Planning.Targets; @@ -50,23 +47,28 @@ public class StandardConstructorScorer : NinjectComponent, IConstructorScorer public virtual int Score(IContext context, ConstructorInjectionDirective directive) { Ensure.ArgumentNotNull(context, "context"); - Ensure.ArgumentNotNull(directive, "constructor"); + Ensure.ArgumentNotNull(directive, "directive"); - if (directive.Constructor.HasAttribute(Settings.InjectAttribute)) + if (directive.HasInjectAttribute) { return int.MaxValue; } + if (directive.HasObsoleteAttribute) + { + return int.MinValue; + } + var score = 1; foreach (ITarget target in directive.Targets) { - if (ParameterExists(context, target)) + if (this.ParameterExists(context, target)) { score++; continue; } - - if (BindingExists(context, target)) + + if (this.BindingExists(context, target)) { score++; continue; @@ -78,7 +80,7 @@ public virtual int Score(IContext context, ConstructorInjectionDirective directi score += int.MinValue; } } - + return score; } @@ -90,8 +92,8 @@ public virtual int Score(IContext context, ConstructorInjectionDirective directi /// Whether a binding exists for the target in the given context. protected virtual bool BindingExists(IContext context, ITarget target) { - return this.BindingExists(context.Kernel, context, target); - } + return this.BindingExists(context.Kernel, context, target); + } /// /// Checkes whether a binding exists for a given target on the specified kernel. @@ -102,14 +104,30 @@ protected virtual bool BindingExists(IContext context, ITarget target) /// Whether a binding exists for the target in the given context. protected virtual bool BindingExists(IKernel kernel, IContext context, ITarget target) { - var targetType = GetTargetType(target); - return kernel.GetBindings(targetType).Any(b => !b.IsImplicit) + var targetType = this.GetTargetType(target); + var request = context.Request.CreateChild(targetType, context, target); + + return kernel.GetBindings(targetType).Any(b => !b.IsImplicit && b.Matches(request)) || target.HasDefaultValue; } + /// + /// Checks whether any parameters exist for the given target.. + /// + /// The context. + /// The target. + /// Whether a parameter exists for the target in the given context. + protected virtual bool ParameterExists(IContext context, ITarget target) + { + return context + .Parameters.OfType() + .Any(parameter => parameter.AppliesToTarget(context, target)); + } + private Type GetTargetType(ITarget target) { var targetType = target.Type; + if (targetType.IsArray) { targetType = targetType.GetElementType(); @@ -122,18 +140,5 @@ private Type GetTargetType(ITarget target) return targetType; } - - /// - /// Checks whether any parameters exist for the geiven target.. - /// - /// The context. - /// The target. - /// Whether a parameter exists for the target in the given context. - protected virtual bool ParameterExists(IContext context, ITarget target) - { - return context - .Parameters.OfType() - .Any(parameter => parameter.AppliesToTarget(context, target)); - } } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardInjectionHeuristic.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardInjectionHeuristic.cs index 0a1c6228..53e6a687 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardInjectionHeuristic.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/Heuristics/StandardInjectionHeuristic.cs @@ -1,22 +1,32 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + /// /// Determines whether members should be injected during activation by checking /// if they are decorated with an injection marker attribute. @@ -32,22 +42,16 @@ public virtual bool ShouldInject(MemberInfo member) { Ensure.ArgumentNotNull(member, "member"); - var propertyInfo = member as PropertyInfo; - - if (propertyInfo != null) + if (member is PropertyInfo propertyInfo) { -#if !SILVERLIGHT - bool injectNonPublic = Settings.InjectNonPublic; -#else - const bool injectNonPublic = false; -#endif // !SILVERLIGHT + var injectNonPublic = this.Settings.InjectNonPublic; var setMethod = propertyInfo.GetSetMethod(injectNonPublic); - return member.HasAttribute(Settings.InjectAttribute) && setMethod != null; + return member.HasAttribute(this.Settings.InjectAttribute) && setMethod != null; } - return member.HasAttribute(Settings.InjectAttribute); + return member.HasAttribute(this.Settings.InjectAttribute); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/ISelector.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/ISelector.cs index 7f5d85bd..f9ea787a 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/ISelector.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/ISelector.cs @@ -1,31 +1,42 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection { + using System; + using System.Collections.Generic; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics; + /// /// Selects members for injection. /// public interface ISelector : INinjectComponent { /// - /// Gets or sets the constructor scorer. + /// Gets the constructor scorer. /// - IConstructorScorer ConstructorScorer { get; set; } + IConstructorScorer ConstructorScorer { get; } /// /// Gets the heuristics used to determine which members should be injected. diff --git a/Telerik.JustMock/AutoMock/Ninject/Selection/Selector.cs b/Telerik.JustMock/AutoMock/Ninject/Selection/Selector.cs index 063be910..66fbb92f 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Selection/Selector.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Selection/Selector.cs @@ -1,25 +1,35 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Components; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Selection { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Components; + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; using Telerik.JustMock.AutoMock.Ninject.Infrastructure.Language; + using Telerik.JustMock.AutoMock.Ninject.Selection.Heuristics; /// /// Selects members for injection. @@ -29,24 +39,23 @@ public class Selector : NinjectComponent, ISelector private const BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Instance; /// - /// Gets the default binding flags. + /// Initializes a new instance of the class. /// - protected virtual BindingFlags Flags + /// The constructor scorer. + /// The injection heuristics. + public Selector(IConstructorScorer constructorScorer, IEnumerable injectionHeuristics) { - get - { - #if !NO_LCG && !SILVERLIGHT - return Settings.InjectNonPublic ? (DefaultFlags | BindingFlags.NonPublic) : DefaultFlags; - #else - return DefaultFlags; - #endif - } + Ensure.ArgumentNotNull(constructorScorer, "constructorScorer"); + Ensure.ArgumentNotNull(injectionHeuristics, "injectionHeuristics"); + + this.ConstructorScorer = constructorScorer; + this.InjectionHeuristics = injectionHeuristics.ToList(); } /// - /// Gets or sets the constructor scorer. + /// Gets the constructor scorer. /// - public IConstructorScorer ConstructorScorer { get; set; } + public IConstructorScorer ConstructorScorer { get; private set; } /// /// Gets the property injection heuristics. @@ -54,17 +63,18 @@ protected virtual BindingFlags Flags public ICollection InjectionHeuristics { get; private set; } /// - /// Initializes a new instance of the class. + /// Gets the default binding flags. /// - /// The constructor scorer. - /// The injection heuristics. - public Selector(IConstructorScorer constructorScorer, IEnumerable injectionHeuristics) + protected virtual BindingFlags Flags { - Ensure.ArgumentNotNull(constructorScorer, "constructorScorer"); - Ensure.ArgumentNotNull(injectionHeuristics, "injectionHeuristics"); - - ConstructorScorer = constructorScorer; - InjectionHeuristics = injectionHeuristics.ToList(); + get + { +#if !NO_LCG + return this.Settings.InjectNonPublic ? (DefaultFlags | BindingFlags.NonPublic) : DefaultFlags; +#else + return DefaultFlags; +#endif + } } /// @@ -72,11 +82,16 @@ public Selector(IConstructorScorer constructorScorer, IEnumerable /// The type. /// The selected constructor, or if none were available. - public virtual IEnumerable SelectConstructorsForInjection(Type type) + public virtual IEnumerable SelectConstructorsForInjection(Type type) { Ensure.ArgumentNotNull(type, "type"); - var constructors = type.GetConstructors( Flags ); + if (type.IsSubclassOf(typeof(MulticastDelegate))) + { + return null; + } + + var constructors = type.GetConstructors(this.Flags); return constructors.Length == 0 ? null : constructors; } @@ -88,30 +103,24 @@ public virtual IEnumerable SelectConstructorsForInjection(Type public virtual IEnumerable SelectPropertiesForInjection(Type type) { Ensure.ArgumentNotNull(type, "type"); - List properties = new List(); + + var properties = new List(); properties.AddRange( type.GetProperties(this.Flags) - .Select(p => p.GetPropertyFromDeclaredType(p, this.Flags)) - .Where(p => this.InjectionHeuristics.Any(h => h.ShouldInject(p)))); -#if !SILVERLIGHT + .Select(p => p.GetPropertyFromDeclaredType(p, this.Flags)) + .Where(p => this.InjectionHeuristics.Any(h => p != null && h.ShouldInject(p)))); + if (this.Settings.InjectParentPrivateProperties) { for (Type parentType = type.BaseType; parentType != null; parentType = parentType.BaseType) { - properties.AddRange(this.GetPrivateProperties(type.BaseType)); + properties.AddRange(this.GetPrivateProperties(parentType)); } } -#endif return properties; } - private IEnumerable GetPrivateProperties(Type type) - { - return type.GetProperties(this.Flags).Where(p => p.DeclaringType == type && p.IsPrivate()) - .Where(p => this.InjectionHeuristics.Any(h => h.ShouldInject(p))); - } - /// /// Selects methods that should be injected. /// @@ -120,7 +129,14 @@ private IEnumerable GetPrivateProperties(Type type) public virtual IEnumerable SelectMethodsForInjection(Type type) { Ensure.ArgumentNotNull(type, "type"); - return type.GetMethods(Flags).Where(m => InjectionHeuristics.Any(h => h.ShouldInject(m))); + + return type.GetMethods(this.Flags).Where(m => this.InjectionHeuristics.Any(h => h.ShouldInject(m))); + } + + private IEnumerable GetPrivateProperties(Type type) + { + return type.GetProperties(this.Flags).Where(p => p.DeclaringType == type && p.IsPrivate()) + .Where(p => this.InjectionHeuristics.Any(h => h.ShouldInject(p))); } } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/StandardKernel.cs b/Telerik.JustMock/AutoMock/Ninject/StandardKernel.cs index 214b84f6..59ba111d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/StandardKernel.cs +++ b/Telerik.JustMock/AutoMock/Ninject/StandardKernel.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { @@ -31,6 +29,7 @@ namespace Telerik.JustMock.AutoMock.Ninject using Telerik.JustMock.AutoMock.Ninject.Injection; using Telerik.JustMock.AutoMock.Ninject.Modules; using Telerik.JustMock.AutoMock.Ninject.Planning; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings.Resolvers; using Telerik.JustMock.AutoMock.Ninject.Planning.Strategies; using Telerik.JustMock.AutoMock.Ninject.Selection; @@ -45,7 +44,8 @@ public class StandardKernel : KernelBase /// Initializes a new instance of the class. /// /// The modules to load into the kernel. - public StandardKernel(params INinjectModule[] modules) : base(modules) + public StandardKernel(params INinjectModule[] modules) + : base(modules) { } @@ -54,7 +54,8 @@ public StandardKernel(params INinjectModule[] modules) : base(modules) /// /// The configuration to use. /// The modules to load into the kernel. - public StandardKernel(INinjectSettings settings, params INinjectModule[] modules) : base(settings, modules) + public StandardKernel(INinjectSettings settings, params INinjectModule[] modules) + : base(settings, modules) { } @@ -84,7 +85,7 @@ private void AddComponent() Components.Add(); } } - + /// /// Adds components to the kernel during startup. /// @@ -100,7 +101,7 @@ protected override void AddComponents() AddComponent(); AddComponent(); - if (!Settings.ActivationCacheDisabled) + if (!this.Settings.ActivationCacheDisabled) { AddComponent(); } @@ -112,6 +113,8 @@ protected override void AddComponents() AddComponent(); AddComponent(); + AddComponent(); + AddComponent(); AddComponent(); @@ -119,7 +122,7 @@ protected override void AddComponents() AddComponent(); #if !NO_LCG - if (!Settings.UseReflectionBasedInjection) + if (!this.Settings.UseReflectionBasedInjection) { AddComponent(); } @@ -133,11 +136,9 @@ protected override void AddComponents() AddComponent(); AddComponent(); -#if !NO_ASSEMBLY_SCANNING AddComponent(); AddComponent(); AddComponent(); -#endif } } } diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/BindingRoot.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/BindingRoot.cs index e03ce6e1..524ae87a 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/BindingRoot.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/BindingRoot.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { @@ -49,7 +47,7 @@ public abstract class BindingRoot : DisposableObject, IBindingRoot /// The fluent syntax public IBindingToSyntax Bind() { - Type service = typeof(T); + var service = typeof(T); var binding = new Binding(service); this.AddBinding(binding); @@ -68,9 +66,9 @@ public IBindingToSyntax Bind() var firstBinding = new Binding(typeof(T1)); this.AddBinding(firstBinding); this.AddBinding(new Binding(typeof(T2), firstBinding.BindingConfiguration)); - var servceNames = new[] { typeof(T1).Format(), typeof(T2).Format() }; + var serviceNames = new[] { typeof(T1).Format(), typeof(T2).Format() }; - return new BindingBuilder(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", servceNames)); + return new BindingBuilder(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", serviceNames)); } /// @@ -86,9 +84,9 @@ public IBindingToSyntax Bind() this.AddBinding(firstBinding); this.AddBinding(new Binding(typeof(T2), firstBinding.BindingConfiguration)); this.AddBinding(new Binding(typeof(T3), firstBinding.BindingConfiguration)); - var servceNames = new[] { typeof(T1).Format(), typeof(T2).Format(), typeof(T3).Format() }; + var serviceNames = new[] { typeof(T1).Format(), typeof(T2).Format(), typeof(T3).Format() }; - return new BindingBuilder(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", servceNames)); + return new BindingBuilder(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", serviceNames)); } /// @@ -106,9 +104,9 @@ public IBindingToSyntax Bind() this.AddBinding(new Binding(typeof(T2), firstBinding.BindingConfiguration)); this.AddBinding(new Binding(typeof(T3), firstBinding.BindingConfiguration)); this.AddBinding(new Binding(typeof(T4), firstBinding.BindingConfiguration)); - var servceNames = new[] { typeof(T1).Format(), typeof(T2).Format(), typeof(T3).Format(), typeof(T4).Format() }; + var serviceNames = new[] { typeof(T1).Format(), typeof(T2).Format(), typeof(T3).Format(), typeof(T4).Format() }; - return new BindingBuilder(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", servceNames)); + return new BindingBuilder(firstBinding.BindingConfiguration, this.KernelInstance, string.Join(", ", serviceNames)); } /// @@ -121,7 +119,7 @@ public IBindingToSyntax Bind(params Type[] services) Ensure.ArgumentNotNull(services, "service"); if (services.Length == 0) { - throw new ArgumentException("The services must contain at least one type", "services"); + throw new ArgumentException("The services must contain at least one type", "services"); } var firstBinding = new Binding(services[0]); @@ -129,7 +127,7 @@ public IBindingToSyntax Bind(params Type[] services) foreach (var service in services.Skip(1)) { - this.AddBinding(new Binding(service, firstBinding.BindingConfiguration)); + this.AddBinding(new Binding(service, firstBinding.BindingConfiguration)); } return new BindingBuilder(firstBinding, this.KernelInstance, string.Join(", ", services.Select(service => service.Format()).ToArray())); @@ -141,7 +139,7 @@ public IBindingToSyntax Bind(params Type[] services) /// The service to unbind. public void Unbind() { - Unbind(typeof(T)); + this.Unbind(typeof(T)); } /// @@ -157,8 +155,8 @@ public void Unbind() /// The fluent syntax public IBindingToSyntax Rebind() { - Unbind(); - return Bind(); + this.Unbind(); + return this.Bind(); } /// @@ -169,9 +167,9 @@ public IBindingToSyntax Rebind() /// The fluent syntax. public IBindingToSyntax Rebind() { - Unbind(); - Unbind(); - return Bind(); + this.Unbind(); + this.Unbind(); + return this.Bind(); } /// @@ -183,10 +181,10 @@ public IBindingToSyntax Rebind() /// The fluent syntax. public IBindingToSyntax Rebind() { - Unbind(); - Unbind(); - Unbind(); - return Bind(); + this.Unbind(); + this.Unbind(); + this.Unbind(); + return this.Bind(); } /// @@ -199,11 +197,11 @@ public IBindingToSyntax Rebind() /// The fluent syntax. public IBindingToSyntax Rebind() { - Unbind(); - Unbind(); - Unbind(); - Unbind(); - return Bind(); + this.Unbind(); + this.Unbind(); + this.Unbind(); + this.Unbind(); + return this.Bind(); } /// @@ -215,10 +213,10 @@ public IBindingToSyntax Rebind(params Type[] services) { foreach (var service in services) { - Unbind(service); + this.Unbind(service); } - return Bind(services); + return this.Bind(services); } /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInNamedWithOrOnSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInNamedWithOrOnSyntax.cs index 40ffb731..9c44b693 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInNamedWithOrOnSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInNamedWithOrOnSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { @@ -27,10 +25,10 @@ namespace Telerik.JustMock.AutoMock.Ninject.Syntax /// Used to set the scope, name, or add additional information or actions to a binding. /// /// The service being bound. - public interface IBindingInNamedWithOrOnSyntax : - IBindingInSyntax, - IBindingNamedSyntax, - IBindingWithSyntax, + public interface IBindingInNamedWithOrOnSyntax : + IBindingInSyntax, + IBindingNamedSyntax, + IBindingWithSyntax, IBindingOnSyntax { } diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInSyntax.cs index 5d3e270f..53aac015 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingInSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedSyntax.cs index bccda9f1..fec05ae8 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedWithOrOnSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedWithOrOnSyntax.cs index 83dc4626..f5e1a83b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedWithOrOnSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingNamedWithOrOnSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingOnSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingOnSyntax.cs index 57f7bfad..a2b3e93b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingOnSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingOnSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingRoot.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingRoot.cs index 79e48e79..951bcb93 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingRoot.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingRoot.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,11 +17,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { using System; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingSyntax.cs index 70686a43..cc92b471 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3,T4}.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3,T4}.cs index d5f52cfe..43b3fb45 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3,T4}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3,T4}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; /// @@ -43,7 +40,7 @@ public interface IBindingToSyntax : IBindingSyntax /// /// The implementation type. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax To() + IBindingWhenInNamedWithOrOnSyntax To() where TImplementation : T1, T2, T3, T4; /// @@ -59,7 +56,8 @@ IBindingWhenInNamedWithOrOnSyntax To() /// /// The type of provider to activate. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider; + IBindingWhenInNamedWithOrOnSyntax ToProvider() + where TProvider : IProvider; /// /// Indicates that the service should be bound to an instance of the specified provider type. @@ -68,7 +66,7 @@ IBindingWhenInNamedWithOrOnSyntax To() /// The type of provider to activate. /// The type of the implementation. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() + IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider where TImplementation : T1, T2, T3, T4; @@ -108,9 +106,8 @@ IBindingWhenInNamedWithOrOnSyntax ToMethod( IBindingWhenInNamedWithOrOnSyntax ToConstant(TImplementation value) where TImplementation : T1, T2, T3, T4; -#if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -118,6 +115,5 @@ IBindingWhenInNamedWithOrOnSyntax ToConstant(T IBindingWhenInNamedWithOrOnSyntax ToConstructor( Expression> newExpression) where TImplementation : T1, T2, T3, T4; -#endif } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3}.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3}.cs index fca0ca92..79fb9a7f 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2,T3}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; /// @@ -42,7 +39,7 @@ public interface IBindingToSyntax : IBindingSyntax /// /// The implementation type. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax To() + IBindingWhenInNamedWithOrOnSyntax To() where TImplementation : T1, T2, T3; /// @@ -58,7 +55,8 @@ IBindingWhenInNamedWithOrOnSyntax To() /// /// The type of provider to activate. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider; + IBindingWhenInNamedWithOrOnSyntax ToProvider() + where TProvider : IProvider; /// /// Indicates that the service should be bound to an instance of the specified provider type. @@ -67,7 +65,7 @@ IBindingWhenInNamedWithOrOnSyntax To() /// The type of provider to activate. /// The type of the implementation. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() + IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider where TImplementation : T1, T2, T3; @@ -107,9 +105,8 @@ IBindingWhenInNamedWithOrOnSyntax ToMethod( IBindingWhenInNamedWithOrOnSyntax ToConstant(TImplementation value) where TImplementation : T1, T2, T3; -#if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -117,6 +114,5 @@ IBindingWhenInNamedWithOrOnSyntax ToConstant(T IBindingWhenInNamedWithOrOnSyntax ToConstructor( Expression> newExpression) where TImplementation : T1, T2, T3; -#endif } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2}.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2}.cs index f1bae6a9..0cfbb04b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1,T2}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; /// @@ -41,7 +38,7 @@ public interface IBindingToSyntax : IBindingSyntax /// /// The implementation type. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax To() + IBindingWhenInNamedWithOrOnSyntax To() where TImplementation : T1, T2; /// @@ -57,7 +54,8 @@ IBindingWhenInNamedWithOrOnSyntax To() /// /// The type of provider to activate. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider; + IBindingWhenInNamedWithOrOnSyntax ToProvider() + where TProvider : IProvider; /// /// Indicates that the service should be bound to an instance of the specified provider type. @@ -66,7 +64,7 @@ IBindingWhenInNamedWithOrOnSyntax To() /// The type of provider to activate. /// The type of the implementation. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() + IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider where TImplementation : T1, T2; @@ -106,9 +104,8 @@ IBindingWhenInNamedWithOrOnSyntax ToMethod( IBindingWhenInNamedWithOrOnSyntax ToConstant(TImplementation value) where TImplementation : T1, T2; -#if !NETCF /// - /// Indicates that the service should be bound to the speecified constructor. + /// Indicates that the service should be bound to the specified constructor. /// /// The type of the implementation. /// The expression that specifies the constructor. @@ -116,6 +113,5 @@ IBindingWhenInNamedWithOrOnSyntax ToConstant(T IBindingWhenInNamedWithOrOnSyntax ToConstructor( Expression> newExpression) where TImplementation : T1, T2; -#endif } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1}.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1}.cs index 1f4a53b7..149fabb5 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1}.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingToSyntax{T1}.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,14 +17,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { using System; -#if !NETCF using System.Linq.Expressions; -#endif + using Telerik.JustMock.AutoMock.Ninject.Activation; /// @@ -46,7 +43,7 @@ public interface IBindingToSyntax : IBindingSyntax /// /// The implementation type. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax To() + IBindingWhenInNamedWithOrOnSyntax To() where TImplementation : T1; /// @@ -62,7 +59,7 @@ IBindingWhenInNamedWithOrOnSyntax To() /// /// The type of provider to activate. /// The fluent syntax. - IBindingWhenInNamedWithOrOnSyntax ToProvider() + IBindingWhenInNamedWithOrOnSyntax ToProvider() where TProvider : IProvider; /// @@ -108,7 +105,6 @@ IBindingWhenInNamedWithOrOnSyntax ToMethod( IBindingWhenInNamedWithOrOnSyntax ToConstant(TImplementation value) where TImplementation : T1; -#if !NETCF /// /// Indicates that the service should be bound to the specified constructor. /// @@ -118,6 +114,5 @@ IBindingWhenInNamedWithOrOnSyntax ToConstant(T IBindingWhenInNamedWithOrOnSyntax ToConstructor( Expression> newExpression) where TImplementation : T1; -#endif } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenInNamedWithOrOnSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenInNamedWithOrOnSyntax.cs index 20f03c7a..74a48d5d 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenInNamedWithOrOnSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenInNamedWithOrOnSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenSyntax.cs index 4968222d..fb262a47 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWhenSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { @@ -68,7 +66,7 @@ public interface IBindingWhenSyntax : IBindingSyntax /// /// Indicates that the binding should be used only for injections on the specified type. /// The type must match exactly the specified type. Types that derive from the specified type - /// will not be considered as valid target. + /// will not be considered as valid target. /// /// The type. /// The fluent syntax. @@ -77,7 +75,7 @@ public interface IBindingWhenSyntax : IBindingSyntax /// /// Indicates that the binding should be used only for injections on the specified type. /// The type must match exactly the specified type. Types that derive from the specified type - /// will not be considered as valid target. + /// will not be considered as valid target. /// /// The type. /// The fluent syntax. @@ -86,7 +84,7 @@ public interface IBindingWhenSyntax : IBindingSyntax /// /// Indicates that the binding should be used only for injections on the specified type. /// The type must match one of the specified types exactly. Types that derive from one of the specified types - /// will not be considered as valid target. + /// will not be considered as valid target. /// Should match at least one of the specified targets /// /// The types. @@ -99,7 +97,8 @@ public interface IBindingWhenSyntax : IBindingSyntax /// /// The type of attribute. /// The fluent syntax. - IBindingInNamedWithOrOnSyntax WhenClassHas() where TAttribute : Attribute; + IBindingInNamedWithOrOnSyntax WhenClassHas() + where TAttribute : Attribute; /// /// Indicates that the binding should be used only when the member being injected has @@ -107,7 +106,8 @@ public interface IBindingWhenSyntax : IBindingSyntax /// /// The type of attribute. /// The fluent syntax. - IBindingInNamedWithOrOnSyntax WhenMemberHas() where TAttribute : Attribute; + IBindingInNamedWithOrOnSyntax WhenMemberHas() + where TAttribute : Attribute; /// /// Indicates that the binding should be used only when the target being injected has @@ -115,7 +115,8 @@ public interface IBindingWhenSyntax : IBindingSyntax /// /// The type of attribute. /// The fluent syntax. - IBindingInNamedWithOrOnSyntax WhenTargetHas() where TAttribute : Attribute; + IBindingInNamedWithOrOnSyntax WhenTargetHas() + where TAttribute : Attribute; /// /// Indicates that the binding should be used only when the class being injected has @@ -170,7 +171,7 @@ public interface IBindingWhenSyntax : IBindingSyntax /// The name to expect. /// The fluent syntax. IBindingInNamedWithOrOnSyntax WhenNoAncestorNamed(string name); - + /// /// Indicates that the binding should be used only when any ancestor matches the specified predicate. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithOrOnSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithOrOnSyntax.cs index 6e207a87..9aa97f44 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithOrOnSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithOrOnSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithSyntax.cs index a5bb2c2e..20cea215 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IBindingWithSyntax.cs @@ -1,12 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2007-2009, Enkari, Ltd. -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Nate Kohari (nate@enkari.com) -// Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -19,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { @@ -59,6 +57,54 @@ public interface IBindingWithSyntax : IBindingSyntax /// The fluent syntax. IBindingWithOrOnSyntax WithConstructorArgument(string name, Func callback); + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// Specifies the argument type to override. + /// The value for the argument. + /// The fluent syntax. + IBindingWithOrOnSyntax WithConstructorArgument(TValue value); + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The value for the argument. + /// The fluent syntax. + IBindingWithOrOnSyntax WithConstructorArgument(Type type, object value); + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + IBindingWithOrOnSyntax WithConstructorArgument(Func callback); + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + IBindingWithOrOnSyntax WithConstructorArgument(Type type, Func callback); + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + IBindingWithOrOnSyntax WithConstructorArgument(Func callback); + + /// + /// Indicates that the specified constructor argument should be overridden with the specified value. + /// + /// The type of the argument to override. + /// The callback to invoke to get the value for the argument. + /// The fluent syntax. + IBindingWithOrOnSyntax WithConstructorArgument(Type type, Func callback); + /// /// Indicates that the specified property should be injected with the specified value. /// diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IConstructorArgumentSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IConstructorArgumentSyntax.cs index f5130ac3..e976815b 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IConstructorArgumentSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IConstructorArgumentSyntax.cs @@ -1,10 +1,10 @@ -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- // -// Copyright (c) 2009-2011 Ninject Project Contributors -// Authors: Remo Gloor (remo.gloor@gmail.com) -// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// you may not use this file except in compliance with one of the Licenses. +// You may not use this file except in compliance with one of the Licenses. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 @@ -17,7 +17,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//------------------------------------------------------------------------------- +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IFluentSyntax.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IFluentSyntax.cs index 426e17a3..aebf39db 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IFluentSyntax.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IFluentSyntax.cs @@ -1,19 +1,29 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.ComponentModel; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { + using System; + using System.ComponentModel; + /// /// A hack to hide methods defined on for IntelliSense /// on fluent interfaces. Credit to Daniel Cazzulino. @@ -32,28 +42,28 @@ public interface IFluentSyntax /// Returns a hash code for this instance. /// /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// - [EditorBrowsable(EditorBrowsableState.Never)] + [EditorBrowsable(EditorBrowsableState.Never)] int GetHashCode(); /// - /// Returns a that represents this instance. + /// Returns a that represents this instance. /// /// - /// A that represents this instance. + /// A that represents this instance. /// - [EditorBrowsable(EditorBrowsableState.Never)] + [EditorBrowsable(EditorBrowsableState.Never)] string ToString(); /// - /// Determines whether the specified is equal to this instance. + /// Determines whether the specified is equal to this instance. /// - /// The to compare with this instance. + /// The to compare with this instance. /// - /// true if the specified is equal to this instance; otherwise, false. + /// true if the specified is equal to this instance; otherwise, false. /// - [EditorBrowsable(EditorBrowsableState.Never)] + [EditorBrowsable(EditorBrowsableState.Never)] bool Equals(object other); } } \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/IResolutionRoot.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/IResolutionRoot.cs index cac28bae..e0acc339 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/IResolutionRoot.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/IResolutionRoot.cs @@ -1,27 +1,45 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject.Syntax { + using System; + using System.Collections.Generic; + + using Telerik.JustMock.AutoMock.Ninject.Activation; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + /// /// Provides a path to resolve instances. /// public interface IResolutionRoot : IFluentSyntax { + /// + /// Injects the specified existing instance, without managing its lifecycle. + /// + /// The instance to inject. + /// The parameters to pass to the request. + void Inject(object instance, params IParameter[] parameters); + /// /// Determines whether the specified request can be resolved. /// @@ -38,7 +56,7 @@ public interface IResolutionRoot : IFluentSyntax /// True if the request can be resolved; otherwise, false. /// bool CanResolve(IRequest request, bool ignoreImplicitBindings); - + /// /// Resolves instances for the specified request. The instances are not actually resolved /// until a consumer iterates over the enumerator. diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/ModuleLoadExtensions.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/ModuleLoadExtensions.cs index 65810196..a306dbe4 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/ModuleLoadExtensions.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/ModuleLoadExtensions.cs @@ -1,21 +1,31 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Reflection; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Modules; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System.Reflection; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Modules; + /// /// Extension methods that enhance module loading. /// @@ -43,7 +53,6 @@ public static void Load(this IKernel kernel, params INinjectModule[] modules) kernel.Load(modules); } - #if !NO_ASSEMBLY_SCANNING /// /// Loads modules from the files that match the specified pattern(s). /// @@ -63,6 +72,5 @@ public static void Load(this IKernel kernel, params Assembly[] assemblies) { kernel.Load(assemblies); } - #endif } -} +} \ No newline at end of file diff --git a/Telerik.JustMock/AutoMock/Ninject/Syntax/ResolutionExtensions.cs b/Telerik.JustMock/AutoMock/Ninject/Syntax/ResolutionExtensions.cs index d980e18d..61418113 100644 --- a/Telerik.JustMock/AutoMock/Ninject/Syntax/ResolutionExtensions.cs +++ b/Telerik.JustMock/AutoMock/Ninject/Syntax/ResolutionExtensions.cs @@ -1,25 +1,35 @@ -#region License -// -// Author: Nate Kohari -// Copyright (c) 2007-2010, Enkari, Ltd. -// -// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). -// See the file LICENSE.txt for details. -// -#endregion -#region Using Directives -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.JustMock.AutoMock.Ninject.Activation; -using Telerik.JustMock.AutoMock.Ninject.Infrastructure; -using Telerik.JustMock.AutoMock.Ninject.Parameters; -using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; -using Telerik.JustMock.AutoMock.Ninject.Syntax; -#endregion +// ------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2007-2010 Enkari, Ltd. All rights reserved. +// Copyright (c) 2010-2017 Ninject Project Contributors. All rights reserved. +// +// Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). +// You may not use this file except in compliance with one of the Licenses. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// or +// http://www.microsoft.com/opensource/licenses.mspx +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ------------------------------------------------------------------------------------------------- namespace Telerik.JustMock.AutoMock.Ninject { + using System; + using System.Collections.Generic; + using System.Linq; + + using Telerik.JustMock.AutoMock.Ninject.Infrastructure; + using Telerik.JustMock.AutoMock.Ninject.Parameters; + using Telerik.JustMock.AutoMock.Ninject.Planning.Bindings; + using Telerik.JustMock.AutoMock.Ninject.Syntax; + /// /// Extensions that enhance resolution of services. /// @@ -72,7 +82,7 @@ public static T Get(this IResolutionRoot root, Func c /// An instance of the service, or if no implementation was available. public static T TryGet(this IResolutionRoot root, params IParameter[] parameters) { - return TryGet(GetResolutionIterator(root, typeof(T), null, parameters, true, true).Cast()); + return TryGet(() => GetResolutionIterator(root, typeof(T), null, parameters, true, true).Cast()); } /// @@ -85,7 +95,7 @@ public static T TryGet(this IResolutionRoot root, params IParameter[] paramet /// An instance of the service, or if no implementation was available. public static T TryGet(this IResolutionRoot root, string name, params IParameter[] parameters) { - return TryGet(GetResolutionIterator(root, typeof(T), b => b.Name == name, parameters, true, true).Cast()); + return TryGet(() => GetResolutionIterator(root, typeof(T), b => b.Name == name, parameters, true, true).Cast()); } /// @@ -98,7 +108,45 @@ public static T TryGet(this IResolutionRoot root, string name, params IParame /// An instance of the service, or if no implementation was available. public static T TryGet(this IResolutionRoot root, Func constraint, params IParameter[] parameters) { - return TryGet(GetResolutionIterator(root, typeof(T), constraint, parameters, true, true).Cast()); + return TryGet(() => GetResolutionIterator(root, typeof(T), constraint, parameters, true, true).Cast()); + } + + /// + /// Tries to get an instance of the specified service. + /// + /// The service to resolve. + /// The resolution root. + /// The parameters to pass to the request. + /// An instance of the service, or if no implementation was available. + public static T TryGetAndThrowOnInvalidBinding(this IResolutionRoot root, params IParameter[] parameters) + { + return DoTryGetAndThrowOnInvalidBinding(root, null, parameters); + } + + /// + /// Tries to get an instance of the specified service by using the first binding with the specified name. + /// + /// The service to resolve. + /// The resolution root. + /// The name of the binding. + /// The parameters to pass to the request. + /// An instance of the service, or if no implementation was available. + public static T TryGetAndThrowOnInvalidBinding(this IResolutionRoot root, string name, params IParameter[] parameters) + { + return DoTryGetAndThrowOnInvalidBinding(root, b => b.Name == name, parameters); + } + + /// + /// Tries to get an instance of the specified service by using the first binding that matches the specified constraint. + /// + /// The service to resolve. + /// The resolution root. + /// The constraint to apply to the binding. + /// The parameters to pass to the request. + /// An instance of the service, or if no implementation was available. + public static T TryGetAndThrowOnInvalidBinding(this IResolutionRoot root, Func constraint, params IParameter[] parameters) + { + return DoTryGetAndThrowOnInvalidBinding(root, constraint, parameters); } /// @@ -186,7 +234,7 @@ public static object Get(this IResolutionRoot root, Type service, FuncAn instance of the service, or if no implementation was available. public static object TryGet(this IResolutionRoot root, Type service, params IParameter[] parameters) { - return TryGet(GetResolutionIterator(root, service, null, parameters, true, true)); + return TryGet(() => GetResolutionIterator(root, service, null, parameters, true, true)); } /// @@ -199,7 +247,7 @@ public static object TryGet(this IResolutionRoot root, Type service, params IPar /// An instance of the service, or if no implementation was available. public static object TryGet(this IResolutionRoot root, Type service, string name, params IParameter[] parameters) { - return TryGet(GetResolutionIterator(root, service, b => b.Name == name, parameters, true, false)); + return TryGet(() => GetResolutionIterator(root, service, b => b.Name == name, parameters, true, true)); } /// @@ -212,7 +260,7 @@ public static object TryGet(this IResolutionRoot root, Type service, string name /// An instance of the service, or if no implementation was available. public static object TryGet(this IResolutionRoot root, Type service, Func constraint, params IParameter[] parameters) { - return TryGet(GetResolutionIterator(root, service, constraint, parameters, true, false)); + return TryGet(() => GetResolutionIterator(root, service, constraint, parameters, true, true)); } /// @@ -259,7 +307,7 @@ public static IEnumerable GetAll(this IResolutionRoot root, Type service /// The service to resolve. /// The resolution root. /// The parameters to pass to the request. - /// An instance of the service. + /// True if the request can be resolved; otherwise, false. public static bool CanResolve(this IResolutionRoot root, params IParameter[] parameters) { return CanResolve(root, typeof(T), null, parameters, false, true); @@ -272,7 +320,7 @@ public static bool CanResolve(this IResolutionRoot root, params IParameter[] /// The resolution root. /// The name of the binding. /// The parameters to pass to the request. - /// An instance of the service. + /// True if the request can be resolved; otherwise, false. public static bool CanResolve(this IResolutionRoot root, string name, params IParameter[] parameters) { return CanResolve(root, typeof(T), b => b.Name == name, parameters, false, true); @@ -285,7 +333,7 @@ public static bool CanResolve(this IResolutionRoot root, string name, params /// The resolution root. /// The constraint to apply to the binding. /// The parameters to pass to the request. - /// An instance of the service. + /// True if the request can be resolved; otherwise, false. public static bool CanResolve(this IResolutionRoot root, Func constraint, params IParameter[] parameters) { return CanResolve(root, typeof(T), constraint, parameters, false, true); @@ -297,8 +345,8 @@ public static bool CanResolve(this IResolutionRoot root, FuncThe resolution root. /// The service to resolve. /// The parameters to pass to the request. - /// An instance of the service. - public static object CanResolve(this IResolutionRoot root, Type service, params IParameter[] parameters) + /// True if the request can be resolved; otherwise, false. + public static bool CanResolve(this IResolutionRoot root, Type service, params IParameter[] parameters) { return CanResolve(root, service, null, parameters, false, true); } @@ -310,8 +358,8 @@ public static object CanResolve(this IResolutionRoot root, Type service, params /// The service to resolve. /// The name of the binding. /// The parameters to pass to the request. - /// An instance of the service. - public static object CanResolve(this IResolutionRoot root, Type service, string name, params IParameter[] parameters) + /// True if the request can be resolved; otherwise, false. + public static bool CanResolve(this IResolutionRoot root, Type service, string name, params IParameter[] parameters) { return CanResolve(root, service, b => b.Name == name, parameters, false, true); } @@ -323,8 +371,8 @@ public static object CanResolve(this IResolutionRoot root, Type service, string /// The service to resolve. /// The constraint to apply to the binding. /// The parameters to pass to the request. - /// An instance of the service. - public static object CanResolve(this IResolutionRoot root, Type service, Func constraint, params IParameter[] parameters) + /// True if the request can be resolved; otherwise, false. + public static bool CanResolve(this IResolutionRoot root, Type service, Func constraint, params IParameter[] parameters) { return CanResolve(root, service, constraint, parameters, false, true); } @@ -335,7 +383,7 @@ private static bool CanResolve(IResolutionRoot root, Type service, Func GetResolutionIterator(IResolutionRoot root, T Ensure.ArgumentNotNull(service, "service"); Ensure.ArgumentNotNull(parameters, "parameters"); - IRequest request = root.CreateRequest(service, constraint, parameters, isOptional, isUnique); + var request = root.CreateRequest(service, constraint, parameters, isOptional, isUnique); + return root.Resolve(request); + } + + private static IEnumerable GetResolutionIterator(IResolutionRoot root, Type service, Func constraint, IEnumerable parameters, bool isOptional, bool isUnique, bool forceUnique) + { + Ensure.ArgumentNotNull(root, "root"); + Ensure.ArgumentNotNull(service, "service"); + Ensure.ArgumentNotNull(parameters, "parameters"); + + var request = root.CreateRequest(service, constraint, parameters, isOptional, isUnique); + request.ForceUnique = forceUnique; return root.Resolve(request); } - private static T TryGet(IEnumerable iterator) + private static T TryGet(Func> iterator) { try { - return iterator.SingleOrDefault(); + return iterator().SingleOrDefault(); } catch (ActivationException) { return default(T); } } + + private static T DoTryGetAndThrowOnInvalidBinding(IResolutionRoot root, Func constraint, IEnumerable parameters) + { + return GetResolutionIterator(root, typeof(T), constraint, parameters, true, true, true).Cast().SingleOrDefault(); + } } } diff --git a/Telerik.JustMock/AutoMock/Ninject/VERSION b/Telerik.JustMock/AutoMock/Ninject/VERSION new file mode 100644 index 00000000..eedb52ba --- /dev/null +++ b/Telerik.JustMock/AutoMock/Ninject/VERSION @@ -0,0 +1 @@ +3.3.6 \ No newline at end of file diff --git a/Telerik.JustMock/Telerik.JustMock.csproj b/Telerik.JustMock/Telerik.JustMock.csproj index caabf301..75251cf7 100644 --- a/Telerik.JustMock/Telerik.JustMock.csproj +++ b/Telerik.JustMock/Telerik.JustMock.csproj @@ -1,7 +1,8 @@  + net45;net472 netcoreapp2.0 - net45;net472;$(NetCoreSupportedVersions) + $(NetFxSupportedVersions);$(NetCoreSupportedVersions) Debug;Release;ReleaseFree;DebugFree Telerik.JustMock Telerik.JustMock @@ -10,7 +11,6 @@ false false - NO_EXCEPTION_SERIALIZATION Debug AnyCPU {0749EBC2-4E83-4960-BF28-1FF5C2DEB2B9} @@ -26,7 +26,7 @@ full false ..\..\..\Binaries\Debug\ - $(CommonConstants);TRACE;DEBUG + TRACE;DEBUG prompt 4 @@ -34,14 +34,14 @@ pdbonly true ..\..\..\Binaries\Release\ - $(CommonConstants);TRACE + TRACE prompt 4 ..\..\..\Binaries\Release\Telerik.JustMock.xml ..\..\..\Binaries\ReleaseFree\ - $(CommonConstants);TRACE;LITE_EDITION + TRACE;LITE_EDITION true pdbonly AnyCPU @@ -53,19 +53,19 @@ true ..\..\..\Binaries\DebugFree\ - $(CommonConstants);TRACE;DEBUG;LITE_EDITION + TRACE;DEBUG;LITE_EDITION full AnyCPU prompt MinimumRecommendedRules.ruleset - + $(DefineConstants);FEATURE_APPDOMAIN;FEATURE_ASSEMBLYBUILDER_SAVE - $(DefineConstants);NETCORE;NO_APPDOMAIN_ISOLATION + $(DefineConstants);NETCORE;NO_ASSEMBLY_SCANNING;NO_REMOTING - + From bfeed97319f347e5786615673cb0caf2b51953a3 Mon Sep 17 00:00:00 2001 From: Ivo Stoilov Date: Tue, 13 Feb 2024 17:58:24 +0200 Subject: [PATCH 9/9] Fix API reference (#205) --- .../DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs | 1 + .../DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs | 1 + .../Generators/Emitters/SimpleAST/IndirectReference.cs | 1 + .../Castle.DynamicProxy/Generators/MethodFinder.cs | 1 + .../Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs | 3 ++- .../Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs | 1 + .../Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs | 1 + .../DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs | 1 + .../DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs | 1 + .../Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs | 1 + .../Serialization/CacheMappingsAttribute.cs | 1 + .../Castle.DynamicProxy/Serialization/ProxyObjectReference.cs | 1 + 12 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs index 907d6641..9da23640 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/CustomAttributeInfo.cs @@ -29,6 +29,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy /// Arrays passed to this class as constructor arguments or property or field values become owned by this class. /// They should not be mutated after creation. /// + /// internal class CustomAttributeInfo : IEquatable { // Cached empty arrays to avoid unnecessary allocations diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs index ba966954..8b533c1d 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/DefaultProxyBuilder.cs @@ -26,6 +26,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy /// /// Default implementation of interface producing in-memory proxy assemblies. /// + /// internal class DefaultProxyBuilder : IProxyBuilder { private readonly ModuleScope scope; diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs index c0d37f52..b690834a 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/Emitters/SimpleAST/IndirectReference.cs @@ -23,6 +23,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAS /// Wraps a reference that is passed /// ByRef and provides indirect load/store support. /// + /// [DebuggerDisplay("&{OwnerReference}")] internal class IndirectReference : TypeReference { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs index bb7057a4..6f3be81e 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Generators/MethodFinder.cs @@ -23,6 +23,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators /// Returns the methods implemented by a type. Use this instead of Type.GetMethods() to work around a CLR issue /// where duplicate MethodInfos are returned by Type.GetMethods() after a token of a generic type's method was loaded. /// + /// internal class MethodFinder { private static readonly Dictionary cachedMethodInfosByType = new Dictionary(); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs index 3e483a05..55a9c91f 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/IProxyGenerator.cs @@ -22,6 +22,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy /// /// Provides proxy objects for classes and interfaces. /// + /// [CLSCompliant(true)] internal interface IProxyGenerator { @@ -1030,4 +1031,4 @@ object CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, object[] constructorArguments, params IInterceptor[] interceptors); } -} \ No newline at end of file +} diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs index d52a5410..12dcc974 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/MixinData.cs @@ -23,6 +23,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy using Telerik.JustMock.Core.Castle.DynamicProxy.Generators; using Telerik.JustMock.Core.Castle.DynamicProxy.Internal; + /// internal class MixinData { private readonly Dictionary mixinPositions = new Dictionary(); diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs index 2e099701..f6e512e2 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ModuleScope.cs @@ -30,6 +30,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization; #endif + /// internal class ModuleScope { /// diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs index 842cd91c..ee8bf727 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/PersistentProxyBuilder.cs @@ -22,6 +22,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy /// /// The saved assembly contains just the last generated type. /// + /// internal class PersistentProxyBuilder : DefaultProxyBuilder { /// diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs index 4c8c24f4..9a9b560b 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerationOptions.cs @@ -33,6 +33,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy /// used to create a proxy (or proxy type). /// /// + /// #if FEATURE_SERIALIZATION [Serializable] #endif diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs index 7857a05b..636f1a49 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/ProxyGenerator.cs @@ -26,6 +26,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy /// /// Provides proxy objects for classes and interfaces. /// + /// [CLSCompliant(true)] internal class ProxyGenerator : IProxyGenerator { diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs index a039a402..e33afad4 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/CacheMappingsAttribute.cs @@ -28,6 +28,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Serialization /// /// Applied to the assemblies saved by in order to persist the cache data included in the persisted assembly. /// + /// [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] [CLSCompliant(false)] internal class CacheMappingsAttribute : Attribute diff --git a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs index 4ae099a8..726bd851 100644 --- a/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs +++ b/Telerik.JustMock/Core/DynamicProxy/Castle.DynamicProxy/Serialization/ProxyObjectReference.cs @@ -28,6 +28,7 @@ namespace Telerik.JustMock.Core.Castle.DynamicProxy.Serialization /// /// Handles the deserialization of proxies. /// + /// [Serializable] internal class ProxyObjectReference : IObjectReference, ISerializable, IDeserializationCallback {