コード例 #1
0
 public static ISenderReceiver GetBuilder(BuilderType type)
 {
     ISenderReceiver people = null;
     switch (type)
     {
         case BuilderType.Hello:
             people = new HelloBuilder();
             break;
         case BuilderType.Hi:
             people = new HiBuilder();
             break;
     }
     return people;
 }
コード例 #2
0
 public static void ImplementAssignMethodAttribute(Builder builder, AssignMethodAttributeInfo[] assignMethodAttributeInfos, Field interceptorInstance, BuilderType contentType, Coder coder) =>
 ImplementAssignMethodAttribute(builder, assignMethodAttributeInfos,
                                (delegateCtor, method, assignMethodAttributeInfo) => coder.Load(interceptorInstance)
                                .As(contentType)
                                .SetValue(assignMethodAttributeInfo.AttributeField, y => y.NewObj(delegateCtor, method.ThisOrNull(), method)));
コード例 #3
0
 protected BooleanExpressionCoderBase(BooleanExpressionCoderBase self, BuilderType builderType) : base(self.instructions, self.jumpTargets, builderType)
 {
 }
コード例 #4
0
 internal VariableCoder(InstructionBlock instructionBlock, BuilderType builderType) : base(instructionBlock) => this.builderType = builderType;
コード例 #5
0
 CoderBase ICasting.As(BuilderType type) => this.As(type);
コード例 #6
0
 internal BooleanExpressionFieldCoder(BooleanExpressionCoderBase coder, BuilderType builderType) : base(coder, builderType)
 {
 }
コード例 #7
0
        static public int AddUnsignedInt(UInt32 dataNum, byte[] dataStream, UInt16 addPos, BuilderType builderType)
        {
            int retValue = 0;

            if (builderType == BuilderType.BYTE)
            {
                byte _data = (byte)dataNum;
                dataStream[addPos] = (byte)(_data & 0xff);
                retValue           = 1;
            }
            else if (builderType == BuilderType.INT16_BYTE)
            {
                UInt16 _data = (UInt16)dataNum;
                dataStream[addPos]     = (byte)(_data & 0xff);
                dataStream[addPos + 1] = (byte)((_data >> 8) & 0xff);
                retValue = 2;
            }
            else if (builderType == BuilderType.INT32_BYTE)
            {
                UInt32 _data = (UInt32)dataNum;
                dataStream[addPos]     = (byte)(_data & 0xff);
                dataStream[addPos + 1] = (byte)((_data >> 8) & 0xff);
                dataStream[addPos + 2] = (byte)((_data >> 16) & 0xff);
                dataStream[addPos + 3] = (byte)((_data >> 24) & 0xff);
                retValue = 4;
            }
            return(retValue);
        }
コード例 #8
0
 internal FieldCoder(InstructionBlock instructionBlock, BuilderType builderType) : base(instructionBlock) => this.builderType = builderType;
コード例 #9
0
 public static Field GetChanged(BuilderType builderType) => builderType.GetField("Changed", false);
コード例 #10
0
        //foreach (EbControl control in Controls)
        //{
        //    if (control is EbControlContainer)
        //    {
        //        EbControlContainer Cont = control as EbControlContainer;
        //        if (Cont.TableName.IsNullOrEmpty()|| Cont.TableName.Trim() == string.Empty)
        //        {
        //            Cont.TableName = TableName;
        //        }
        //    }
        //}

        //public virtual string GetSelectQuery(string _parentTblName)
        //{
        //	string ColoumsStr = Get1stLvlColNames();
        //	string qry = string.Empty;
        //	if (ColoumsStr.Length > 0)
        //	{
        //		if (TableName == _parentTblName)
        //			qry = string.Format("SELECT id, {0} FROM {1} WHERE {3} = {2};", ColoumsStr, TableName, TableRowId, "id");
        //		else
        //			qry = string.Format("SELECT id, {0} FROM {1} WHERE {3}={2};", ColoumsStr, TableName, TableRowId, _parentTblName + "_id");

        //	}

        //	foreach (EbControl control in Controls)
        //	{
        //		if (control is EbControlContainer)
        //		{
        //			EbControlContainer _control = (control as EbControlContainer);
        //			if (_control.TableName.IsNullOrEmpty())
        //			{
        //				_control.TableName = TableName;
        //			}
        //			//_control.TableName = _control.TableName.IsNullOrEmpty() ? TableName : _control.TableName;
        //			_control.TableRowId = (_control.TableRowId == 0) ? TableRowId : _control.TableRowId;
        //			qry += _control.GetSelectQuery(_parentTblName);
        //		}
        //	}
        //	return qry;
        //}

        public static string GetControlOpsJS(EbControlContainer ebControlContainer, BuilderType FormTypeEnum)
        {
            string JSCode = "var ControlOps = {}";

            Type[] _typeArray = (ebControlContainer.GetType().GetTypeInfo().Assembly.GetTypes());
            Dictionary <string, string> DictControlOps = new Dictionary <string, string>();

            foreach (Type ctrlType in _typeArray)
            {
                try
                {
                    TypeInfo _typeInfo       = ctrlType.GetTypeInfo();
                    var      _enableInBuider = _typeInfo.GetCustomAttribute <EnableInBuilder>();
                    string   TypeName        = ctrlType.Name.Substring(2, ctrlType.Name.Length - 2);

                    if (_enableInBuider != null && _enableInBuider.BuilderTypes.Contains(FormTypeEnum))
                    {
                        object ctrlObj = Activator.CreateInstance(ctrlType);
                        if (
                            //(!_typeInfo.IsDefined(typeof(HideInToolBox))) && // temp
                            ctrlObj is EbControl)
                        {
                            if (!DictControlOps.ContainsKey(TypeName))
                            {
                                EbControl _ctrlObj = (ctrlObj as EbControl);
                                string    opFnsJs  = string.Empty;
                                opFnsJs += GetOpFnJs("getValue", _ctrlObj.GetValueJSfn, TypeName);
                                opFnsJs += GetOpFnJs("getValueFromDOM", _ctrlObj.GetValueFromDOMJSfn, TypeName);
                                opFnsJs += GetOpFnJs("getDisplayMember", _ctrlObj.GetDisplayMemberJSfn, TypeName);
                                opFnsJs += GetOpFnJs("getDisplayMemberFromDOM", _ctrlObj.GetDisplayMemberFromDOMJSfn, TypeName);
                                opFnsJs += GetOpFnJs("isRequiredOK", _ctrlObj.IsRequiredOKJSfn, TypeName);
                                opFnsJs += GetOpFnJs("isEmpty", _ctrlObj.IsEmptyJSfn, TypeName);
                                opFnsJs += GetOpFnJs("setValue", _ctrlObj.SetValueJSfn, TypeName);
                                opFnsJs += GetOpFnJs("setDisplayMember", _ctrlObj.SetDisplayMemberJSfn, TypeName);
                                opFnsJs += GetOpFnJs("justSetValue", _ctrlObj.JustSetValueJSfn, TypeName);
                                opFnsJs += GetOpFnJs("hide", _ctrlObj.HideJSfn, TypeName);
                                opFnsJs += GetOpFnJs("show", _ctrlObj.ShowJSfn, TypeName);
                                opFnsJs += GetOpFnJs("enable", _ctrlObj.EnableJSfn, TypeName);
                                opFnsJs += GetOpFnJs("disable", _ctrlObj.DisableJSfn, TypeName);
                                opFnsJs += GetOpFnJs("reset", _ctrlObj.ResetJSfn, TypeName);
                                opFnsJs += GetOpFnJs("refresh", _ctrlObj.RefreshJSfn, TypeName);
                                opFnsJs += GetOpFnJs("clear", _ctrlObj.ClearJSfn, TypeName);
                                opFnsJs += GetOpFnJs("addInvalidStyle", _ctrlObj.AddInvalidStyleJSFn, TypeName);
                                opFnsJs += GetOpFnJs("removeInvalidStyle", _ctrlObj.RemoveInvalidStyleJSFn, TypeName);
                                opFnsJs += GetOpFnJs("bindOnChange", _ctrlObj.OnChangeBindJSFn, TypeName);

                                if (_ctrlObj.ObjType == "DGPowerSelectColumn")
                                {
                                    opFnsJs += GetOpFnJs("getColumn", _ctrlObj.GetColumnJSfn, TypeName);
                                }

                                string fn = string.Concat("function ", TypeName, "(jsonObj){ $.extend(this, jsonObj);", opFnsJs, "}");//.RemoveCR();

                                JSCode += string.Concat(@"
                                                        ControlOps.", TypeName, " = ", fn);;

                                DictControlOps.Add(TypeName, "fn placeholder");
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return(JSCode);
        }
コード例 #11
0
        /// <summary>
        /// Makes the transformer builder following the specified builder type.
        /// </summary>
        /// <typeparam name="TSource">The type of the source.</typeparam>
        /// <typeparam name="TDestination">The type of the destination.</typeparam>
        /// <param name="type">The builder type to use.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException">Builder type not implemented by now.</exception>
        public ITransformerBuilder <TSource, TDestination> MakeTransformerBuilder <TSource, TDestination>(BuilderType type)
            where TSource : class
            where TDestination : class
        {
            switch (type)
            {
            case BuilderType.DefaultMappers:
                return(new TransformerBuilder <TSource, TDestination>(this, FactoryMapper.GetDefaultPropertyMappers <TSource, TDestination>()));

            case BuilderType.Empty:
                return(new TransformerBuilder <TSource, TDestination>(this));

            case BuilderType.DynamicResolver:
                return(new TransformerBuilder <TSource, TDestination>(this, FactoryMapper.GetDefaultPropertyMappers <TSource, TDestination>(this)));

            default:
                throw new NotImplementedException("Builder type not implemented by now.");
            }
        }
コード例 #12
0
    private static AssignMethodAttributeInfo[] GetAllAssignMethodAttributedFields(Method attributedMethod, BuilderCustomAttribute builderCustomAttribute, BuilderType targetType, string name, string returnTypeName)
    {
        var fields = builderCustomAttribute.Type
                     .GetAttributedFields()
                     .Where(x => x.Field.IsPublic && !x.Field.IsStatic && x.Attribute.Fullname == __AssignMethodAttribute.Type.Fullname)
                     .Select(x => x.Import());

        if (!fields.Any())
        {
            return(new AssignMethodAttributeInfo[0]);
        }

        return(fields
               .Select(x =>
        {
            var throwError = !(bool)x.Attribute.ConstructorArguments[1].Value;
            return new AssignMethodAttributeInfo
            {
                AttributeField = x.Field,
                TargetMethodName = ReplacePlaceHolder(targetType.Builder, x.Attribute.ConstructorArguments[0].Value as string ?? "", name, returnTypeName, builderCustomAttribute, throwError),
                TargetMethodReturnType = GetDelegateType(x.Field.FieldType),
                ThrowError = throwError,
                Type = targetType,
                ParameterTypes = GetParameters(x.Field.FieldType),
                AttributedMethod = attributedMethod
            };
        }).ToArray());
    }
コード例 #13
0
ファイル: ModuleWeaver.cs プロジェクト: ChaseFlorell/Cauldron
        private Method CreateAssigningMethod(BuilderType anonSource, BuilderType anonTarget, BuilderType anonTargetInterface, Method method)
        {
            var name         = $"<{counter++}>f__Anon_Assign";
            var assignMethod = method.DeclaringType.CreateMethod(Modifiers.PrivateStatic, anonTarget, name, anonSource);

            assignMethod.NewCode()
            .Context(x =>
            {
                var resultVar = x.GetReturnVariable();
                x.Assign(resultVar).Set(x.NewCode().NewObj(anonTarget.ParameterlessContructor));

                foreach (var property in anonSource.Properties)
                {
                    try
                    {
                        var targetProperty = anonTarget.GetProperty(property.Name);
                        if (property.ReturnType.Fullname != targetProperty.ReturnType.Fullname)
                        {
                            this.LogError($"The property '{property.Name}' in '{method.Name}' in type '{method.DeclaringType.Name}' does not have the expected return type. Is: {property.ReturnType.Fullname} Expected: {targetProperty.ReturnType.Fullname}");
                            continue;
                        }
                        x.Load(resultVar).Callvirt(targetProperty.Setter, x.NewCode().Load(x.GetParameter(0)).Callvirt(property.Getter));
                    }
                    catch (MethodNotFoundException)
                    {
                        this.LogWarning($"The property '{property.Name}' does not exist in '{anonTarget.Name}'");
                    }
                }

                x.Load(resultVar).Return();
            })
            .Replace();

            assignMethod.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);

            return(assignMethod);
        }
コード例 #14
0
    public static void Implement(Builder builder)
    {
        builder.Log(LogTypes.Info, "Creating Cauldron Cache");

        var cauldron                  = builder.GetType("CauldronInterceptionHelper", SearchContext.Module);
        var componentAttribute        = BuilderTypes.ComponentAttribute;
        var genericComponentAttribute = BuilderTypes.GenericComponentAttribute;

        // Before we start let us find all factoryextensions and add a component attribute to them
        var factoryResolverInterface = (BuilderType)BuilderTypes.IFactoryExtension;

        AddComponentAttribute(builder, builder.FindTypesByInterface(factoryResolverInterface), x => factoryResolverInterface);

        // Get all Components
        var componentTypes = new List <BuilderType>();
        var components     = builder
                             .FindTypesByAttribute(componentAttribute)
                             .Concat(builder
                                     .CustomAttributes
                                     .Where(x => x.Type == genericComponentAttribute)
                                     .Select(x => new
        {
            Attribute = BuilderCustomAttribute.Create(componentAttribute, x.ConstructorArguments.Skip(1)),
            Type      = (x.ConstructorArguments[0].Value as TypeReference).ToBuilderType()
        })
                                     .Where(x =>
        {
            if (x.Type.IsAbstract)
            {
                builder.Log(LogTypes.Error, $"The GenericComponentAttribute does not support abstract types.");
                return(false);
            }

            if (x.Type.IsInterface)
            {
                builder.Log(LogTypes.Error, $"The GenericComponentAttribute does not support interfaces.");
                return(false);
            }

            if (x.Type.IsValueType)
            {
                builder.Log(LogTypes.Error, $"The GenericComponentAttribute does not support value types.");
                return(false);
            }

            return(true);
        })
                                     .Select(x => new AttributedType(x.Type, x.Attribute)));

        foreach (var component in components)
        {
            var factoryType = FactoryTypeInfoWeaver.Create(component);
            componentTypes.Add(factoryType);
        }

        builder.Log(LogTypes.Info, "Adding component IFactoryCache Interface");

        var linqEnumerable   = builder.GetType("System.Linq.Enumerable", SearchContext.AllReferencedModules);
        var ifactoryTypeInfo = BuilderTypes.IFactoryTypeInfo.BuilderType.Import().MakeArray();
        var getComponentsFromOtherAssemblies = builder.ReferencedAssemblies
                                               .Select(x => x.MainModule.GetType("CauldronInterceptionHelper"))
                                               .Where(x => x != null)
                                               .Select(x => x.ToBuilderType())
                                               .Select(x => x.GetMethod("GetComponents", false)?.Import())
                                               .Where(x => x != null)
                                               .ToArray();

        var getComponentsMethod = cauldron.CreateMethod(Modifiers.Public | Modifiers.Static, ifactoryTypeInfo, "GetComponents");
        var componentsField     = cauldron.CreateField(Modifiers.PrivateStatic, ifactoryTypeInfo, "<FactoryType>f__components");

        getComponentsMethod
        .NewCoder()
        .NewCoder()
        .Context(context =>
        {
            context.If(x => x.Load(componentsField).IsNotNull(), then => then.Load(componentsField).Return());

            var resultValue = context.GetOrCreateReturnVariable();
            context.SetValue(resultValue, x => x.Newarr(BuilderTypes.IFactoryTypeInfo, componentTypes.Count));

            for (int i = 0; i < componentTypes.Count; i++)
            {
                context
                .Load(resultValue)
                .StoreElement(context.NewCoder().NewObj(componentTypes[i].ParameterlessContructor), i);
            }

            context.SetValue(componentsField, resultValue);
            return(context.Load(resultValue).Return());
        })
        .Replace();

        var voidMain = builder.GetMain();

        if (voidMain != null)
        {
            voidMain.NewCoder()
            .Context(context =>
            {
                context.Call(builder.GetType("Cauldron.Activator.FactoryCore").GetMethod("SetComponents", 1, true), x => x.Call(getComponentsMethod));
                if (getComponentsFromOtherAssemblies.Length > 0)
                {
                    foreach (var item in getComponentsFromOtherAssemblies)
                    {
                        context.Call(builder.GetType("Cauldron.Activator.FactoryCore").GetMethod("SetComponents", 1, true), x => x.Call(item));
                    }
                }

                return(context);
            })
            .End
            .Insert(InsertionPosition.Beginning);
        }

        var injectAttribute = new BuilderType[] { builder.GetType("Cauldron.Activator.InjectAttribute") };
        var properties      = builder.FindPropertiesByAttributes(injectAttribute).ToArray();
        var fields          = builder.FindFieldsByAttributes(injectAttribute).ToArray();

        ImplementInjectField(builder, fields);
        ImplementInjectProperties(builder, properties);
        ReplaceFactoryCreate(builder);
    }
コード例 #15
0
        private void CreateComponentCache(Builder builder, BuilderType cauldron)
        {
            var componentAttribute            = __ComponentAttribute.Instance;
            var componentConstructorAttribute = __ComponentConstructorAttribute.Type;
            var factory = __Factory.Instance;

            // Before we start let us find all factoryextensions and add a component attribute to them
            var factoryResolverInterface = __IFactoryResolver.Type;

            this.AddComponentAttribute(builder, builder.FindTypesByInterface(factoryResolverInterface), x => factoryResolverInterface.Fullname);
            // Also the same to all types that inherits from Factory<>
            var factoryGeneric = __Factory_1.Type;

            this.AddComponentAttribute(builder, builder.FindTypesByBaseClass(factoryGeneric), type =>
            {
                var factoryBase = type.BaseClasses.FirstOrDefault(x => x.Fullname.StartsWith("Cauldron.Activator.Factory"));
                if (factoryBase == null)
                {
                    return(type.Fullname);
                }

                return(factoryBase.GetGenericArgument(0).Fullname);
            });

            int counter     = 0;
            var arrayAvatar = builder.GetType("System.Array").New(x => new
            {
                Length = x.GetMethod("get_Length")
            });
            var extensionAvatar = builder.GetType("Cauldron.ExtensionsReflection").New(x => new
            {
                CreateInstance = x.GetMethod("CreateInstance", 2)
            });
            var factoryCacheInterface         = builder.GetType("Cauldron.Activator.IFactoryCache");
            var factoryTypeInfoInterface      = builder.GetType("Cauldron.Activator.IFactoryTypeInfo");
            var createInstanceInterfaceMethod = factoryTypeInfoInterface.GetMethod("CreateInstance", 1);

            // Get all Components
            var components     = builder.FindTypesByAttribute(componentAttribute.ToBuilderType);
            var componentTypes = new List <BuilderType>();

            // Create types with the components properties
            foreach (var component in components)
            {
                this.Log("Hardcoding component factory .ctor: " + component.Type.Fullname);

                var componentType           = builder.CreateType("", TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, $"<>f__IFactoryTypeInfo_{component.Type.Name}_{counter++}");
                var componentAttributeField = componentType.CreateField(Modifiers.Private, componentAttribute.ToBuilderType, "componentAttribute");
                componentType.AddInterface(factoryTypeInfoInterface);
                componentTypes.Add(componentType);

                // Create ctor
                componentType
                .CreateConstructor()
                .NewCode()
                .Context(x =>
                {
                    x.Load(Crumb.This).Call(builder.GetType(typeof(object)).Import().ParameterlessContructor.Import());
                    x.Assign(componentAttributeField).NewObj(component);
                })
                .Return()
                .Replace();

                // Implement the methods
                componentType.CreateMethod(Modifiers.Public | Modifiers.Overrrides, createInstanceInterfaceMethod.ReturnType, createInstanceInterfaceMethod.Name, createInstanceInterfaceMethod.Parameters)
                .NewCode()
                .Context(x =>
                {
                    var localVariable = x.GetReturnVariable();
                    // Find any method with a componentcontructor attribute
                    var ctors = component.Type.GetMethods(y =>
                    {
                        if (y.Name == ".cctor")
                        {
                            return(true);
                        }

                        if (!y.Resolve().IsPublic || !y.Resolve().IsAssembly)
                        {
                            return(false);
                        }

                        if (y.Name == ".ctor" && y.DeclaringType.FullName.GetHashCode() != component.Type.Fullname.GetHashCode() && y.DeclaringType.FullName != component.Type.Fullname)
                        {
                            return(false);
                        }

                        if (y.Name.StartsWith("set_"))
                        {
                            return(false);
                        }

                        return(true);
                    })
                                .Where(y => y.CustomAttributes.HasAttribute(componentConstructorAttribute))
                                .Concat(
                        component.Type.GetAllProperties().Where(y => y.CustomAttributes.HasAttribute(componentConstructorAttribute))
                        .Select(y =>
                    {
                        y.CustomAttributes.Remove(componentConstructorAttribute);
                        y.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);

                        return(y.Getter);
                    })
                        )
                                .OrderBy(y => y.Parameters.Length)
                                .ToArray();

                    if (ctors.Length > 0)
                    {
                        bool parameterlessCtorAlreadyHandled = false;

                        for (int index = 0; index < ctors.Length; index++)
                        {
                            this.Log("- " + ctors[index].Fullname);

                            var ctor = ctors[index];
                            // add a EditorBrowsable attribute
                            ctor.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);
                            var ctorParameters = ctor.Parameters;

                            if (ctorParameters.Length > 0)
                            {
                                // In this case we have to find a parameterless constructor first
                                if (component.Type.ParameterlessContructor != null && !parameterlessCtorAlreadyHandled && component.Type.ParameterlessContructor.IsPublicOrInternal)
                                {
                                    x.Load(Crumb.GetParameter(0)).IsNull().Then(y => y.NewObj(component.Type.ParameterlessContructor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                    x.Load(Crumb.GetParameter(0)).Call(arrayAvatar.Length).EqualTo(0).Then(y => y.NewObj(component.Type.ParameterlessContructor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                    parameterlessCtorAlreadyHandled = true;
                                }

                                var code = x.Load(Crumb.GetParameter(0)).Call(arrayAvatar.Length).EqualTo(ctorParameters.Length);

                                for (int i = 0; i < ctorParameters.Length; i++)
                                {
                                    code.And.Load(Crumb.GetParameter(0).UnPacked(i)).Is(ctorParameters[i]);
                                }

                                if (ctor.Name == ".ctor")
                                {
                                    code.Then(y => y.NewObj(ctor, Crumb.GetParameter(0).UnPacked()).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                }
                                else
                                {
                                    code.Then(y => y.Call(ctor, Crumb.GetParameter(0).UnPacked()).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                }
                            }
                            else
                            {
                                if (ctor.Name == ".ctor")
                                {
                                    x.Load(Crumb.GetParameter(0)).IsNull().Then(y => y.NewObj(ctor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                    x.Load(Crumb.GetParameter(0)).Call(arrayAvatar.Length).EqualTo(0).Then(y => y.NewObj(ctor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                }
                                else
                                {
                                    x.Load(Crumb.GetParameter(0)).IsNull().Then(y => y.Call(ctor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                    x.Load(Crumb.GetParameter(0)).Call(arrayAvatar.Length).EqualTo(0).Then(y => y.Call(ctor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                                }

                                parameterlessCtorAlreadyHandled = true;
                            }
                        }
                    }
                    else
                    {
                        // In case we don't have constructor with ComponentConstructor Attribute,
                        // then we should look for a parameterless Ctor
                        if (component.Type.ParameterlessContructor == null)
                        {
                            this.Log(LogTypes.Error, component.Type, $"The component '{component.Type.Fullname}' has no ComponentConstructor attribute or the constructor is not public");
                        }
                        else if (component.Type.ParameterlessContructor.IsPublicOrInternal)
                        {
                            x.Load(Crumb.GetParameter(0)).IsNull().Then(y => y.NewObj(component.Type.ParameterlessContructor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());
                            x.Load(Crumb.GetParameter(0)).Call(arrayAvatar.Length).EqualTo(0).Then(y => y.NewObj(component.Type.ParameterlessContructor).Dup().Call(factory.OnObjectCreation, Crumb.This).Return());

                            this.Log($"The component '{component.Type.Fullname}' has no ComponentConstructor attribute. A parameterless ctor was found and will be used.");
                        }
                    }
                })
                .Context(x => x.Call(extensionAvatar.CreateInstance, component.Type, Crumb.GetParameter(0)).Dup().Call(factory.OnObjectCreation, Crumb.This).Return())
                .Return()
                .Replace();

                // Implement the properties
                foreach (var property in factoryTypeInfoInterface.Properties)
                {
                    var propertyResult = componentType.CreateProperty(Modifiers.Public | Modifiers.Overrrides, property.ReturnType, property.Name, true);
                    propertyResult.BackingField.Remove();

                    switch (property.Name)
                    {
                    case "ContractName":
                        propertyResult.Getter.NewCode().Call(componentAttributeField, componentAttribute.ContractName).Return().Replace();
                        break;

                    case "CreationPolicy":
                        propertyResult.Getter.NewCode().Call(componentAttributeField, componentAttribute.Policy).Return().Replace();
                        break;

                    case "Priority":
                        propertyResult.Getter.NewCode().Call(componentAttributeField, componentAttribute.Priority).Return().Replace();
                        break;

                    case "Type":
                        propertyResult.Getter.NewCode().Load(component.Type).Return().Replace();
                        break;
                    }
                }

                componentType.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);
                // Also remove the component attribute
                component.Attribute.Remove();
            }

            this.Log("Adding component IFactoryCache Interface");
            cauldron.AddInterface(factoryCacheInterface);
            var factoryCacheInterfaceAvatar = factoryCacheInterface.New(x => new
            {
                Components = x.GetMethod("GetComponents")
            });
            var ctorCoder = cauldron.ParameterlessContructor.NewCode();

            cauldron.CreateMethod(Modifiers.Public | Modifiers.Overrrides, factoryCacheInterfaceAvatar.Components.ReturnType, factoryCacheInterfaceAvatar.Components.Name)
            .NewCode()
            .Context(x =>
            {
                var resultValue = x.GetReturnVariable();
                x.Newarr(factoryTypeInfoInterface, componentTypes.Count).StoreLocal(resultValue);

                for (int i = 0; i < componentTypes.Count; i++)
                {
                    var field = cauldron.CreateField(Modifiers.Private, factoryTypeInfoInterface, "<FactoryType>f__" + i);
                    x.Load(resultValue);
                    x.StoreElement(factoryTypeInfoInterface, field, i);
                    // x.StoreElement(factoryTypeInfoInterface,
                    // x.NewCode().NewObj(componentTypes[i].ParameterlessContructor), i);
                    ctorCoder.Assign(field).NewObj(componentTypes[i].ParameterlessContructor);
                }
            })
            .Return()
            .Replace();

            ctorCoder.Insert(InsertionPosition.End);
        }
コード例 #16
0
        private static void CreateSetterDelegate(Builder builder, Method setterDelegateMethod, BuilderType propertyType,
                                                 Func <ICode, ICode> loadValue, Func <ICode, Func <object>, ICode> setValue)
        {
            var extensions = new __Extensions();
            var iList      = new __IList();
            var setterCode = setterDelegateMethod.NewCode();

            if (propertyType.ParameterlessContructor != null && propertyType.ParameterlessContructor.IsPublic)
            {
                loadValue(setterCode).IsNull().Then(y => setValue(y, () => setterCode.NewCode().NewObj(propertyType.ParameterlessContructor)));
            }

            // Only this if the property implements idisposable
            if (propertyType.Implements(typeof(IDisposable)))
            {
                setterCode.Call(extensions.TryDisposeInternal, loadValue(setterCode.NewCode()));
            }

            setterCode.Load(Crumb.GetParameter(0)).IsNull().Then(x =>
            {
                // Just clear if its clearable
                if (propertyType.Implements(__IList.Type.Fullname))
                {
                    loadValue(x).Callvirt(iList.Clear).Return();
                }
                // Otherwise if the property is not a value type and nullable
                else if (!propertyType.IsValueType || propertyType.IsNullable || propertyType.IsArray)
                {
                    setValue(x, () => null).Return();
                }
                else // otherwise... throw an exception
                {
                    x.ThrowNew(typeof(NotSupportedException), "Value types does not accept null values.");
                }
            });

            if (propertyType.IsArray)
            {
                setterCode.Load(Crumb.GetParameter(0)).Is(typeof(IEnumerable))
                .Then(x => setValue(x, () => Crumb.GetParameter(0)).Return())
                .ThrowNew(typeof(NotSupportedException), "Value does not inherits from IEnumerable");
            }
            else if (propertyType.Implements(__IList.Type.Fullname) && propertyType.ParameterlessContructor != null)
            {
                var addRange = propertyType.GetMethod("AddRange", 1, false);
                if (addRange == null)
                {
                    var add   = propertyType.GetMethod("Add", 1);
                    var array = setterCode.CreateVariable(propertyType.ChildType.MakeArray());
                    setterCode.Assign(array).Set(Crumb.GetParameter(0));
                    setterCode.For(array, (x, item) => loadValue(x).Callvirt(add, item));
                    if (!add.ReturnType.IsVoid)
                    {
                        setterCode.Pop();
                    }
                }
                else
                {
                    loadValue(setterCode).Callvirt(addRange, Crumb.GetParameter(0));
                }
            }
            else if (propertyType.IsEnum)
            {
                // Enums requires special threatment
                setterCode.Load(Crumb.GetParameter(0)).Is(typeof(string)).Then(x =>
                {
                    var stringVariable = setterCode.CreateVariable(typeof(string));
                    setterCode.Assign(stringVariable).Set(Crumb.GetParameter(0));
                    setValue(setterCode, () => stringVariable).Return();
                });

                setValue(setterCode, () => Crumb.GetParameter(0));
            }
            else
            {
                setValue(setterCode, () => Crumb.GetParameter(0));
            }

            setterCode.Return().Replace();
        }
コード例 #17
0
ファイル: Weaver_Property.cs プロジェクト: AnnaGuzy/Cauldron
    private static void CreateSetterDelegate(Builder builder, Method setterDelegateMethod, BuilderType propertyType, object value)
    {
        var setterCode = setterDelegateMethod.NewCoder();

        T CodeMe <T>(Func <Field, T> fieldCode, Func <Property, T> propertyCode) where T : class
        {
            switch (value)
            {
            case Field field: return(fieldCode(field));

            case Property property: return(propertyCode(property));

            default: return(null);
            }
        }

        if (propertyType.ParameterlessContructor != null && propertyType.ParameterlessContructor.IsPublic)
        {
            CodeMe(
                field => setterCode.If(x => x.Load(field).IsNull(), then => then.SetValue(field, x => x.NewObj(propertyType.ParameterlessContructor))),
                property => setterCode.If(x => x.Call(property.Getter).IsNull(), then => then.Call(property.Setter, x => x.NewObj(propertyType.ParameterlessContructor))));
        }

        // Only this if the property implements idisposable
        if (propertyType.Implements(typeof(IDisposable)))
        {
            CodeMe(
                field => setterCode.Call(BuilderTypes.Extensions.GetMethod_TryDisposeInternal(), x => x.Load(field)),
                property => setterCode.Call(BuilderTypes.Extensions.GetMethod_TryDisposeInternal(), x => x.Call(property.Getter)));
        }

        setterCode.If(x => x.Load(CodeBlocks.GetParameter(0)).IsNull(), then =>
        {
            // Just clear if its clearable
            if (propertyType.Implements(BuilderTypes.IList))
            {
                CodeMe(
                    field => setterCode.Load(field).Call(BuilderTypes.IList.GetMethod_Clear()).Return(),
                    property => setterCode.Call(property.Getter).Call(BuilderTypes.IList.GetMethod_Clear()).Return());
            }
            // Otherwise if the property is not a value type and nullable
            else if (!propertyType.IsValueType || propertyType.IsNullable || propertyType.IsArray)
            {
                CodeMe <CoderBase>(
                    field => setterCode.SetValue(field, null),
                    property => setterCode.Call(property.Setter, null));
            }
            else // otherwise... throw an exception
            {
                then.ThrowNew(typeof(NotSupportedException), "Value types does not accept null values.");
            }

            return(then);
        });

        setterCode.If(x => CodeMe(
                          field => x.Load(CodeBlocks.GetParameter(0)).Is(field.FieldType),
                          property => x.Load(CodeBlocks.GetParameter(0)).Is(property.ReturnType)), then =>
                      CodeMe(
                          field => then.SetValue(field, CodeBlocks.GetParameter(0)).Return(),
                          property => then.Call(property.Setter, CodeBlocks.GetParameter(0)).Return()));

        if (propertyType.Implements(BuilderTypes.IList))
        {
            var add   = propertyType.GetMethod("Add", 1);
            var array = setterDelegateMethod.GetOrCreateVariable(propertyType.ChildType.MakeArray());
            setterCode.SetValue(array, CodeBlocks.GetParameter(0));
            setterCode.For(array, (x, item, indexer) => CodeMe(
                               field => x.Load(field).Call(add, item()),
                               property => x.Call(property.Getter).Call(add, item())));
            if (!add.ReturnType.IsVoid)
            {
                setterCode.Pop();
            }
        }
        else if (propertyType.Implements(typeof(IEnumerable)) || propertyType.IsArray)
        {
            setterCode.If(x => x.Load(CodeBlocks.GetParameter(0)).Is(typeof(IEnumerable)), then =>
                          CodeMe(
                              field => then.SetValue(field, CodeBlocks.GetParameter(0)).Return(),
                              property => then.Call(property.Setter, CodeBlocks.GetParameter(0)).Return()))
            .ThrowNew(typeof(NotSupportedException), "Value does not inherits from IEnumerable");
        }
        else if (propertyType.IsEnum)
        {
            // Enums requires special threatment
            setterCode.If(x => x.Load(CodeBlocks.GetParameter(0)).Is(typeof(string)),
                          then =>
            {
                var stringVariable = setterDelegateMethod.GetOrCreateVariable(typeof(string));
                then.SetValue(stringVariable, CodeBlocks.GetParameter(0));
                CodeMe(     // Cecilator automagically implements a convertion for this
                    field => then.SetValue(field, stringVariable).Return(),
                    property => then.Call(property.Setter, stringVariable).Return());
                return(then);
            });

            CodeMe <CoderBase>(
                field => setterCode.SetValue(field, CodeBlocks.GetParameter(0)),
                property => setterCode.Call(property.Setter, CodeBlocks.GetParameter(0)));
        }
        else
        {
            CodeMe <CoderBase>(
                field => setterCode.SetValue(field, CodeBlocks.GetParameter(0)),
                property => setterCode.Call(property.Setter, CodeBlocks.GetParameter(0)));
        }

        setterCode.Return().Replace();
    }
コード例 #18
0
 public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message)
 {
     message.ResolvePluginType(BizTalkFactoryProperties.ContextBuilderTypeName, BuilderType)
     .AsPlugin <IContextBuilder>()
     .IfNotNull(
         contextBuilder => {
         if (ExecutionMode == PluginExecutionMode.Deferred)
         {
             if (_logger.IsDebugEnabled)
             {
                 _logger.DebugFormat("Scheduling builder plugin '{0}' for deferred execution.", BuilderType.ToString());
             }
             message.BodyPart.WrapOriginalDataStream(
                 originalStream => {
                 var substitutionStream = new EventingReadStream(originalStream);
                 substitutionStream.AfterLastReadEvent += (src, args) => {
                     if (_logger.IsDebugEnabled)
                     {
                         _logger.DebugFormat("Executing builder plugin '{0}' that was scheduled for deferred execution.", BuilderType.ToString());
                     }
                     contextBuilder.Execute(message.Context);
                 };
                 return(substitutionStream);
             },
                 pipelineContext.ResourceTracker);
         }
         else
         {
             if (_logger.IsDebugEnabled)
             {
                 _logger.DebugFormat("Executing builder plugin '{0}' that is scheduled for immediate execution.", BuilderType.ToString());
             }
             contextBuilder.Execute(message.Context);
         }
     });
     return(message);
 }
コード例 #19
0
 internal BuilderId(YVisibility visibility, BuilderType type)
 {
     this.visibility = visibility;
     this.type       = type;
 }
コード例 #20
0
        static public int AddUnsignedFloat(float dataNum, byte[] dataStream, UInt16 addPos, BuilderType builderType)
        {
            UInt32 _data = 0;

            if (builderType == BuilderType.FLOAT_BYTE_Q8)
            {
                _data = (UInt32)(dataNum * (1 << 8));
            }
            else if (builderType == BuilderType.FLOAT_BYTE_Q16)
            {
                _data = (UInt32)(dataNum * (1 << 16));
            }
            return(AddUnsignedInt(_data, dataStream, addPos, BuilderType.INT32_BYTE));
        }
コード例 #21
0
 internal BooleanExpressionVariableCoder(BooleanExpressionCoderBase coder, BuilderType builderType) : base(coder, builderType)
 {
 }
コード例 #22
0
 public BooleanExpressionFieldCoder As(BuilderType type)
 {
     InstructionBlock.CastOrBoxValues(this, type);
     return(new BooleanExpressionFieldCoder(this, type));
 }
コード例 #23
0
 public CatchCoder Catch(BuilderType exceptionType, Func <CatchThrowerCoder, Func <ExceptionCodeBlock>, Coder> code) => this.CatchInternal(exceptionType, code);
コード例 #24
0
 internal FactoryTypeInfoWeaverBase(ComponentAttributeValues componentAttributeValue, BuilderType componentInfoType, Coder componentTypeCtor, BuilderType componentType, (TypeReference childType, bool isSuccessful) childType)
コード例 #25
0
    private static Method CreateAssigningMethod(Builder builder, BuilderType anonSource, BuilderType anonTarget, BuilderType anonTargetInterface, Method method)
    {
        var name         = $"<{counter++}>f__Anon_Assign";
        var assignMethod = method.OriginType.CreateMethod(Modifiers.PrivateStatic, anonTarget, name, anonSource);

        assignMethod.NewCoder()
        .Context(context =>
        {
            var resultVar = context.GetOrCreateReturnVariable();
            context.SetValue(resultVar, x => x.NewObj(anonTarget.ParameterlessContructor));

            foreach (var property in anonSource.Properties)
            {
                try
                {
                    var targetProperty = anonTarget.GetProperty(property.Name);
                    if (property.ReturnType.Fullname != targetProperty.ReturnType.Fullname)
                    {
                        builder.Log(LogTypes.Error, property, $"The property '{property.Name}' does not have the expected return type. Is: {property.ReturnType.Fullname} Expected: {targetProperty.ReturnType.Fullname}");
                        continue;
                    }
                    context.Load(resultVar).Call(targetProperty.Setter, x => x.Load(CodeBlocks.GetParameter(0)).Call(property.Getter));
                }
                catch (MethodNotFoundException)
                {
                    builder.Log(LogTypes.Warning, anonTarget, $"The property '{property.Name}' does not exist in '{anonTarget.Name}'");
                }
            }

            return(context.Load(resultVar).Return());
        })
        .Replace();

        assignMethod.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);

        return(assignMethod);
    }
コード例 #26
0
 public Field GetIsChangedChanged(BuilderType builderType) => builderType.GetField("IsChangedChanged", false);
        private static IEnumerable <Method> GetValidMethods(DecoratorDecription decorator, BuilderType[] methodParameters, BuilderType @class)
        {
            return(@class.Methods.Where(x =>
            {
                if (x.IsPropertyGetterSetter)
                {
                    return false;
                }

                if (!decorator.TargetMethodFilter.Static && x.IsStatic)
                {
                    return false;
                }

                if (!decorator.TargetMethodFilter.Instanced && !x.IsStatic)
                {
                    return false;
                }

                if (
                    decorator.TargetMethodFilter.Protected && !x.IsProtected &&
                    decorator.TargetMethodFilter.Public && !x.IsPublic &&
                    decorator.TargetMethodFilter.Private && !x.IsPrivate &&
                    decorator.TargetMethodFilter.Internal && !x.IsInternal)
                {
                    return false;
                }

                if (decorator.TargetMethodFilter.ReturnTypeNames.Length > 0 && !decorator.TargetMethodFilter.ReturnTypeNames.Any(y => y == x.Fullname))
                {
                    return false;
                }

                if (decorator.TargetMethodFilter.ParameterMatch)
                {
                    if (!decorator.TargetMethodFilter.ParameterStrict && decorator.TargetMethodFilter.Parameters.Length > 0 && !x.Parameters.AreReferenceAssignable(methodParameters))
                    {
                        return false;
                    }
                    else if (decorator.TargetMethodFilter.ParameterStrict && decorator.TargetMethodFilter.Parameters.Length > 0 && !x.Parameters.SequenceEqual(methodParameters))
                    {
                        return false;
                    }
                }

                if (x.IsGenerated)
                {
                    return false;
                }

                if (!string.IsNullOrEmpty(decorator.TargetMethodFilter.Name) && !Regex.IsMatch(x.Name, decorator.TargetMethodFilter.Name == "*" ? "[a-zA-Z].*" : decorator.TargetMethodFilter.Name, RegexOptions.Singleline))
                {
                    return false;
                }

                return true;
            }));
        }
コード例 #28
0
    public static void ImplementAssignMethodAttribute(Builder builder, AssignMethodAttributeInfo[] assignMethodAttributeInfos, CecilatorBase cecilatorBase, BuilderType contentType, Coder coder)
    {
        switch (cecilatorBase)
        {
        case Field field:
            ImplementAssignMethodAttribute(builder, assignMethodAttributeInfos, field, contentType, coder);
            break;

        case LocalVariable variable:
            ImplementAssignMethodAttribute(builder, assignMethodAttributeInfos, variable, contentType, coder);
            break;

        default:
            throw new NotImplementedException("This is only available for Field and LocalVariable");
        }
    }
        private static IEnumerable <Property> GetValidProperties(DecoratorDecription decorator, BuilderType @class)
        {
            return(@class.Properties.Where(x =>
            {
                if (!decorator.TargetPropertyFilter.Static && x.IsStatic)
                {
                    return false;
                }

                if (!decorator.TargetPropertyFilter.Instanced && !x.IsStatic)
                {
                    return false;
                }

                if (
                    decorator.TargetPropertyFilter.Protected && !x.IsProtected &&
                    decorator.TargetPropertyFilter.Public && !x.IsPublic &&
                    decorator.TargetPropertyFilter.Private && !x.IsPrivate &&
                    decorator.TargetPropertyFilter.Internal && !x.IsInternal)
                {
                    return false;
                }

                if (decorator.TargetPropertyFilter.ReturnTypeNames.Length > 0 && !decorator.TargetPropertyFilter.ReturnTypeNames.Any(y => y == x.ReturnType.Fullname))
                {
                    return false;
                }

                if (x.IsGenerated)
                {
                    return false;
                }

                if (!string.IsNullOrEmpty(decorator.TargetPropertyFilter.Name) && !Regex.IsMatch(x.Name, decorator.TargetMethodFilter.Name == "*" ? "[a-zA-Z].*" : decorator.TargetPropertyFilter.Name, RegexOptions.Singleline))
                {
                    return false;
                }

                return true;
            }));
        }
コード例 #30
0
 public Field GetField(BuilderType builderType) => builderType.GetField(this.Name, true).Import();
コード例 #31
0
 public static bool IsIEnumerable(this BuilderType builderType) =>
 BuilderTypes
 .IEnumerable
 .BuilderType
 .AreReferenceAssignable(builderType) || builderType.IsArray;