/// <summary> /// Weaves method with weaving advices <see cref="IWeavingAdvice"/>. /// </summary> /// <param name="markedMethod">The marked method.</param> /// <param name="context">The context.</param> private void RunWeavingAdvices(MarkedNode markedMethod, WeavingContext context) { var method = markedMethod.Node.Method; var methodName = method.Name; // our special recipe, with weaving advices var weavingAdvicesMarkers = GetAllMarkers(markedMethod.Node, context.WeavingAdviceInterfaceType, context).Select(t => t.Item2).ToArray(); var typeDefinition = markedMethod.Node.Method.DeclaringType; var initialType = TypeLoader.GetType(typeDefinition); var weaverMethodWeavingContext = new WeaverMethodWeavingContext(typeDefinition, initialType, methodName, context, TypeResolver, Logging); foreach (var weavingAdviceMarker in weavingAdvicesMarkers) { Logging.WriteDebug("Weaving method '{0}' using weaving advice '{1}'", method.FullName, weavingAdviceMarker.Type.FullName); var weavingAdviceType = TypeLoader.GetType(weavingAdviceMarker.Type); var weavingAdvice = (IWeavingAdvice)Activator.CreateInstance(weavingAdviceType); if (weavingAdvice is IMethodWeavingAdvice methodWeavingAdvice && !method.IsGetter && !method.IsSetter) { methodWeavingAdvice.Advise(weaverMethodWeavingContext); } } if (weaverMethodWeavingContext.TargetMethodName != methodName) { method.Name = weaverMethodWeavingContext.TargetMethodName; } }
/// <summary> /// This signature is for calls where the func name, arg types, etc., are supplied individually. /// </summary> /// internal static string CreateDLLCall(string funcName, string dllName, string callConv, string retTypeName, string[] argTypeNames, bool[] areOutParams, string strFormat) { // TypeLoadException from these... Type retType = retTypeName == null ? typeof(void) : TypeLoader.GetType(Utils.addSystemNamespace(retTypeName), true); Type[] argTypes = new Type[argTypeNames == null ? 0 : argTypeNames.Length]; if (argTypeNames != null) { for (int i = 0; i < argTypes.Length; i++) { argTypes[i] = TypeLoader.GetType(Utils.addSystemNamespace(argTypeNames[i]), true); } } // strFormat is guaranteed to be lower case by M code. CharSet charSet = strFormat == "ansi" ? CharSet.Ansi : (strFormat == "unicode" ? CharSet.Unicode : CharSet.Auto); CallingConvention callingConv; // callConv is sent from M as lower case. if (callConv == "cdecl") { callingConv = CallingConvention.Cdecl; } else if (callConv == "thiscall") { callingConv = CallingConvention.ThisCall; } else if (callConv == "stdcall") { callingConv = CallingConvention.StdCall; } else { callingConv = CallingConvention.Winapi; } TypeBuilder typeBuilder = dllModuleBuilder.DefineType(dllNamespace + "." + dllTypePrefix + index++, TypeAttributes.Public); MethodBuilder methodBuilder = typeBuilder.DefinePInvokeMethod(funcName, dllName, MethodAttributes.PinvokeImpl | MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, retType, argTypes, callingConv, charSet); // Don't ask me why this is not default with the PInvokeImpl attribute, but it isn't, at least in the // first release of .NET: methodBuilder.SetImplementationFlags(MethodImplAttributes.PreserveSig); // Mark any that are out-only params. for (int i = 0; i < areOutParams.Length; i++) { if (areOutParams[i]) { // Note that params are indexed starting with 1, not 0. methodBuilder.DefineParameter(i + 1, ParameterAttributes.Out, null); } } Type t = typeBuilder.CreateType(); return(t.FullName); }
public static Type LoadType(this TypeLoader typeLoader, string typeName, Type requiredBaseType, ConfigurationElement configElement, string propertyName) { Type type; try { type = typeLoader.GetType(typeName, throwOnError: true, ignoreCase: false); } catch (Exception ex) { if (configElement != null) { throw new ConfigurationErrorsException(ex.Message, ex, configElement.ElementInformation.Properties[propertyName].Source, configElement.ElementInformation.Properties[propertyName].LineNumber); } throw new ConfigurationErrorsException(ex.Message, ex); } CheckAssignableType(requiredBaseType, type, configElement, propertyName); return(type); }
private static int nextIndex = 1; // Used for differentiating delegate names within the assembly if necessary. /// <summary> /// This method is called by the DefineNETDelegate Mathematica function. /// </summary> /// <remarks> /// Thie method dynamically creates and returns a new delegate Type object. It does not actually create an /// instance of the type--that would be done by a later call to the Mathematica function NETNewDelegate, which /// calls the createDynamicMethod method above. /// <para> /// This is a rarely-used method. It is only needed when there is not an existing delegate type for a method signature /// you want to use as a callback to Mathematica (refer to the DefineNETDelegate Mathematica function for more information). /// </para> /// </remarks> /// internal static string defineDelegate(string name, string retTypeName, string[] paramTypeNames) { Type retType = retTypeName == null ? typeof(void) : TypeLoader.GetType(Utils.addSystemNamespace(retTypeName), true); Type[] paramTypes = new Type[paramTypeNames == null ? 0 : paramTypeNames.Length]; if (paramTypeNames != null) { for (int i = 0; i < paramTypes.Length; i++) { paramTypes[i] = TypeLoader.GetType(Utils.addSystemNamespace(paramTypeNames[i]), true); } } // Check to see if incoming name conflicts with an existing type name. This is easy to get if user reevals a // DefineNETDelegate call without changing the type name. We make the change for them. Type[] existingTypes = delegateModuleBuilder.GetTypes(); // Use an ArrayList instead of a plain array so that we can simply the name-checking logic by using the Contains() method. System.Collections.ArrayList existingNames = new System.Collections.ArrayList(existingTypes.Length); foreach (Type t in existingTypes) { existingNames.Add(t.Name); } string uniqueName = name; while (existingNames.Contains(uniqueName)) { uniqueName = name + "$" + (nextIndex++); } TypeBuilder typeBuilder = delegateModuleBuilder.DefineType(delegateNamespace + "." + uniqueName, TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Sealed, typeof(MulticastDelegate)); ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[] { typeof(object), typeof(int) }); ctorBuilder.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.Runtime); MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual, retType, paramTypes); methodBuilder.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.Runtime); Type newType = typeBuilder.CreateType(); return(newType.FullName); }
private static EventInfo getEventInfo(object eventsObject, string aqTypeName, string evtName) { EventInfo ei = null; // For a static event, use aqTypeName, for instance use eventsObject. if (eventsObject != null) { Type t = eventsObject.GetType(); EventInfo[] eis = t.GetEvents(BindingFlags.Public | BindingFlags.Instance); foreach (EventInfo e in eis) { if (Utils.memberNamesMatch(e.Name, evtName)) { ei = e; break; } } if (ei == null) { throw new ArgumentException("No public instance event named " + evtName + " exists for the given object."); } } else { Type t = TypeLoader.GetType(aqTypeName, true); EventInfo[] eis = t.GetEvents(BindingFlags.Public | BindingFlags.Static); foreach (EventInfo e in eis) { if (Utils.memberNamesMatch(e.Name, evtName)) { ei = e; break; } } if (ei == null) { throw new ArgumentException("No public static event named " + evtName + " exists for the type " + aqTypeName.Split(',')[0] + "."); } } return(ei); }
private static void CreateBinding(FrameworkElement targetElement, object sourceElement, RelativeSourceBinding bindingConfiguration) { // input check if (targetElement == null) { return; } if (sourceElement == null) { return; } if (bindingConfiguration == null) { return; } // check binding configuration // ...target property must be set if (string.IsNullOrWhiteSpace(bindingConfiguration.TargetProperty)) { return; } // ...path property must be set if (string.IsNullOrWhiteSpace(bindingConfiguration.Path)) { return; } // support of attached property binding syntax: TargetProperty='(Grid.Row)' string targetPropertyName = (bindingConfiguration.TargetProperty + "").Trim().TrimStart('(').TrimEnd(')') + "Property"; // find the target dependency property DependencyProperty targetDependencyProperty = null; if (targetPropertyName.Contains(".")) { // it is an attached dependency property string[] parts = targetPropertyName.Split('.'); if (parts.Length == 2 && !string.IsNullOrWhiteSpace(parts[0]) && !string.IsNullOrWhiteSpace(parts[1])) { Type attachedType = TypeLoader.GetType(parts[0], bindingConfiguration.TargetNamespace); if (attachedType != null) { FieldInfo[] targetFields = attachedType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); FieldInfo targetDependencyPropertyField = targetFields.FirstOrDefault(i => i.Name == parts[1]); if (targetDependencyPropertyField != null) { targetDependencyProperty = targetDependencyPropertyField.GetValue(null) as DependencyProperty; } } } } else { // it is a standard dependency property FieldInfo[] targetFields = targetElement.GetType().GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); FieldInfo targetDependencyPropertyField = targetFields.FirstOrDefault(i => i.Name == targetPropertyName); if (targetDependencyPropertyField != null) { targetDependencyProperty = targetDependencyPropertyField.GetValue(null) as DependencyProperty; } } // set binding if (targetDependencyProperty != null) { Binding binding = new Binding(); binding.Source = sourceElement; binding.Path = new PropertyPath(bindingConfiguration.Path); binding.Mode = bindingConfiguration.BindingMode; binding.Converter = bindingConfiguration.Converter; binding.ConverterParameter = bindingConfiguration.ConverterParameter; binding.ConverterCulture = bindingConfiguration.ConverterCulture; binding.NotifyOnValidationError = bindingConfiguration.NotifyOnValidationError; binding.ValidatesOnDataErrors = bindingConfiguration.ValidatesOnDataErrors; binding.ValidatesOnExceptions = bindingConfiguration.ValidatesOnExceptions; binding.ValidatesOnNotifyDataErrors = bindingConfiguration.ValidatesOnNotifyDataErrors; // set the binding on our target element targetElement.SetBinding(targetDependencyProperty, binding); } }
public static void InitializeServices() { if (!initialized) { //this could be a critical section, but it's not the end of the world if it executes twice. initialized = true; log.Info("Starting up DreamSpell"); //set the DataProviderFactory. /* * try * { * DataProvider.Factory = DataProviderFactory.Factory; * } * catch (Exception e) * { * log.Error (e); * } * log.Debug ("set dataprovider factory", DataProvider.Factory); */ //set the cache provider. string cacheProvider = Setting.GetValueT <string>("CacheProvider"); log.Debug("cacheProvider key : ", cacheProvider); if (!String.IsNullOrEmpty(cacheProvider)) { Type cacheType = TypeLoader.GetType(cacheProvider); if (cacheType != null) { ICacheProvider cacheInstance = (ICacheProvider)Activator.CreateInstance(cacheType); CacheProvider.Instance = cacheInstance; log.Info("Activated provider ", cacheInstance); } else { throw new InvalidOperationException(string.Format("Could not initialize provider '{0}' for service '{1}'", cacheProvider, "CacheProvider")); } } else { log.Warn("Using default provider for cache."); } //set the search provider. string searchProvider = Setting.GetValueT <string>("SearchProvider"); log.Debug("searchProvider key : ", searchProvider); if (!String.IsNullOrEmpty(searchProvider)) { Type searchType = TypeLoader.GetType(searchProvider); if (searchType != null) { ISearchServiceProvider searchInstance = (ISearchServiceProvider)Activator.CreateInstance(searchType); EmergeTk.Model.Search.IndexManager.Instance = searchInstance; log.Info("Activated provider ", EmergeTk.Model.Search.IndexManager.Instance); searchInstance.CommitEnabled = Setting.GetValueT <bool>("SearchCommitEnabled", true); } else { throw new InvalidOperationException(string.Format("Could not initialize provider '{0}' for service '{1}'", searchProvider, "SearchProvider")); } } else { log.Warn("Using default provider for search."); } } }
/// <summary> /// Weaves the specified method. /// </summary> /// <param name="markedMethod">The marked method.</param> /// <param name="types">The types.</param> private void WeaveAdvices(MarkedNode markedMethod, Types types) { var method = markedMethod.Node.Method; // sanity check var moduleDefinition = method.Module; if (method.ReturnType.SafeEquivalent(moduleDefinition.SafeImport(typeof(void)))) { var customAttributes = method.CustomAttributes; if (customAttributes.Any(c => c.AttributeType.Name == "AsyncStateMachineAttribute")) { Logger.WriteWarning("Advising async void method '{0}' could confuse async advices. Consider switching its return type to async Task.", method.FullName); } } if (method.IsAbstract) { method.Attributes = (method.Attributes & ~MethodAttributes.Abstract) | MethodAttributes.Virtual; Logger.WriteDebug("Weaving abstract method '{0}'", method.FullName); WritePointcutBody(method, null, false); } else if (markedMethod.AbstractTarget) { Logger.WriteDebug("Weaving and abstracting method '{0}'", method.FullName); WritePointcutBody(method, null, true); } else { Logger.WriteDebug("Weaving method '{0}'", method.FullName); var methodName = method.Name; // our special recipe, with weaving advices var weavingAdvicesMarkers = GetAllMarkers(markedMethod.Node, types.WeavingAdviceAttributeType, types).ToArray(); if (weavingAdvicesMarkers.Any()) { var typeDefinition = markedMethod.Node.Method.DeclaringType; var initialType = TypeLoader.GetType(typeDefinition); var weaverMethodWeavingContext = new WeaverMethodWeavingContext(typeDefinition, initialType, methodName, types); foreach (var weavingAdviceMarker in weavingAdvicesMarkers) { var weavingAdviceType = TypeLoader.GetType(weavingAdviceMarker.Type); var weavingAdvice = (IWeavingAdvice)Activator.CreateInstance(weavingAdviceType); var methodWeavingAdvice = weavingAdvice as IMethodWeavingAdvice; if (methodWeavingAdvice != null && !method.IsGetter && !method.IsSetter) { methodWeavingAdvice.Advise(weaverMethodWeavingContext); } } if (weaverMethodWeavingContext.TargetMethodName != methodName) { methodName = method.Name = weaverMethodWeavingContext.TargetMethodName; } } // create inner method const MethodAttributes attributesToKeep = MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.PInvokeImpl | MethodAttributes.UnmanagedExport | MethodAttributes.HasSecurity | MethodAttributes.RequireSecObject; var innerMethodAttributes = method.Attributes & attributesToKeep | (InjectAsPrivate ? MethodAttributes.Private : MethodAttributes.Public); string innerMethodName; if (method.IsGetter) { innerMethodName = GetPropertyInnerGetterName(GetPropertyName(methodName)); } else if (method.IsSetter) { innerMethodName = GetPropertyInnerSetterName(GetPropertyName(methodName)); } else { innerMethodName = GetInnerMethodName(methodName); } var innerMethod = new MethodDefinition(innerMethodName, innerMethodAttributes, method.ReturnType); innerMethod.GenericParameters.AddRange(method.GenericParameters.Select(p => p.Clone(innerMethod))); innerMethod.ImplAttributes = method.ImplAttributes; innerMethod.SemanticsAttributes = method.SemanticsAttributes; innerMethod.Parameters.AddRange(method.Parameters); if (method.IsPInvokeImpl) { innerMethod.PInvokeInfo = method.PInvokeInfo; // must be removed before attributes are updated (otherwise Cecil gets angry) method.PInvokeInfo = null; method.IsPreserveSig = false; method.IsPInvokeImpl = false; } else { innerMethod.Body.InitLocals = method.Body.InitLocals; innerMethod.Body.Instructions.AddRange(method.Body.Instructions); innerMethod.Body.Variables.AddRange(method.Body.Variables); innerMethod.Body.ExceptionHandlers.AddRange(method.Body.ExceptionHandlers); } WritePointcutBody(method, innerMethod, false); lock (method.DeclaringType) method.DeclaringType.Methods.Add(innerMethod); } }
/// <summary> /// When overridden in a derived class, controls the binding of a serialized object to a type. /// </summary> /// <returns> /// The type of the object the formatter creates a new instance of. /// </returns> /// <param name="assemblyName"> /// Specifies the <see cref="T:System.Reflection.Assembly" /> name of the serialized object. /// </param> /// <param name="typeName"> /// Specifies the <see cref="T:System.Type" /> name of the serialized object. /// </param> public override Type BindToType(string assemblyName, string typeName) { return(TypeLoader.GetType(Assembly.CreateQualifiedName(assemblyName, typeName))); }