How to use CacheMappingsAttribute class of Telerik.JustMock.Core.Castle.DynamicProxy.Serialization package

Best JustMockLite code snippet using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization.CacheMappingsAttribute

Run JustMockLite automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

CacheMappingsAttribute.cs

Source: CacheMappingsAttribute.cs Github

copy
1// Copyright 2004-2012 Castle Project - http://www.castleproject.org/
2// 
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// 
7//   http://www.apache.org/licenses/LICENSE-2.0
8// 
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#if FEATURE_SERIALIZATION
16
17namespace Telerik.JustMock.Core.Castle.DynamicProxy.Serialization
18{
19	using System;
20	using System.Collections.Generic;
21	using System.IO;
22	using System.Reflection;
23	using System.Reflection.Emit;
24	using System.Runtime.Serialization.Formatters.Binary;
25
26	using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
27
28	/// <summary>
29	///   Applied to the assemblies saved by <see cref="ModuleScope" /> in order to persist the cache data included in the persisted assembly.
30	/// </summary>
31	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
32	[CLSCompliant(false)]
33	internal class CacheMappingsAttribute : Attribute
34	{
35		private static readonly ConstructorInfo constructor =
36			typeof(CacheMappingsAttribute).GetConstructor(new[] { typeof(byte[]) });
37
38		private readonly byte[] serializedCacheMappings;
39
40		public CacheMappingsAttribute(byte[] serializedCacheMappings)
41		{
42			this.serializedCacheMappings = serializedCacheMappings;
43		}
44
45		public byte[] SerializedCacheMappings
46		{
47			get { return serializedCacheMappings; }
48		}
49
50		public Dictionary<CacheKey, string> GetDeserializedMappings()
51		{
52			using (var stream = new MemoryStream(SerializedCacheMappings))
53			{
54				var formatter = new BinaryFormatter();
55				return (Dictionary<CacheKey, string>)formatter.Deserialize(stream);
56			}
57		}
58
59		public static void ApplyTo(AssemblyBuilder assemblyBuilder, Dictionary<CacheKey, string> mappings)
60		{
61			using (var stream = new MemoryStream())
62			{
63				var formatter = new BinaryFormatter();
64				formatter.Serialize(stream, mappings);
65				var bytes = stream.ToArray();
66				var attributeBuilder = new CustomAttributeBuilder(constructor, new object[] { bytes });
67				assemblyBuilder.SetCustomAttribute(attributeBuilder);
68			}
69		}
70	}
71}
72
73#endif
Full Screen

ModuleScope.cs

Source: ModuleScope.cs Github

copy
1// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
2// 
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// 
7//   http://www.apache.org/licenses/LICENSE-2.0
8// 
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15namespace Telerik.JustMock.Core.Castle.DynamicProxy
16{
17    using System;
18    using System.Collections.Generic;
19    using System.IO;
20    using System.Reflection;
21    using System.Reflection.Emit;
22    using System.Resources;
23
24    using Telerik.JustMock.Core.Castle.Core.Internal;
25    using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
26    using Telerik.JustMock.Core.DynamicProxy;
27#if FEATURE_SERIALIZATION
28    using Telerik.JustMock.Core.Castle.DynamicProxy.Serialization;
29#endif
30
31    /// <summary>
32    ///   Summary description for ModuleScope.
33    /// </summary>
34    internal class ModuleScope
35    {
36        /// <summary>
37        ///   The default file name used when the assembly is saved using <see cref = "DEFAULT_FILE_NAME" />.
38        /// </summary>
39        public static readonly String DEFAULT_FILE_NAME = "Telerik.JustMock.Dynamic.dll";
40
41        /// <summary>
42        ///   The default assembly (simple) name used for the assemblies generated by a <see cref = "ModuleScope" /> instance.
43        /// </summary>
44        public static readonly String DEFAULT_ASSEMBLY_NAME = "Telerik.JustMock";
45
46        private ModuleBuilder moduleBuilderWithStrongName;
47        private ModuleBuilder moduleBuilder;
48
49        // The names to use for the generated assemblies and the paths (including the names) of their manifest modules
50        private readonly string strongAssemblyName;
51        private readonly string weakAssemblyName;
52        private readonly string strongModulePath;
53        private readonly string weakModulePath;
54
55        // Keeps track of generated types
56        private readonly Dictionary<CacheKey, Type> typeCache = new Dictionary<CacheKey, Type>();
57
58        // Users of ModuleScope should use this lock when accessing the cache
59        private readonly Lock cacheLock = Lock.Create();
60
61        // Used to lock the module builder creation
62        private readonly object moduleLocker = new object();
63
64        // Specified whether the generated assemblies are intended to be saved
65        private readonly bool savePhysicalAssembly;
66        private readonly bool disableSignedModule;
67        private readonly INamingScope namingScope;
68
69        /// <summary>
70        ///   Initializes a new instance of the <see cref = "ModuleScope" /> class; assemblies created by this instance will not be saved.
71        /// </summary>
72        public ModuleScope() : this(false, false)
73        {
74        }
75
76        /// <summary>
77        ///   Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
78        ///   should be saved.
79        /// </summary>
80        /// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
81        public ModuleScope(bool savePhysicalAssembly)
82            : this(savePhysicalAssembly, false)
83        {
84        }
85
86        /// <summary>
87        ///   Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
88        ///   should be saved.
89        /// </summary>
90        /// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
91        /// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
92        public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule)
93            : this(
94                savePhysicalAssembly, disableSignedModule, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME,
95                DEFAULT_FILE_NAME)
96        {
97        }
98
99        /// <summary>
100        ///   Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
101        ///   should be saved and what simple names are to be assigned to them.
102        /// </summary>
103        /// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
104        /// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
105        /// <param name = "strongAssemblyName">The simple name of the strong-named assembly generated by this <see
106        ///    cref = "ModuleScope" />.</param>
107        /// <param name = "strongModulePath">The path and file name of the manifest module of the strong-named assembly generated by this <see
108        ///    cref = "ModuleScope" />.</param>
109        /// <param name = "weakAssemblyName">The simple name of the weak-named assembly generated by this <see cref = "ModuleScope" />.</param>
110        /// <param name = "weakModulePath">The path and file name of the manifest module of the weak-named assembly generated by this <see
111        ///    cref = "ModuleScope" />.</param>
112        public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, string strongAssemblyName,
113                           string strongModulePath,
114                           string weakAssemblyName, string weakModulePath)
115            : this(
116                savePhysicalAssembly, disableSignedModule, new NamingScope(), strongAssemblyName, strongModulePath, weakAssemblyName,
117                weakModulePath)
118        {
119        }
120
121        /// <summary>
122        ///   Initializes a new instance of the <see cref = "ModuleScope" /> class, allowing to specify whether the assemblies generated by this instance
123        ///   should be saved and what simple names are to be assigned to them.
124        /// </summary>
125        /// <param name = "savePhysicalAssembly">If set to <c>true</c> saves the generated module.</param>
126        /// <param name = "disableSignedModule">If set to <c>true</c> disables ability to generate signed module. This should be used in cases where ran under constrained permissions.</param>
127        /// <param name = "namingScope">Naming scope used to provide unique names to generated types and their members (usually via sub-scopes).</param>
128        /// <param name = "strongAssemblyName">The simple name of the strong-named assembly generated by this <see
129        ///    cref = "ModuleScope" />.</param>
130        /// <param name = "strongModulePath">The path and file name of the manifest module of the strong-named assembly generated by this <see
131        ///    cref = "ModuleScope" />.</param>
132        /// <param name = "weakAssemblyName">The simple name of the weak-named assembly generated by this <see cref = "ModuleScope" />.</param>
133        /// <param name = "weakModulePath">The path and file name of the manifest module of the weak-named assembly generated by this <see
134        ///    cref = "ModuleScope" />.</param>
135        public ModuleScope(bool savePhysicalAssembly, bool disableSignedModule, INamingScope namingScope,
136                           string strongAssemblyName, string strongModulePath,
137                           string weakAssemblyName, string weakModulePath)
138        {
139            this.savePhysicalAssembly = savePhysicalAssembly;
140            this.disableSignedModule = disableSignedModule;
141            this.namingScope = namingScope;
142            this.strongAssemblyName = strongAssemblyName;
143            this.strongModulePath = strongModulePath;
144            this.weakAssemblyName = weakAssemblyName;
145            this.weakModulePath = weakModulePath;
146        }
147
148        public INamingScope NamingScope
149        {
150            get { return namingScope; }
151        }
152
153        /// <summary>
154        ///   Users of this <see cref = "ModuleScope" /> should use this lock when accessing the cache.
155        /// </summary>
156        public Lock Lock
157        {
158            get { return cacheLock; }
159        }
160
161        /// <summary>
162        ///   Returns a type from this scope's type cache, or null if the key cannot be found.
163        /// </summary>
164        /// <param name = "key">The key to be looked up in the cache.</param>
165        /// <returns>The type from this scope's type cache matching the key, or null if the key cannot be found</returns>
166        public Type GetFromCache(CacheKey key)
167        {
168            Type type;
169            typeCache.TryGetValue(key, out type);
170            return type;
171        }
172
173        /// <summary>
174        ///   Registers a type in this scope's type cache.
175        /// </summary>
176        /// <param name = "key">The key to be associated with the type.</param>
177        /// <param name = "type">The type to be stored in the cache.</param>
178        public void RegisterInCache(CacheKey key, Type type)
179        {
180            typeCache[key] = type;
181        }
182
183        /// <summary>
184        ///   Gets the key pair used to sign the strong-named assembly generated by this <see cref = "ModuleScope" />.
185        /// </summary>
186        /// <returns></returns>
187        public static byte[] GetKeyPair()
188        {
189            string snkeyName = DEFAULT_ASSEMBLY_NAME + ".Core.DynamicProxy.DynamicProxy.snk";
190
191            var assembly = typeof(ModuleScope).GetTypeInfo().Assembly;
192
193            using (var stream = typeof(ModuleScope).GetTypeInfo().Assembly.GetManifestResourceStream(snkeyName))
194            {
195                if (stream == null)
196                {
197                    throw new MissingManifestResourceException(
198                        "Should have a "+ snkeyName + " as an embedded resource, so Dynamic Proxy could sign generated assembly");
199                }
200
201                var length = (int)stream.Length;
202                var keyPair = new byte[length];
203                stream.Read(keyPair, 0, length);
204                return keyPair;
205            }
206        }
207
208        /// <summary>
209        ///   Gets the strong-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.
210        /// </summary>
211        /// <value>The strong-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.</value>
212        public ModuleBuilder StrongNamedModule
213        {
214            get { return moduleBuilderWithStrongName; }
215        }
216
217        /// <summary>
218        ///   Gets the file name of the strongly named module generated by this scope.
219        /// </summary>
220        /// <value>The file name of the strongly named module generated by this scope.</value>
221        public string StrongNamedModuleName
222        {
223            get { return Path.GetFileName(strongModulePath); }
224        }
225
226#if FEATURE_ASSEMBLYBUILDER_SAVE
227        /// <summary>
228        ///   Gets the directory where the strongly named module generated by this scope will be saved, or <see langword = "null" /> if the current directory
229        ///   is used.
230        /// </summary>
231        /// <value>The directory where the strongly named module generated by this scope will be saved when <see
232        ///    cref = "SaveAssembly()" /> is called
233        ///   (if this scope was created to save modules).</value>
234        public string StrongNamedModuleDirectory
235        {
236            get
237            {
238                var directory = Path.GetDirectoryName(strongModulePath);
239                if (string.IsNullOrEmpty(directory))
240                {
241                    return null;
242                }
243                return directory;
244            }
245        }
246#endif
247
248        /// <summary>
249        ///   Gets the weak-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.
250        /// </summary>
251        /// <value>The weak-named module generated by this scope, or <see langword = "null" /> if none has yet been generated.</value>
252        public ModuleBuilder WeakNamedModule
253        {
254            get { return moduleBuilder; }
255        }
256
257        /// <summary>
258        ///   Gets the file name of the weakly named module generated by this scope.
259        /// </summary>
260        /// <value>The file name of the weakly named module generated by this scope.</value>
261        public string WeakNamedModuleName
262        {
263            get { return Path.GetFileName(weakModulePath); }
264        }
265
266#if FEATURE_ASSEMBLYBUILDER_SAVE
267        /// <summary>
268        ///   Gets the directory where the weakly named module generated by this scope will be saved, or <see langword = "null" /> if the current directory
269        ///   is used.
270        /// </summary>
271        /// <value>The directory where the weakly named module generated by this scope will be saved when <see
272        ///    cref = "SaveAssembly()" /> is called
273        ///   (if this scope was created to save modules).</value>
274        public string WeakNamedModuleDirectory
275        {
276            get
277            {
278                var directory = Path.GetDirectoryName(weakModulePath);
279                if (directory == string.Empty)
280                {
281                    return null;
282                }
283                return directory;
284            }
285        }
286#endif
287
288        /// <summary>
289        ///   Gets the specified module generated by this scope, creating a new one if none has yet been generated.
290        /// </summary>
291        /// <param name = "isStrongNamed">If set to true, a strong-named module is returned; otherwise, a weak-named module is returned.</param>
292        /// <returns>A strong-named or weak-named module generated by this scope, as specified by the <paramref
293        ///    name = "isStrongNamed" /> parameter.</returns>
294        public ModuleBuilder ObtainDynamicModule(bool isStrongNamed)
295        {
296            if (isStrongNamed)
297            {
298                return ObtainDynamicModuleWithStrongName();
299            }
300
301            return ObtainDynamicModuleWithWeakName();
302        }
303
304        /// <summary>
305        ///   Gets the strong-named module generated by this scope, creating a new one if none has yet been generated.
306        /// </summary>
307        /// <returns>A strong-named module generated by this scope.</returns>
308        public ModuleBuilder ObtainDynamicModuleWithStrongName()
309        {
310            if (disableSignedModule)
311            {
312                throw new InvalidOperationException(
313                    "Usage of signed module has been disabled. Use unsigned module or enable signed module.");
314            }
315            lock (moduleLocker)
316            {
317                if (moduleBuilderWithStrongName == null)
318                {
319                    moduleBuilderWithStrongName = CreateModule(true);
320                }
321                return moduleBuilderWithStrongName;
322            }
323        }
324
325        /// <summary>
326        ///   Gets the weak-named module generated by this scope, creating a new one if none has yet been generated.
327        /// </summary>
328        /// <returns>A weak-named module generated by this scope.</returns>
329        public ModuleBuilder ObtainDynamicModuleWithWeakName()
330        {
331            lock (moduleLocker)
332            {
333                if (moduleBuilder == null)
334                {
335                    moduleBuilder = CreateModule(false);
336                }
337                return moduleBuilder;
338            }
339        }
340
341        private ModuleBuilder CreateModule(bool signStrongName)
342        {
343            var assemblyName = GetAssemblyName(signStrongName);
344            var moduleName = signStrongName ? StrongNamedModuleName : WeakNamedModuleName;
345#if FEATURE_APPDOMAIN
346            if (savePhysicalAssembly)
347            {
348                AssemblyBuilder assemblyBuilder;
349                try
350                {
351                    assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
352                        assemblyName, AssemblyBuilderAccess.RunAndSave, signStrongName ? StrongNamedModuleDirectory : WeakNamedModuleDirectory);
353                }
354                catch (ArgumentException e)
355                {
356                    if (signStrongName == false && e.StackTrace.Contains("ComputePublicKey") == false)
357                    {
358                        // I have no idea what that could be
359                        throw;
360                    }
361                    var message = string.Format(
362                        "There was an error creating dynamic assembly for your proxies - you don't have permissions " +
363                        "required to sign the assembly. To workaround it you can enforce generating non-signed assembly " +
364                        "only when creating {0}. Alternatively ensure that your account has all the required permissions.",
365                        GetType());
366                    throw new ArgumentException(message, e);
367                }
368                var module = assemblyBuilder.DefineDynamicModule(moduleName, moduleName, false);
369                return module;
370            }
371            else
372#endif
373            {
374#if FEATURE_APPDOMAIN
375                var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
376                    assemblyName, AssemblyBuilderAccess.Run);
377#else
378				var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
379#endif
380
381                var module = assemblyBuilder.DefineDynamicModule(moduleName);
382                return module;
383            }
384        }
385
386        private AssemblyName GetAssemblyName(bool signStrongName)
387        {
388            var assemblyName = new AssemblyName
389            {
390                Name = signStrongName ? strongAssemblyName : weakAssemblyName
391            };
392
393            if (signStrongName)
394            {
395#if FEATURE_ASSEMBLYBUILDER_SAVE
396                byte[] keyPairStream = GetKeyPair();
397                if (keyPairStream != null)
398                {
399                    assemblyName.KeyPair = new StrongNameKeyPair(keyPairStream);
400                }
401#else
402				assemblyName.SetPublicKey(JustMockInternalsVisible.JustMockGenAssemblyPublicKey);
403#endif
404            }
405
406            return assemblyName;
407        }
408
409#if FEATURE_ASSEMBLYBUILDER_SAVE
410        /// <summary>
411        ///   Saves the generated assembly with the name and directory information given when this <see cref = "ModuleScope" /> instance was created (or with
412        ///   the <see cref = "DEFAULT_FILE_NAME" /> and current directory if none was given).
413        /// </summary>
414        /// <remarks>
415        ///   <para>
416        ///     This method stores the generated assembly in the directory passed as part of the module information specified when this instance was
417        ///     constructed (if any, else the current directory is used). If both a strong-named and a weak-named assembly
418        ///     have been generated, it will throw an exception; in this case, use the <see cref = "SaveAssembly (bool)" /> overload.
419        ///   </para>
420        ///   <para>
421        ///     If this <see cref = "ModuleScope" /> was created without indicating that the assembly should be saved, this method does nothing.
422        ///   </para>
423        /// </remarks>
424        /// <exception cref = "InvalidOperationException">Both a strong-named and a weak-named assembly have been generated.</exception>
425        /// <returns>The path of the generated assembly file, or null if no file has been generated.</returns>
426        public string SaveAssembly()
427        {
428            if (!savePhysicalAssembly)
429            {
430                return null;
431            }
432
433            if (StrongNamedModule != null && WeakNamedModule != null)
434            {
435                throw new InvalidOperationException("Both a strong-named and a weak-named assembly have been generated.");
436            }
437
438            if (StrongNamedModule != null)
439            {
440                return SaveAssembly(true);
441            }
442
443            if (WeakNamedModule != null)
444            {
445                return SaveAssembly(false);
446            }
447
448            return null;
449        }
450
451        /// <summary>
452        ///   Saves the specified generated assembly with the name and directory information given when this <see
453        ///    cref = "ModuleScope" /> instance was created
454        ///   (or with the <see cref = "DEFAULT_FILE_NAME" /> and current directory if none was given).
455        /// </summary>
456        /// <param name = "strongNamed">True if the generated assembly with a strong name should be saved (see <see
457        ///    cref = "StrongNamedModule" />);
458        ///   false if the generated assembly without a strong name should be saved (see <see cref = "WeakNamedModule" />.</param>
459        /// <remarks>
460        ///   <para>
461        ///     This method stores the specified generated assembly in the directory passed as part of the module information specified when this instance was
462        ///     constructed (if any, else the current directory is used).
463        ///   </para>
464        ///   <para>
465        ///     If this <see cref = "ModuleScope" /> was created without indicating that the assembly should be saved, this method does nothing.
466        ///   </para>
467        /// </remarks>
468        /// <exception cref = "InvalidOperationException">No assembly has been generated that matches the <paramref
469        ///    name = "strongNamed" /> parameter.
470        /// </exception>
471        /// <returns>The path of the generated assembly file, or null if no file has been generated.</returns>
472        public string SaveAssembly(bool strongNamed)
473        {
474            if (!savePhysicalAssembly)
475            {
476                return null;
477            }
478
479            AssemblyBuilder assemblyBuilder;
480            string assemblyFileName;
481            string assemblyFilePath;
482
483            if (strongNamed)
484            {
485                if (StrongNamedModule == null)
486                {
487                    throw new InvalidOperationException("No strong-named assembly has been generated.");
488                }
489                assemblyBuilder = (AssemblyBuilder)StrongNamedModule.Assembly;
490                assemblyFileName = StrongNamedModuleName;
491                assemblyFilePath = StrongNamedModule.FullyQualifiedName;
492            }
493            else
494            {
495                if (WeakNamedModule == null)
496                {
497                    throw new InvalidOperationException("No weak-named assembly has been generated.");
498                }
499                assemblyBuilder = (AssemblyBuilder)WeakNamedModule.Assembly;
500                assemblyFileName = WeakNamedModuleName;
501                assemblyFilePath = WeakNamedModule.FullyQualifiedName;
502            }
503
504            if (File.Exists(assemblyFilePath))
505            {
506                File.Delete(assemblyFilePath);
507            }
508
509#if FEATURE_SERIALIZATION
510            AddCacheMappings(assemblyBuilder);
511#endif
512
513            assemblyBuilder.Save(assemblyFileName);
514            return assemblyFilePath;
515        }
516#endif
517
518#if FEATURE_SERIALIZATION
519        private void AddCacheMappings(AssemblyBuilder builder)
520        {
521            Dictionary<CacheKey, string> mappings;
522
523            using (Lock.ForReading())
524            {
525                mappings = new Dictionary<CacheKey, string>();
526                foreach (var cacheEntry in typeCache)
527                {
528                    // NOTE: using == returns invalid results.
529                    // we need to use Equals here for it to work properly
530                    if (builder.Equals(cacheEntry.Value.Assembly))
531                    {
532                        mappings.Add(cacheEntry.Key, cacheEntry.Value.FullName);
533                    }
534                }
535            }
536
537            CacheMappingsAttribute.ApplyTo(builder, mappings);
538        }
539
540        /// <summary>
541        ///   Loads the generated types from the given assembly into this <see cref = "ModuleScope" />'s cache.
542        /// </summary>
543        /// <param name = "assembly">The assembly to load types from. This assembly must have been saved via <see
544        ///    cref = "SaveAssembly(bool)" /> or
545        ///   <see cref = "SaveAssembly()" />, or it must have the <see cref = "CacheMappingsAttribute" /> manually applied.</param>
546        /// <remarks>
547        ///   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
548        ///   to avoid the performance hit associated with proxy generation.
549        /// </remarks>
550        public void LoadAssemblyIntoCache(Assembly assembly)
551        {
552            if (assembly == null)
553            {
554                throw new ArgumentNullException("assembly");
555            }
556
557            var cacheMappings =
558                (CacheMappingsAttribute[])assembly.GetCustomAttributes(typeof(CacheMappingsAttribute), false);
559
560            if (cacheMappings.Length == 0)
561            {
562                var message = string.Format(
563                    "The given assembly '{0}' does not contain any cache information for generated types.",
564                    assembly.FullName);
565                throw new ArgumentException(message, "assembly");
566            }
567
568            foreach (var mapping in cacheMappings[0].GetDeserializedMappings())
569            {
570                var loadedType = assembly.GetType(mapping.Value);
571
572                if (loadedType != null)
573                {
574                    RegisterInCache(mapping.Key, loadedType);
575                }
576            }
577        }
578#endif
579
580        public TypeBuilder DefineType(bool inSignedModulePreferably, string name, TypeAttributes flags)
581        {
582            var module = ObtainDynamicModule(disableSignedModule == false && inSignedModulePreferably);
583            return module.DefineType(name, flags);
584        }
585    }
586}
587
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in CacheMappingsAttribute

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)