public static FieldDefinition InjectField(this TypeDefinition targetType, FieldDefinition sourceField, ReferenceResolver resolver) { if (sourceField == null) throw new ArgumentNullException("sourceField"); if (resolver == null) throw new ArgumentNullException("resolver"); FieldDefinition newField = null; if (Helper.TryGetField(targetType.Fields, sourceField, ref newField)) return newField; TypeReference fieldType = resolver.ReferenceType(sourceField.FieldType, targetType); newField = new FieldDefinition(sourceField.Name, sourceField.Attributes, fieldType) { InitialValue = sourceField.InitialValue, DeclaringType = targetType, }; targetType.Fields.Add(newField); MetadataBuilderHelper.CopyCustomAttributes(sourceField, newField, resolver); if (newField.HasDefault) newField.Constant = sourceField.Constant; return newField; }
public static CustomAttribute InjectCustomAttribute(this ICustomAttributeProvider provider, CustomAttribute attribute, ReferenceResolver resolver) { if (attribute == null) throw new ArgumentNullException("attribute"); if (resolver == null) throw new ArgumentNullException("resolver"); TypeReference attributeType = resolver.ReferenceType(attribute.AttributeType); // no context required as attributes cannot be generic MethodReference constructor = resolver.ReferenceMethod(attribute.Constructor); CustomAttribute newAttribute; if ((newAttribute = Helper.GetCustomAttribute(provider.CustomAttributes, attribute)) != null) return newAttribute; newAttribute = new CustomAttribute(constructor);//, attr.GetBlob()); provider.CustomAttributes.Add(newAttribute); MetadataBuilderHelper.CopyCustomAttributeArguments(attribute.ConstructorArguments, newAttribute.ConstructorArguments, resolver); MetadataBuilderHelper.CopyCustomAttributeNamedArguments(attribute.Fields, newAttribute.Fields, resolver); MetadataBuilderHelper.CopyCustomAttributeNamedArguments(attribute.Properties, newAttribute.Properties, resolver); return newAttribute; }
/// <summary> /// Initialize the state without delayed initialization of the BinaryClassInfo. /// </summary> public BinaryConverter Initialize(Type type, BinarySerializerOptions options, bool supportContinuation) { _typeSeqList = new List <ushort>(); BinaryClassInfo binaryClassInfo = options.GetOrAddClass(type); TypeMap = options.TypeMap; AddTypeSeq(binaryClassInfo.TypeSeq); //PrimaryTypeSeq = binaryClassInfo.TypeSeq; Current.BinaryClassInfo = binaryClassInfo; Current.BinaryTypeInfo = TypeMap.GetTypeInfo(binaryClassInfo.TypeSeq); Current.DeclaredBinaryPropertyInfo = binaryClassInfo.PropertyInfoForClassInfo; if (options.ReferenceHandler != null) { ReferenceResolver = options.ReferenceHandler !.CreateResolver(writing: true); } else { ReferenceResolver = new ObjectReferenceResolver(); } SupportContinuation = supportContinuation; return(binaryClassInfo.PropertyInfoForClassInfo.ConverterBase); }
/// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { AppDomain appDomain = null; try { var assembly = typeof (GrainClientGenerator).GetTypeInfo().Assembly; // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( assembly.FullName, typeof(GrainClientGenerator).FullName); // Call a method return generator.CreateGrainClient(options); } finally { if (appDomain != null) AppDomain.Unload(appDomain); // Unload the AppDomain } }
public static ReferenceResolver GetResolver(this Debugger debugger) { //Get all referenced assemblies string assemblyLocation = string.Empty; for (int i = 0; i < 10; i++) { try { assemblyLocation = debugger.GetExpression("System.Reflection.Assembly.GetExecutingAssembly().Location;", false, 5000).Value; assemblyLocation = assemblyLocation.Replace(@"\\", @"\").Replace("\"", ""); if (File.Exists(assemblyLocation)) { break; //es kann auch eine Message wie "Function evaluation timed out" zurückkommen } } catch { System.Threading.Thread.Sleep(50); } } if (!File.Exists(assemblyLocation) || string.IsNullOrEmpty(assemblyLocation)) { return(null); } ReferenceResolver resolver = new ReferenceResolver(assemblyLocation); return(resolver); }
public ReferenceResolver AcquireConfiguration(NailsTestsConfigurable test) { rwLock.AcquireReaderLock(ConfigurationTimeout); var testConfigurationName = test.ConfigurationName; if (currentConfigurationName != testConfigurationName) { var lockCookie = rwLock.UpgradeToWriterLock(ConfigurationTimeout); try { var configurationDelegate = NailsTestsConfigurationRepository.Instance.Get(testConfigurationName); Nails.Reset(); configurationDelegate(Nails.Configure().UnitOfWork.ConnectionBoundUnitOfWork(false)); currentReferenceResolver = new ReferenceResolver(Nails.ObjectFactory); currentConfigurationName = testConfigurationName; } finally { rwLock.DowngradeFromWriterLock(ref lockCookie); } } return(currentReferenceResolver); }
public ServerSession(TcpClient client, IAuthenticationService authenticationService, IDto initialObject) : base(client) { _initialObject = initialObject; _delegates = new ConcurrentDictionary <delegateKey, Delegate>(); _serializer = JsonSerializer.CreateDefault(); _referenceResolver = new ReferenceResolver(); _referenceResolver.ReferencePropertyChanged += _referenceResolver_ReferencePropertyChanged; _referenceResolver.ReferenceDisposed += _referencedObjectDisposed; _serializer.ReferenceResolver = _referenceResolver; _serializer.TypeNameHandling = TypeNameHandling.Objects; _serializer.Context = new StreamingContext(StreamingContextStates.Remoting); #if DEBUG _serializer.Formatting = Formatting.Indented; #endif if (!(client.Client.RemoteEndPoint is IPEndPoint endPoint)) { throw new UnauthorizedAccessException($"Client RemoteEndpoint {Client.Client.RemoteEndPoint} is invalid"); } _sessionUser = authenticationService.FindUser(AuthenticationSource.IpAddress, endPoint.Address.ToString()); if (_sessionUser == null) { throw new UnauthorizedAccessException($"Access from {Client.Client.RemoteEndPoint} not allowed"); } StartThreads(); }
protected override bool Step( GraphStructuredProgram <TNode> targetProgram, ResolvedMethod <TNode> targetMethod, TNode source, Statement statement, TNode target, Func <TNode> nodeCreator) { if (statement is AssignmentStatement assignment) { var sourceEntity = ReferenceResolver.Resolve(targetProgram, targetMethod, assignment.Source); var targetEntity = ReferenceResolver.Resolve(targetProgram, targetMethod, assignment.Target); var targetSecondaryEntity = targetEntity as SecondaryEntity; Trace.Assert(targetSecondaryEntity != null); var referencedByThis = assignment.Target is ClassFieldReference classFieldReference && classFieldReference.Owner is ClassReference classReference && classReference.ThisClassReference; var newStatement = new ResolvedAssignmentStatement( assignment.Location, sourceEntity, targetSecondaryEntity, referencedByThis); targetProgram.AddEdge(new OperationEdge <TNode>(source, newStatement, target)); return(false); } return(true); }
public void IsReferencedTest_NonReferenced_ReturnFalse() { var mockObject = new MockServerObject("TestValue"); var serverReferenceResolver = new ReferenceResolver(); Assert.IsFalse(serverReferenceResolver.IsReferenced(this, mockObject)); }
public IEnumerable <Assembly> Find() { var referenceItems = new List <Assembly>(); foreach (Assembly assembly in _referenceAssemblies) { referenceItems.Add(assembly); } if (_includeTargets) { foreach (var target in _targetAssemblies) { try { referenceItems.Add(Assembly.Load(target)); } catch (FileNotFoundException ex) { // occurs if we cannot load this ... for example in a test project where we aren't currently referencing Umbraco.Web, etc... _logger.LogDebug(ex, "Could not load assembly " + target); } } } var provider = new ReferenceResolver(_targetAssemblies, referenceItems, _loggerFactory.CreateLogger <ReferenceResolver>()); IEnumerable <Assembly> assemblyNames = provider.ResolveAssemblies(); return(assemblyNames.ToList()); }
public static void CopySecurityAttributes(SecurityDeclaration source, SecurityDeclaration target, ReferenceResolver resolver) { if (!source.HasSecurityAttributes) return; foreach (var attribute in source.SecurityAttributes) target.InjectSecurityAttribute(attribute, resolver); }
public static void CopyGenericParameters(IGenericParameterProvider source, IGenericParameterProvider target, ReferenceResolver resolver) { if (!source.HasGenericParameters) return; foreach (var parameter in source.GenericParameters) target.InjectGenericParameter(parameter, resolver); }
public static void CopyCustomAttributeArguments(Collection<Mono.Cecil.CustomAttributeArgument> source, Collection<Mono.Cecil.CustomAttributeArgument> target, ReferenceResolver resolver) { foreach (var argument in source) { var argumentType = resolver.ReferenceType(argument.Type); target.Add(new CustomAttributeArgument(argumentType, argument.Value)); } }
public static void CopySecurityDeclarations(ISecurityDeclarationProvider source, ISecurityDeclarationProvider target, ReferenceResolver resolver) { if (!source.HasSecurityDeclarations) return; foreach (var declaration in source.SecurityDeclarations) target.InjectSecurityDeclaration(declaration, resolver); }
public void ResolveReferenceTest_UnknownGuid_ReturnNull() { var serverReferenceResolver = new ReferenceResolver(); var dto = serverReferenceResolver.ResolveReference(new Guid()); Assert.IsNull(dto, "dto not null!"); }
public void IsReferencedTest_NonDto_ReturnGuidEmpty() { var obj = new object(); var serverReferenceResolver = new ReferenceResolver(); var result = serverReferenceResolver.IsReferenced(this, obj); Assert.AreEqual(result, Guid.Empty); }
public void IsReferencedTest_Referenced_ReturnTrue() { var mockObject = new MockServerObject("TestValue"); var serverReferenceResolver = new ReferenceResolver(); serverReferenceResolver.GetReference(this, mockObject); Assert.IsTrue(serverReferenceResolver.IsReferenced(this, mockObject)); }
public void GetReferenceTest_NonDtoObject_ReturnEmpty() { var mockObject = new object(); var serverReferenceResolver = new ReferenceResolver(); var result = serverReferenceResolver.GetReference(this, mockObject); Assert.AreEqual(result, String.Empty, ""); }
public static void CopyCustomAttributes(ICustomAttributeProvider source, ICustomAttributeProvider target, ReferenceResolver resolver) { if (!source.HasCustomAttributes) return; foreach (var attribute in source.CustomAttributes) target.InjectCustomAttribute(attribute, resolver); }
public ThreadLoader(Post post, ApiConfig config) { _post = post; resolver = new ReferenceResolver(); _config = config; _threadController = new ThreadController(_config); PageSize = _threadController.PageSize; }
/// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output code file under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { string generatedCode = null; AppDomain appDomain = null; try { var assembly = typeof(GrainClientGenerator).GetTypeInfo().Assembly; // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( assembly.FullName, typeof(GrainClientGenerator).FullName); // Call a method generatedCode = generator.CreateGrainClient(options); } finally { if (appDomain != null) { AppDomain.Unload(appDomain); // Unload the AppDomain } } if (generatedCode != null) { using (var sourceWriter = new StreamWriter(options.OutputFileName)) { sourceWriter.WriteLine("#if !EXCLUDE_CODEGEN"); DisableWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine(generatedCode); RestoreWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine("#endif"); } ConsoleText.WriteStatus("Orleans-CodeGen - Generated file written {0}", options.OutputFileName); return(true); } return(false); }
protected override void ProcessAssembly(AssemblyDefinition assembly) { _resolver = ReferenceResolver.GetDefaultResolver(assembly.MainModule); foreach (TypeDefinition type in assembly.MainModule.GetTypes().Where(t => !t.IsInterface)) { FindImplementationsOfBaseMethods(type); FindImplementationsOfInterfaceMethods(type); } }
public static void InjectSecurityAttribute(this SecurityDeclaration target, SecurityAttribute attribute, ReferenceResolver resolver) { var attributeType = resolver.ReferenceType(attribute.AttributeType); var newAttribute = new SecurityAttribute(attributeType); MetadataBuilderHelper.CopyCustomAttributeNamedArguments(attribute.Fields, newAttribute.Fields, resolver); MetadataBuilderHelper.CopyCustomAttributeNamedArguments(attribute.Properties, newAttribute.Properties, resolver); target.SecurityAttributes.Add(newAttribute); }
public AssetReferencesConverter( SourceDescriptions descriptions, IServiceProvider provider, IEntitySourceContext <Asset> sources, PropertyInfo property) { _assetContext = new Lazy <IAssetContext>(provider.GetRequired <IAssetContext>); _resolver = ReferenceResolver <TOwner, TAsset> .Build(property, descriptions, GetEntity); _sources = sources; }
public ActorReferencesConverter( IActorContext actorContext, SourceDescriptions descriptions, IEntitySourceContext <Actor> sources, PropertyInfo property) { _actorContext = actorContext; _resolver = ReferenceResolver <TOwner, TActor> .Build(property, descriptions, GetEntity); _sources = sources; }
public void Initialize() { _mockObject = new MockProxyObject { DtoGuid = Guid.NewGuid() }; _clientReferenceResolver = new ReferenceResolver(); var po = new PrivateObject(_clientReferenceResolver); _knownDtos = ((Dictionary <Guid, WeakReference <ProxyObjectBase> >)po.GetField("_knownDtos")); }
public static TypeDefinition InjectType(this ModuleDefinition module, TypeDefinition sourceType, ReferenceResolver resolver) { TypeDefinition newType = null; if (Helper.TryGetType(module.Types, sourceType, ref newType)) return newType; newType = MetadataBuilderHelper.CreateNewType(sourceType, resolver); module.Types.Add(newType); newType.InjectTypeMembers(sourceType, resolver); return newType; }
public RemoteClient(string address) : base(address) { _serializer = JsonSerializer.CreateDefault(); _serializer.Context = new StreamingContext(StreamingContextStates.Remoting, this); _serializer.PreserveReferencesHandling = PreserveReferencesHandling.Objects; _referenceResolver = new ReferenceResolver(); _serializer.ReferenceResolver = _referenceResolver; _serializer.TypeNameHandling = TypeNameHandling.Objects | TypeNameHandling.Arrays; #if DEBUG _serializer.Formatting = Formatting.Indented; #endif StartThreads(); }
public ServerSession() { _delegates = new ConcurrentDictionary <delegateKey, Delegate>(); _serializer = JsonSerializer.CreateDefault(); _referenceResolver = new ReferenceResolver(); _referenceResolver.ReferencePropertyChanged += _referenceResolver_ReferencePropertyChanged; _referenceResolver.ReferenceDisposed += _referencedObjectDisposed; _serializer.ReferenceResolver = _referenceResolver; _serializer.TypeNameHandling = TypeNameHandling.Objects; _serializer.Context = new StreamingContext(StreamingContextStates.Remoting); #if DEBUG _serializer.Formatting = Formatting.Indented; #endif }
public StringLiteralDictionary(ReferenceResolver resolver) { m_dict = new Dictionary <string, FieldReference>(); m_resolver = resolver; m_usedNames = new HashSet <string>(); m_typedef = new TypeDefinition("", ARRAY_CLASS_NAME, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract /*static*/); // make sure other parts of the system don't get confused m_resolver.GetTypeReference(typeof(ESharp.EObject)).Module.Types.Add(m_typedef); }
/// <summary> /// Helper method to get all references for the given compilation. /// </summary> /// <param name="context"></param> /// <returns></returns> protected IEnumerable <CompilerReference> GetAllReferences(TypeContext context) { #pragma warning disable 0618 // Backwards Compat. var references = ReferenceResolver.GetReferences( context, IncludeAssemblies() .Select(CompilerReference.From) .Concat(IncludeReferences())) #pragma warning restore 0618 // Backwards Compat. .ToList(); context.AddReferences(references); return(references); }
/// <summary> /// Helper method to get all references for the given compilation. /// </summary> /// <param name="context"></param> /// <returns></returns> protected IEnumerable <CompilerReference> GetAllReferences(TypeContext context) { var references = ReferenceResolver.GetReferences( context, IncludeAssemblies() .Select(RazorEngine.Compilation.ReferenceResolver.CompilerReference.From) .Concat(IncludeReferences())); foreach (var reference in references) { this.references.Add(reference); yield return(reference); } }
public void ResolveReferenceTest_NonReferenced_ReturnDto() { var serverReferenceResolver = new ReferenceResolver(); PrivateObject po = new PrivateObject(serverReferenceResolver); var mockObject = new MockServerObject("TestValue"); var _knownDtos = ((Dictionary <Guid, ServerObjectBase>)po.GetField("_knownDtos")); var _knownDtosCount = _knownDtos.Count; var stringGuid = serverReferenceResolver.GetReference(this, mockObject); var dto = serverReferenceResolver.ResolveReference(new Guid(stringGuid)); Assert.IsNotNull(dto); Assert.AreEqual(_knownDtosCount + 1, _knownDtos.Count); }
internal JsonConverter Initialize(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options, bool supportContinuation) { Current.JsonTypeInfo = jsonTypeInfo; Current.DeclaredJsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; Current.NumberHandling = Current.DeclaredJsonPropertyInfo.NumberHandling; if (options.ReferenceHandlingStrategy != ReferenceHandlingStrategy.None) { Debug.Assert(options.ReferenceHandler != null); ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: true); } SupportContinuation = supportContinuation; return(jsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase); }
public CommunicationBehavior(IDto initialObject) { _initialObject = initialObject; _delegates = new ConcurrentDictionary <delegateKey, Delegate>(); Debug.WriteLine(initialObject, "Server: created behavior for"); _serializer = JsonSerializer.CreateDefault(); _referenceResolver = new ReferenceResolver(); _referenceResolver.ReferencePropertyChanged += _referenceResolver_ReferencePropertyChanged; _referenceResolver.ReferenceDisposed += _referencedObjectDisposed; _serializer.ReferenceResolver = _referenceResolver; _serializer.TypeNameHandling = TypeNameHandling.Auto; _serializer.Context = new StreamingContext(StreamingContextStates.Remoting); #if DEBUG _serializer.Formatting = Formatting.Indented; #endif }
internal void Initialize(JsonTypeInfo jsonTypeInfo, bool supportContinuation = false) { JsonSerializerOptions options = jsonTypeInfo.Options; if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) { ReferenceResolver = options.ReferenceHandler !.CreateResolver(writing: false); CanContainMetadata = true; } SupportContinuation = supportContinuation; Current.JsonTypeInfo = jsonTypeInfo; Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; Current.NumberHandling = Current.JsonPropertyInfo.NumberHandling; UseFastPath = !supportContinuation && !CanContainMetadata; }
internal void Initialize(JsonTypeInfo jsonTypeInfo, bool supportContinuation = false) { JsonSerializerOptions options = jsonTypeInfo.Options; if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve) { ReferenceResolver = options.ReferenceHandler !.CreateResolver(writing: false); PreserveReferences = true; } SupportContinuation = supportContinuation; Current.JsonTypeInfo = jsonTypeInfo; Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; Current.NumberHandling = Current.JsonPropertyInfo.EffectiveNumberHandling; Current.CanContainMetadata = PreserveReferences || jsonTypeInfo.PolymorphicTypeResolver?.UsesTypeDiscriminators == true; }
/// <summary> /// Helper method to get all references for the given compilation. /// </summary> /// <param name="context"></param> /// <returns></returns> protected IEnumerable <CompilerReference> GetAllReferences(TypeContext context) { #pragma warning disable 0618 // Backwards Compat. var references = ReferenceResolver.GetReferences( context, IncludeAssemblies() .Select(RazorEngine.Compilation.ReferenceResolver.CompilerReference.From) .Concat(IncludeReferences())); #pragma warning restore 0618 // Backwards Compat. foreach (var reference in references) { this.references.Add(reference); yield return(reference); } }
public void GlobalOptimization(List <Mono.Cecil.TypeDefinition> types) { ReferenceResolver resolver = new ReferenceResolver(types); dict = new StringLiteralDictionary(resolver); foreach (var t in types) { foreach (var method in t.Methods) { if (method.Body == null) { continue; } Instruction prev_inst = null; foreach (var inst in method.Body.Instructions) { if (inst.OpCode == OpCodes.Ldstr) { inst.OpCode = OpCodes.Ldsfld; var stringValue = (string)inst.Operand; inst.Operand = dict.AddString(stringValue); //inst. } // array initializer if (inst.OpCode == OpCodes.Call && (inst.Operand as MethodReference).Name.Contains("InitializeArray") && (inst.Operand as MethodReference).DeclaringType.Name.Contains("RuntimeHelpers")) { var fieldRef = (FieldReference)prev_inst.Operand; var data = fieldRef.Resolve().InitialValue; // todo convert data to actual values. prev_inst.Operand = dict.AddArray_1(data); prev_inst.OpCode = OpCodes.Ldsfld; } prev_inst = inst; } } } // todo iterate over il, replace ldstring //add new class with custom c code types.Add(dict.GetStringsType()); }
/// <summary> /// Initialize the state without delayed initialization of the JsonClassInfo. /// </summary> public JsonConverter Initialize(Type type, JsonSerializerOptions options, bool supportContinuation) { JsonClassInfo jsonClassInfo = options.GetOrAddClassForRootType(type); Current.JsonClassInfo = jsonClassInfo; Current.DeclaredJsonPropertyInfo = jsonClassInfo.PropertyInfoForClassInfo; Current.NumberHandling = Current.DeclaredJsonPropertyInfo.NumberHandling; if (options.ReferenceHandler != null) { ReferenceResolver = options.ReferenceHandler !.CreateResolver(writing: true); } SupportContinuation = supportContinuation; return(jsonClassInfo.PropertyInfoForClassInfo.ConverterBase); }
public IEnumerable <TypeDefinition> GetUsedTypes(MethodReference EntryPoint) { m_resolver = new ReferenceResolver(m_all); // start with entry point type AddType(EntryPoint.Resolve().DeclaringType); while (m_toProcess.Count > 0) { var first = m_toProcess.First(); Process(first); m_toProcess.Remove(first); } return(m_all); }
public static TypeDefinition CreateNewType(TypeDefinition sourceType, ReferenceResolver resolver) { TypeDefinition newType = new TypeDefinition(sourceType.Namespace, sourceType.Name, sourceType.Attributes) { PackingSize = sourceType.PackingSize, ClassSize = sourceType.ClassSize, }; CopyGenericParameters(sourceType, newType, resolver); if (sourceType.BaseType != null) { newType.BaseType = resolver.ReferenceType(sourceType.BaseType, newType); } CopyCustomAttributes(sourceType, newType, resolver); return newType; }
public static void InjectGenericParameter(this IGenericParameterProvider owner, GenericParameter parameter, ReferenceResolver resolver) { GenericParameter newParameter = new GenericParameter(parameter.Name, owner) { Attributes = parameter.Attributes }; owner.GenericParameters.Add(newParameter); MetadataBuilderHelper.CopyCustomAttributes(newParameter, parameter, resolver); foreach (var constraint in parameter.Constraints) { if (owner is MethodReference) newParameter.Constraints.Add(resolver.ReferenceType(constraint, owner, ((MethodReference)owner).DeclaringType)); else newParameter.Constraints.Add(resolver.ReferenceType(constraint, owner)); } }
public static EventDefinition InjectEvent(this TypeDefinition targetType, EventDefinition sourceEvent, ReferenceResolver resolver) { if (sourceEvent == null) throw new ArgumentNullException("sourceEvent"); if (resolver == null) throw new ArgumentNullException("resolver"); var eventType = resolver.ReferenceType(sourceEvent.EventType, targetType); EventDefinition newEvent = null; if (Helper.TryGetEvent(targetType.Events, sourceEvent, ref newEvent)) return newEvent; newEvent = new EventDefinition(sourceEvent.Name, sourceEvent.Attributes, eventType) { DeclaringType = targetType, }; targetType.Events.Add(newEvent); MetadataBuilderHelper.CopyCustomAttributes(sourceEvent, newEvent, resolver); if (sourceEvent.AddMethod != null) { newEvent.AddMethod = targetType.InjectMethod(sourceEvent.AddMethod, resolver); } if (sourceEvent.RemoveMethod != null) { newEvent.RemoveMethod = targetType.InjectMethod(sourceEvent.RemoveMethod, resolver); } foreach (var otherMethod in sourceEvent.OtherMethods) { newEvent.OtherMethods.Add(targetType.InjectMethod(otherMethod, resolver)); } return newEvent; }
public static void InjectSecurityDeclaration(this ISecurityDeclarationProvider target, SecurityDeclaration declaration, ReferenceResolver resolver) { var newDeclaration = new SecurityDeclaration(declaration.Action); MetadataBuilderHelper.CopySecurityAttributes(declaration, newDeclaration, resolver); target.SecurityDeclarations.Add(newDeclaration); }
public static TypeDefinition InjectMap(AssemblyDefinition assembly) { var module = assembly.MainModule; var mapModule = ModuleDefinition.ReadModule(typeof(Map).Module.FullyQualifiedName); var mapTypeDefinition = mapModule.GetType(typeof(Map).FullName); //string destinationName = String.Concat(MAP_NAME_PREFIX, '{', GUID, '}'); string destinationName = "Map"; ReferenceResolver resolver = new ReferenceResolver(module, Helper.IsCore); resolver.Action = delegate(TypeReference typeReference) { if (typeReference == mapTypeDefinition) return module.InjectType(typeReference.Resolve(), resolver); else return module.Import(typeReference); }; var newType = module.InjectType(mapTypeDefinition, resolver); newType.Name = destinationName; newType.Namespace = String.Empty; return newType; }
public static TypeDefinition InjectNestedType(this TypeDefinition targetType, TypeDefinition sourceType, ReferenceResolver resolver) { TypeDefinition newType = null; if (Helper.TryGetType(targetType.NestedTypes, sourceType, ref newType)) return newType; newType = MetadataBuilderHelper.CreateNewType(sourceType, resolver); newType.DeclaringType = targetType; targetType.NestedTypes.Add(newType); newType.InjectTypeMembers(sourceType, resolver); return newType; }
public static PropertyDefinition InjectProperty(this TypeDefinition targetType, PropertyDefinition sourceProperty, ReferenceResolver resolver) { if (sourceProperty == null) throw new ArgumentNullException("sourceProperty"); if (resolver == null) throw new ArgumentNullException("resolver"); TypeReference propertyType = resolver.ReferenceType(sourceProperty.PropertyType, targetType); PropertyDefinition newProperty = null; if (Helper.TryGetProperty(targetType.Properties, sourceProperty, ref newProperty)) return newProperty; newProperty = new PropertyDefinition(sourceProperty.Name, sourceProperty.Attributes, propertyType) { DeclaringType = targetType }; targetType.Properties.Add(newProperty); MetadataBuilderHelper.CopyCustomAttributes(sourceProperty, newProperty, resolver); if (sourceProperty.GetMethod != null) { newProperty.GetMethod = targetType.InjectMethod(sourceProperty.GetMethod, resolver); } if (sourceProperty.SetMethod != null) { newProperty.SetMethod = targetType.InjectMethod(sourceProperty.SetMethod, resolver); } return newProperty; }
public static MethodDefinition InjectMethod(this TypeDefinition targetType, MethodDefinition sourceMethod, ReferenceResolver resolver, bool body = true) { if (sourceMethod == null) throw new ArgumentNullException("sourceMethod"); if (resolver == null) throw new ArgumentNullException("resolver"); // Console.WriteLine("\tCreating method {0}", sourceMethod.FullName); MethodDefinition newMethod = null; if (Helper.TryGetMethod(targetType.Methods, sourceMethod, ref newMethod)) return newMethod; newMethod = new MethodDefinition(sourceMethod.Name, sourceMethod.Attributes, sourceMethod.ReturnType) { ExplicitThis = sourceMethod.ExplicitThis, ImplAttributes = sourceMethod.ImplAttributes, SemanticsAttributes = sourceMethod.SemanticsAttributes, DeclaringType = targetType, CallingConvention = sourceMethod.CallingConvention, }; targetType.Methods.Add(newMethod); MetadataBuilderHelper.CopyGenericParameters(sourceMethod, newMethod, resolver); CopyParameters(sourceMethod, newMethod, resolver); newMethod.ReturnType = resolver.ReferenceType(sourceMethod.ReturnType, newMethod, targetType); MetadataBuilderHelper.CopyCustomAttributes(sourceMethod, newMethod, resolver); CopyOverrides(sourceMethod, newMethod, resolver); MetadataBuilderHelper.CopySecurityDeclarations(sourceMethod, newMethod, resolver); if(body) CopyMethodBody(sourceMethod, newMethod, resolver); // Console.WriteLine("\tCreated method {0}", sourceMethod.FullName); return newMethod; }
private static void CopyInstructions(MethodDefinition sourceMethod, MethodDefinition targetMethod, ReferenceResolver resolver) { TypeDefinition targetType = targetMethod.DeclaringType; var processor = targetMethod.Body.GetILProcessor(); var offset = 0; foreach (var instruction in sourceMethod.Body.Instructions) { object operand; if (instruction.Operand is FieldReference) { operand = resolver.ReferenceField((FieldReference)instruction.Operand, targetMethod, targetType); } else if (instruction.Operand is MethodReference) { operand = resolver.ReferenceMethod((MethodReference)instruction.Operand, targetMethod, targetType); } else if (instruction.Operand is TypeReference) { operand = resolver.ReferenceType((TypeReference)instruction.Operand, targetMethod, targetType); } else { operand = instruction.Operand; } Instruction newInstruction = Helper.CreateInstruction(instruction.OpCode, instruction.OpCode.OperandType, operand); newInstruction.SequencePoint = instruction.SequencePoint; newInstruction.Offset = offset; offset += newInstruction.GetSize(); processor.Append(newInstruction); } FixBranchingTargets(targetMethod.Body); CopyExceptionHandlers(sourceMethod, targetMethod, resolver); }
private static void CopyMethodBody(MethodDefinition sourceMethod, MethodDefinition targetMethod, ReferenceResolver resolver) { if (!sourceMethod.HasBody) return; targetMethod.Body.InitLocals = sourceMethod.Body.InitLocals; //targetMethod.Body.MaxStackSize = sourceMethod.Body.MaxStackSize; //targetMethod.Body.LocalVarToken = sourceMethod.Body.LocalVarToken; CopyVariables(sourceMethod, targetMethod, resolver); CopyInstructions(sourceMethod, targetMethod, resolver); }
private static void CopyOverrides(MethodDefinition sourceMethod, MethodDefinition targetMethod, ReferenceResolver resolver) { if (!sourceMethod.HasOverrides) return; foreach (var methodOverride in sourceMethod.Overrides) targetMethod.Overrides.Add(resolver.ReferenceMethod(methodOverride, targetMethod, targetMethod.DeclaringType)); }
private static void CopyParameters(MethodReference sourceMethod, MethodReference targetMethod, ReferenceResolver resolver) { if (!sourceMethod.HasParameters) return; //to have full method signature when determining generic patameter owner foreach (var parameterDefinition in sourceMethod.Parameters) targetMethod.Parameters.Add(parameterDefinition); //fix references for (int i = 0; i < targetMethod.Parameters.Count; i++) { var parameterDefinition = targetMethod.Parameters[i]; var parameterType = resolver.ReferenceType(parameterDefinition.ParameterType, targetMethod, targetMethod.DeclaringType); ParameterDefinition newParameter = new ParameterDefinition(parameterDefinition.Name, parameterDefinition.Attributes, parameterType) { HasConstant = parameterDefinition.HasConstant, MarshalInfo = parameterDefinition.MarshalInfo, }; targetMethod.Parameters[i] = newParameter; if (parameterDefinition.HasDefault) newParameter.Constant = parameterDefinition.Constant; MetadataBuilderHelper.CopyCustomAttributes(parameterDefinition, newParameter, resolver); } }
private static void CopyVariables(MethodDefinition sourceMethod, MethodDefinition targetMethod, ReferenceResolver resolver) { if (!sourceMethod.Body.HasVariables) return; foreach (var variableDefinition in sourceMethod.Body.Variables) { var variableType = resolver.ReferenceType(variableDefinition.VariableType, targetMethod, targetMethod.DeclaringType); VariableDefinition newVariable = new VariableDefinition(variableDefinition.Name, variableType); targetMethod.Body.Variables.Add(newVariable); } }
private static void CopyExceptionHandlers(MethodDefinition sourceMethod, MethodDefinition targetMethod, ReferenceResolver resolver) { if (!sourceMethod.Body.HasExceptionHandlers) return; foreach (var handler in sourceMethod.Body.ExceptionHandlers) { var newHandler = new ExceptionHandler(handler.HandlerType) { FilterStart = GetInstruction(targetMethod.Body, handler.FilterStart), // FilterEnd = GetInstruction(targetMethod.Body, handler.FilterEnd), HandlerStart = GetInstruction(targetMethod.Body, handler.HandlerStart), HandlerEnd = GetInstruction(targetMethod.Body, handler.HandlerEnd), TryStart = GetInstruction(targetMethod.Body, handler.TryStart), TryEnd = GetInstruction(targetMethod.Body, handler.TryEnd), }; if (handler.CatchType != null) newHandler.CatchType = resolver.ReferenceType(handler.CatchType, targetMethod, targetMethod.DeclaringType); targetMethod.Body.ExceptionHandlers.Add(newHandler); } }
public static TypeDefinition InjectTypeMembers(this TypeDefinition type, TypeDefinition sourceType, ReferenceResolver resolver) { if (sourceType == null) throw new ArgumentNullException("sourceType"); if (resolver == null) throw new ArgumentNullException("resolver"); foreach (var nestedType in sourceType.NestedTypes) type.InjectNestedType(nestedType, resolver); foreach (var @interface in sourceType.Interfaces) type.Interfaces.Add(resolver.ReferenceType(@interface, type)); foreach (var field in sourceType.Fields) type.InjectField(field, resolver); foreach (var @event in sourceType.Events) type.InjectEvent(@event, resolver); foreach (var method in sourceType.Methods) type.InjectMethod(method, resolver); foreach (var property in sourceType.Properties) type.InjectProperty(property, resolver); MetadataBuilderHelper.CopySecurityDeclarations(sourceType, type, resolver); Console.WriteLine("Created type {0}", type.FullName); return type; }
/// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { AppDomain appDomain = null; try { // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, typeof(GrainClientGenerator).FullName); // Call a method return generator.CreateGrainClient(options); } catch (Exception ex) { ConsoleText.WriteError("ERROR -- Client code-gen FAILED -- Exception caught -- ", ex); throw; } finally { if (appDomain != null) AppDomain.Unload(appDomain); // Unload the AppDomain } }