Inheritance: System.CodeDom.CodeExpression
コード例 #1
0
        public override void DeclareCodeType(IDLInterface idlIntf)
        {
            // Proxy class.
            typeProxy = new CodeTypeDeclaration(name + "Proxy");
            typeProxy.IsClass = true;
            typeProxy.TypeAttributes = TypeAttributes.Public;
            eventsDeclarationHolder = new CodeTypeDeferredNamespaceDeclarationHolderEvents(idlIntf);
            typeProxy.BaseTypes.Add(genInterfaceName);

            // Interface field.
            CodeMemberField memberProxy = new CodeMemberField(genInterfaceName, proxyName);
            memberProxy.Attributes = MemberAttributes.Private;
            typeProxy.Members.Add(memberProxy); // TODO: Going to need a using or a fully qualified name.

            // Constructor.
            CodeConstructor constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Public;
            // TODO - use the actual interface type rather than a string.
            paramProxy = new CodeParameterDeclarationExpression(genInterfaceName, proxyName);
            constructor.Parameters.Add(paramProxy);
            thisProxyFieldRef = new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), proxyName
            );
            assignProxy = new CodeAssignStatement(thisProxyFieldRef,
                new CodeArgumentReferenceExpression(proxyName));
            constructor.Statements.Add(assignProxy);
            typeProxy.Members.Add(constructor);

            declarationHolder = new CodeTypeIgnoredNamespaceDeclarationHolderParams(idlIntf);
            contextDeclarationHolder = declarationHolder;

            bAddNamespace = false;
        }
コード例 #2
0
		public void TypeReferenceExpressionTest ()
		{
			StringBuilder sb = new StringBuilder();

			using (StringWriter sw = new StringWriter (sb)) {
				CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression();
				CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression();
				parentField.TargetObject = thisRef;
				parentField.FieldName = "Parent";

				CodeBinaryOperatorExpression expression = new CodeBinaryOperatorExpression(
					parentField,
					CodeBinaryOperatorType.IdentityInequality,
					new CodePrimitiveExpression(null));

				Assert.AreEqual ("(Not (Me.Parent) Is Nothing)", Generate (expression, sw), "#1");
				sw.Close ();
			}

			sb = new StringBuilder();
			using (StringWriter sw = new StringWriter (sb)) {
				CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression();
				CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression();
				parentField.TargetObject = thisRef;
				parentField.FieldName = "Parent";

				CodeBinaryOperatorExpression expression = new CodeBinaryOperatorExpression(
					new CodePrimitiveExpression(null),
					CodeBinaryOperatorType.IdentityInequality,
					parentField);

				Assert.AreEqual ("(Not (Me.Parent) Is Nothing)", Generate (expression, sw), "#2");
				sw.Close ();
			}
		}
 internal CodeStatement GetCodeStatement(BaseTemplateCodeDomTreeGenerator generator, CodeExpression ctrlRefExpr)
 {
     CodeExpression expression2;
     if (this.UseSetAttribute)
     {
         CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IAttributeAccessor), ctrlRefExpr), "SetAttribute", new CodeExpression[0]);
         expression.Parameters.Add(new CodePrimitiveExpression(base.Name));
         expression.Parameters.Add(new CodePrimitiveExpression(this.Value));
         return new CodeExpressionStatement(expression);
     }
     CodeExpression right = null;
     if (base.PropertyInfo != null)
     {
         expression2 = CodeDomUtility.BuildPropertyReferenceExpression(ctrlRefExpr, base.Name);
     }
     else
     {
         expression2 = new CodeFieldReferenceExpression(ctrlRefExpr, base.Name);
     }
     if (base.Type == typeof(string))
     {
         right = generator.BuildStringPropertyExpression(this);
     }
     else
     {
         right = CodeDomUtility.GenerateExpressionForValue(base.PropertyInfo, this.Value, base.Type);
     }
     return new CodeAssignStatement(expression2, right);
 }
 public override void ImportClass()
 {
     SoapAddressBinding binding = (base.ImportContext.Port == null) ? null : ((SoapAddressBinding) base.ImportContext.Port.Extensions.Find(typeof(SoapAddressBinding)));
     if (base.ImportContext.Style == ServiceDescriptionImportStyle.Client)
     {
         base.ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(SoapHttpClientProtocol).FullName);
         CodeConstructor ctor = WebCodeGenerator.AddConstructor(base.ImportContext.CodeTypeDeclaration, new string[0], new string[0], null, CodeFlags.IsPublic);
         ctor.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
         bool flag = true;
         if (base.ImportContext is Soap12ProtocolImporter)
         {
             flag = false;
             CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(typeof(SoapProtocolVersion));
             CodeFieldReferenceExpression right = new CodeFieldReferenceExpression(targetObject, Enum.Format(typeof(SoapProtocolVersion), SoapProtocolVersion.Soap12, "G"));
             CodePropertyReferenceExpression left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion");
             CodeAssignStatement statement = new CodeAssignStatement(left, right);
             ctor.Statements.Add(statement);
         }
         ServiceDescription serviceDescription = base.ImportContext.Binding.ServiceDescription;
         string url = (binding != null) ? binding.Location : null;
         string appSettingUrlKey = serviceDescription.AppSettingUrlKey;
         string appSettingBaseUrl = serviceDescription.AppSettingBaseUrl;
         ProtocolImporterUtil.GenerateConstructorStatements(ctor, url, appSettingUrlKey, appSettingBaseUrl, flag && !base.ImportContext.IsEncodedBinding);
     }
     else if (base.ImportContext.Style == ServiceDescriptionImportStyle.Server)
     {
         base.ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(WebService).FullName);
     }
 }
 internal static CodeMemberMethod AddAsyncMethod(CodeTypeDeclaration codeClass, string methodName, string[] parameterTypeNames, string[] parameterNames, string callbackMember, string callbackName, string userState)
 {
     CodeMemberMethod method = AddMethod(codeClass, methodName, new CodeFlags[parameterNames.Length], parameterTypeNames, parameterNames, typeof(void).FullName, null, CodeFlags.IsPublic);
     method.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), methodName, new CodeExpression[0]);
     for (int i = 0; i < parameterNames.Length; i++)
     {
         expression.Parameters.Add(new CodeArgumentReferenceExpression(parameterNames[i]));
     }
     expression.Parameters.Add(new CodePrimitiveExpression(null));
     method.Statements.Add(expression);
     method = AddMethod(codeClass, methodName, new CodeFlags[parameterNames.Length], parameterTypeNames, parameterNames, typeof(void).FullName, null, CodeFlags.IsPublic);
     method.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userState));
     CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), callbackMember);
     CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
     CodeDelegateCreateExpression right = new CodeDelegateCreateExpression {
         DelegateType = new CodeTypeReference(typeof(SendOrPostCallback)),
         TargetObject = new CodeThisReferenceExpression(),
         MethodName = callbackName
     };
     CodeStatement[] trueStatements = new CodeStatement[] { new CodeAssignStatement(left, right) };
     method.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[0]));
     return method;
 }
コード例 #6
0
 public override void ImportClass() {
     // grab this here so it gets marked "handled" for both client and server
     SoapAddressBinding soapAddress = ImportContext.Port == null ? null : (SoapAddressBinding)ImportContext.Port.Extensions.Find(typeof(SoapAddressBinding));
     if (ImportContext.Style == ServiceDescriptionImportStyle.Client) {
         ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(SoapHttpClientProtocol).FullName);                                
         CodeConstructor ctor = WebCodeGenerator.AddConstructor(ImportContext.CodeTypeDeclaration, new string[0], new string[0], null, CodeFlags.IsPublic);
         ctor.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));
         bool soap11 = true;
         if (ImportContext is Soap12ProtocolImporter) {
             soap11 = false;
             // add version code
             CodeTypeReferenceExpression versionEnumTypeReference = new CodeTypeReferenceExpression(typeof(SoapProtocolVersion));
             CodeFieldReferenceExpression versionEnumFieldReference = new CodeFieldReferenceExpression(versionEnumTypeReference, Enum.Format(typeof(SoapProtocolVersion), SoapProtocolVersion.Soap12, "G"));
             CodePropertyReferenceExpression versionPropertyReference = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion");
             CodeAssignStatement assignVersionStatement = new CodeAssignStatement(versionPropertyReference, versionEnumFieldReference);
             ctor.Statements.Add(assignVersionStatement);
         }
         ServiceDescription serviceDescription = ImportContext.Binding.ServiceDescription;
         string url = (soapAddress != null) ? soapAddress.Location : null;
         string urlKey = serviceDescription.AppSettingUrlKey;
         string baseUrl = serviceDescription.AppSettingBaseUrl;
         ProtocolImporterUtil.GenerateConstructorStatements(ctor, url, urlKey, baseUrl, soap11 && !ImportContext.IsEncodedBinding);
     }
     else if (ImportContext.Style == ServiceDescriptionImportStyle.Server) {
         ImportContext.CodeTypeDeclaration.BaseTypes.Add(typeof(WebService).FullName);
     }
 }
コード例 #7
0
        /// <summary>
        /// Compose additional items of the test TearDown method.
        /// </summary>
        /// <param name="teardownMethod">A reference to the TearDown method of the test.</param>
        /// <param name="testObjectMemberField">The member field of the object under test.</param>
        /// <param name="testObjectName">The name of the object under test.</param>
        /// <param name="testObjectType">Type of the object under test(OuT).</param>
        protected override void ComposeTestTearDownMethod(
            CodeMemberMethod teardownMethod,
            CodeMemberField testObjectMemberField,
            string testObjectName,
            Type testObjectType)
        {
            /*var invokeExpression = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Assert"),
                "AreEqual",
                //new CodePrimitiveExpression("expected")
                new CodeFieldReferenceExpression(testObjectMemberField, "bla")
                , new CodeVariableReferenceExpression("actual"));*/
            var fieldRef1 =
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), testObjectMemberField.Name);

            // var objectCreate1 = new CodeObjectCreateExpression(testObjectName, new CodeExpression[] { });
            var as1 =
                new CodeAssignStatement(fieldRef1, new CodePrimitiveExpression(null));

            // new CodeAssignStatement(fieldRef1, objectCreate1);

            // Creates a statement using a code expression.
            // var expressionStatement = new CodeExpressionStatement(fieldRef1);
            teardownMethod.Statements.Add(as1);
            base.ComposeTestTearDownMethod(teardownMethod, testObjectMemberField, testObjectName, testObjectType);
        }
コード例 #8
0
		CodeMemberMethod CreateMethod()
		{
			CodeMemberMethod method = new CodeMemberMethod();
			
			// BeginInit method call.
			CodeExpressionStatement statement = new CodeExpressionStatement();
			CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression();
			statement.Expression = methodInvoke;
			
			CodeMethodReferenceExpression methodRef = new CodeMethodReferenceExpression();
			methodRef.MethodName = "BeginInit";
			
			CodeCastExpression cast = new CodeCastExpression();
			cast.TargetType = new CodeTypeReference();
			cast.TargetType.BaseType = "System.ComponentModel.ISupportInitialize";
			
			CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression();
			fieldRef.FieldName = "pictureBox1";
			fieldRef.TargetObject = new CodeThisReferenceExpression();
			cast.Expression = fieldRef;

			methodRef.TargetObject = cast;
			methodInvoke.Method = methodRef;

			method.Statements.Add(statement);
			return method;
		}
コード例 #9
0
        /// <summary>
        /// Add a constructor to the class.
        /// </summary>
        public void AddConstructor()
        {
            // Declare the constructor
            CodeConstructor constructor = new CodeConstructor();
            constructor.Attributes =
                MemberAttributes.Public | MemberAttributes.Final;

            // Add parameters.
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(
                typeof(System.Double), "width"));
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(
                typeof(System.Double), "height"));

            // Add field initialization logic
            CodeFieldReferenceExpression widthReference =
                new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), "widthValue");
            constructor.Statements.Add(new CodeAssignStatement(widthReference,
                new CodeArgumentReferenceExpression("width")));
            CodeFieldReferenceExpression heightReference =
                new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), "heightValue");
            constructor.Statements.Add(new CodeAssignStatement(heightReference,
                new CodeArgumentReferenceExpression("height")));
            targetClass.Members.Add(constructor);
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression;
     CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
     RootContext context = manager.Context[typeof(RootContext)] as RootContext;
     CodeStatementCollection statements = new CodeStatementCollection();
     if ((declaration != null) && (context != null))
     {
         CodeMemberField field = new CodeMemberField(typeof(IContainer), "components") {
             Attributes = MemberAttributes.Private
         };
         declaration.Members.Add(field);
         expression = new CodeFieldReferenceExpression(context.Expression, "components");
     }
     else
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(IContainer), "components");
         statements.Add(statement);
         expression = new CodeVariableReferenceExpression("components");
     }
     base.SetExpression(manager, value, expression);
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(typeof(Container), new CodeExpression[0]);
     CodeAssignStatement statement2 = new CodeAssignStatement(expression, right);
     statement2.UserData["IContainer"] = "IContainer";
     statements.Add(statement2);
     return statements;
 }
コード例 #11
0
 private CodeAssignStatement AssignValueTo(Expression<Func<IRule, string>> func, string value)
 {
     var name = Name.Of(func);
     var property = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name);
     var assignment = new CodeAssignStatement(property, _(value));
     return assignment;
 }
コード例 #12
0
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeFieldReferenceExpression cfre = new CodeFieldReferenceExpression ();
			Assert.AreEqual (String.Empty, cfre.FieldName, "FieldName");
			cfre.FieldName = "mono";
			Assert.IsNull (cfre.TargetObject, "TargetObject");
			cfre.TargetObject = new CodeExpression ();
		}
コード例 #13
0
 public static CodeFieldReferenceExpression Clone(this CodeFieldReferenceExpression expression)
 {
     if (expression == null) return null;
     CodeFieldReferenceExpression e = new CodeFieldReferenceExpression();
     e.FieldName = expression.FieldName;
     e.TargetObject = expression.TargetObject.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
コード例 #14
0
 public CodeStatementCollection DefaultInvocationMethod(Activity activity)
 {
     var activityServiceReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), VariableHelper.ToVariableName(activity.Name));
     var methodInvocation = new CodeMethodInvokeExpression(activityServiceReference, "Execute", new CodeExpression[] { });
     var invocationCodeCollection = new CodeStatementCollection();
     invocationCodeCollection.AddRange(LogActivity(activity));
     invocationCodeCollection.Add(methodInvocation);
     return invocationCodeCollection;
 }
コード例 #15
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeExpression target = new CodeExpression ();
			CodeFieldReferenceExpression cfre = new CodeFieldReferenceExpression (target, "mono");
			Assert.AreEqual ("mono", cfre.FieldName, "FieldName");
			cfre.FieldName = String.Empty;
			Assert.AreSame (target, cfre.TargetObject, "TargetObject");
			cfre.TargetObject = new CodeExpression ();
		}
コード例 #16
0
        private CodeCompileUnit GeneraCodigo()
        {
            //Unidad de Compilación (ensamblado)
            var cu = new CodeCompileUnit();
            cu.ReferencedAssemblies.Add("System.dll");//Ensamblados que enlaza (aunque este debería estar por defecto)
            //Espacio de nombres
            var n = new CodeNamespace("EjemploGeneracionCodigo1");
            cu.Namespaces.Add(n);
            n.Imports.Add(new CodeNamespaceImport("System"));//Espacios de nombres que utiliza este namespace para compilar
            //Clase
            var c = new CodeTypeDeclaration("ClaseGenerada");
            n.Types.Add(c);
            c.BaseTypes.Add(new CodeTypeReference(typeof(System.Timers.Timer)));//Su clase padre
            c.IsPartial = true;

            //Atributo de la clase
            CodeMemberField mf = new CodeMemberField(typeof(string),"_atributo");
            c.Members.Add(mf);
            //Propiedad de la clase
            CodeMemberProperty cp = new CodeMemberProperty();
            c.Members.Add(cp);
            cp.Attributes = MemberAttributes.Public | MemberAttributes.Final;//lo de Final para que no sea virtual (por defecto si es público es virtual)
            cp.Type = new CodeTypeReference(typeof(string));
            cp.Name = "atributo";
            CodeFieldReferenceExpression cfre = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_atributo");
            CodeMethodReturnStatement mrs = new CodeMethodReturnStatement(cfre);
            cp.GetStatements.Add(mrs);
            //Metodo de la clase
            CodeMemberMethod cmm = new CodeMemberMethod();
            c.Members.Add(cmm);
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.Name = "Metodo1";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            CodeParameterDeclarationExpression pde = new CodeParameterDeclarationExpression(typeof(int),"enteroDeEntrada");
            cmm.Parameters.Add(pde);
            pde = new CodeParameterDeclarationExpression(typeof(string),"cadenaDeEntrada");
            cmm.Parameters.Add(pde);
            //Declaración de variable
            CodeVariableDeclarationStatement vds = new CodeVariableDeclarationStatement(typeof(string),"aux",new CodePrimitiveExpression("Prueba1") );
            cmm.Statements.Add(vds);
            //Llamar a método arbitrario
            //variable a llamar y método
            CodeMethodReferenceExpression  ctr = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("Console"),"WriteLine");
            //Llamada en sí con sus parámetros
            CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression( ctr, new CodeExpression[] {new CodePrimitiveExpression("Hola mundo")} );
            cmm.Statements.Add(invoke1);

            //Código a pelo. Ojo no se puede generar, por ejemplo, un foreach.
            cmm.Statements.Add(new CodeSnippetStatement("foreach(string s in cadenas){"));
            cmm.Statements.Add(new CodeSnippetStatement("Console.WriteLine(s);"));
            cmm.Statements.Add(new CodeSnippetStatement("}"));
            mrs = new CodeMethodReturnStatement(new CodePrimitiveExpression(42));
            cmm.Statements.Add(mrs);

            return cu;
        }
コード例 #17
0
 public TypescriptFieldReferenceExpression(
     IExpressionFactory expressionFactory,
     CodeFieldReferenceExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptFieldReferenceExpression Created");
 }
コード例 #18
0
        public CodeStatementCollection GenerateCodeInvocation( AssignActivity assignActivity)
        {
            var invocationCodeCollection = new CodeStatementCollection();
            invocationCodeCollection.AddRange(DefaultActivityBuilder.LogActivity(assignActivity));

            invocationCodeCollection.AddRange(this.xslBuilder.Build(assignActivity.InputBindings));

            var variableToAssignReference = new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), VariableHelper.ToVariableName(assignActivity.VariableName));
            var codeInvocation = new CodeAssignStatement (variableToAssignReference, new CodeVariableReferenceExpression(VariableHelper.ToVariableName(assignActivity.VariableName)));
            invocationCodeCollection.Add(codeInvocation);
            return invocationCodeCollection;
        }
コード例 #19
0
        /// <summary>
        /// Generates code for value
        /// </summary>
        /// <param name="parentClass">The parent class.</param>
        /// <param name="method">The method.</param>
        /// <param name="value">The value.</param>
        /// <param name="baseName">Name of the base.</param>
        /// <param name="dictionary">The dictionary.</param>
        /// <returns></returns>
        public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null)
        {
            CodeExpression valueExpression = null;
            if (value != null)
            {
                FontWeight fontWeight = (FontWeight)value;
                CodeTypeReferenceExpression typeReference = new CodeTypeReferenceExpression("FontStyle");
                valueExpression = new CodeFieldReferenceExpression(typeReference, fontWeight.ToString());
            }

            return valueExpression;
        }
コード例 #20
0
        /// <summary>
        /// Formats an enum value to a code expression.
        /// </summary>
        /// <param name="value">The value to be formatted</param>
        /// <returns>A code expression representing one single enumeration value, or a collection of two or more values concatenated with the <c>Or</c> operator.</returns>
        public static CodeExpression FormatEnumValue(Enum value)
        {
            Type valueType = value.GetType();
            bool isFlags = valueType.HasCustomAttribute(typeof(FlagsAttribute));
            
            long enumValue = Convert.ToInt64(value);

            if (isFlags && enumValue > 0)
            {
                CodeExpression returnExpression = null;

                foreach (FieldInfo field in valueType.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        long fieldValue = Convert.ToInt64(field.GetValue(null));

                        if ((enumValue & fieldValue) == fieldValue)
                        {
                            CodeFieldReferenceExpression fieldExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(valueType), field.Name);

                            if (returnExpression == null)
                                returnExpression = fieldExpression;
                            else
                                returnExpression = new CodeBinaryOperatorExpression(returnExpression, CodeBinaryOperatorType.BitwiseOr, fieldExpression);

                            enumValue ^= fieldValue;
                        }
                    }
                }

                if (enumValue == 0)
                    return returnExpression;
                else
                    return new CodeCastExpression(valueType, new CodePrimitiveExpression(Convert.ToInt64(value)));
            }
            else
            {
                foreach (FieldInfo field in valueType.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        long fieldValue = Convert.ToInt64(field.GetValue(null));
                        if (fieldValue == enumValue)
                            return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(valueType), field.Name);
                    }
                }
            }

            return new CodeCastExpression(valueType, new CodePrimitiveExpression(Convert.ToInt64(value)));
        }
コード例 #21
0
		public void GenerateBuildCode (GeneratorContext ctx, CodeFieldReferenceExpression uiManager)
		{
			StringBuilder sb = new StringBuilder ();
			sb.Append ("<ui>");
			GenerateUiString (sb);
			sb.Append ("</ui>");
			
			CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression (
				uiManager,
				"AddUiFromString",
				new CodePrimitiveExpression (sb.ToString ())
			);
			ctx.Statements.Add (exp);
		}
コード例 #22
0
 protected override void Constructor(CodeTypeDeclaration typeProxy, CodeTypeReference typerefDbusInterface)
 {
     CodeConstructor constructor = new CodeConstructor();
     constructor.Attributes = MemberAttributes.Public;
     CodeParameterDeclarationExpression paramProxy = new CodeParameterDeclarationExpression(typerefDbusInterface, CodeBuilderCommon.targetName);
     constructor.Parameters.Add(paramProxy);
     CodeFieldReferenceExpression thisProxyFieldRef = new CodeFieldReferenceExpression(
         new CodeThisReferenceExpression(), CodeBuilderCommon.targetName
     );
     CodeAssignStatement assignProxy = new CodeAssignStatement(thisProxyFieldRef,
         new CodeArgumentReferenceExpression(CodeBuilderCommon.targetName));
     constructor.Statements.Add(assignProxy);
     typeProxy.Members.Add(constructor);
 }
コード例 #23
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="member"></param>
        /// <param name="inner"></param>
        /// <param name="attrs"></param>
        /// <returns></returns>
        public CodeTypeMember CreateMember(MemberInfo member, CodeFieldReferenceExpression inner, MemberAttributes attrs)
        {
            Debug.Assert(member is MethodInfo);
            MethodInfo method = member as MethodInfo;
            CodeMemberMethod codeMethod = new CodeMemberMethod();

            codeMethod.Name = method.Name;
            codeMethod.ReturnType = new CodeTypeReference(method.ReturnType);
            codeMethod.Attributes = attrs;

            // try
            CodeTryCatchFinallyStatement tryCode = new CodeTryCatchFinallyStatement();

            // decleare parameters
            List<CodeArgumentReferenceExpression> codeParamiteRefrs = new List<CodeArgumentReferenceExpression>();

            foreach (ParameterInfo codeParameter in method.GetParameters()) {
                CodeParameterDeclarationExpression codeParameterDeclare = new CodeParameterDeclarationExpression(codeParameter.ParameterType, codeParameter.Name);
                codeMethod.Parameters.Add(codeParameterDeclare);
                codeParamiteRefrs.Add(new CodeArgumentReferenceExpression(codeParameter.Name));
            }

            // invoke
            CodeMethodInvokeExpression invokeMethod = new CodeMethodInvokeExpression(
                inner, method.Name, codeParamiteRefrs.ToArray());
            if (method.ReturnType.Name.ToLower() == "void") {
                tryCode.TryStatements.Add(invokeMethod);
            } else {
                CodeVariableDeclarationStatement var = new CodeVariableDeclarationStatement(method.ReturnType, "returnObject", invokeMethod);
                //CodeAssignStatement assign = new CodeAssignStatement(var, invokeMethod);
                tryCode.TryStatements.Add(var);

                CodeCommentStatement todo = new CodeCommentStatement("TODO: your code", false);
                tryCode.TryStatements.Add(todo);

                CodeVariableReferenceExpression varRef = new CodeVariableReferenceExpression("returnObject");
                CodeMethodReturnStatement codeReturn = new CodeMethodReturnStatement(varRef);
                tryCode.TryStatements.Add(codeReturn);
            }

            // catch
            CodeTypeReference codeTypeRef = new CodeTypeReference(typeof(Exception));
            CodeCatchClause catchClause = new CodeCatchClause("ex", codeTypeRef);
            catchClause.Statements.Add(new CodeThrowExceptionStatement());
            tryCode.CatchClauses.Add(catchClause);

            codeMethod.Statements.Add(tryCode);
            return codeMethod;
        }
コード例 #24
0
        public static CodeStatementCollection LogActivity(Activity activity)
        {
            var activityServiceReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), VariableHelper.ToVariableName("logger"));
            var methodInvocation = new CodeMethodInvokeExpression(
                activityServiceReference,
                "Info",
                new CodeExpression[]
                {
                    new CodePrimitiveExpression("Start Activity: " + activity.Name + " of type: " + activity.Type)
                });

            var logCallStatements = new CodeStatementCollection();
            logCallStatements.Add(methodInvocation);
            return logCallStatements;
        }
コード例 #25
0
ファイル: CodeMethodComposer.cs プロジェクト: Jedzia/NStub
        /// <summary>
        /// Creates a reference to a collection based member field and initializes it with a new instance of the
        /// specified parameter type and adds a collection item to it.
        /// Sample values are used as the initializing expression.
        /// </summary>
        /// <param name="memberCollectionField">Name of the referenced collection field.</param>
        /// <param name="collectionInitializers">Defines the types of the new object list.</param>
        /// <returns>
        /// An assignment statement for the specified collection member field.
        /// </returns>
        /// <remarks>
        /// With a custom Type, this method produces a statement with a initializer like:
        /// <code>this.paths = new[] { pathsItem };</code>.
        /// where the item is defined like:
        /// <code>this.pathsItem = new PathItemType();</code>.
        /// myType of type System.Type:
        /// <code>this.pathsItem = "An Item";</code>.
        /// </remarks>
        public static CodeAssignStatement CreateAndInitializeCollectionField(
            //Type type,
            string memberCollectionField,
            params string[] collectionInitializers)
        {
            /*if (type == typeof(object))
            {

            }*/
            var fieldRef1 = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), memberCollectionField);
            //CodeExpression assignExpr = CreateExpressionByType(type, memberCollectionField);
            var para = collectionInitializers.Aggregate((x, y) => x += "," + y);
            CodeExpression assignExpr = new CodeSnippetExpression("new[] { " + para + " }");

            return new CodeAssignStatement(fieldRef1, assignExpr);
        }
コード例 #26
0
 void CreateImportFor(bool isNestedSrc, IEnumerable<TypeDefinition> types, CodeMemberMethod method)
 {
     foreach (var type in types) {
         // If the library was written in F#, those resource ID classes are not nested but rather combined with '_'.
         var srcClassRef = new CodeTypeReferenceExpression (
             new CodeTypeReference (primary_name + (isNestedSrc ? '.' : '_') + type.Name, CodeTypeReferenceOptions.GlobalReference));
         // destination language may not support nested types, but they should take care of such types by themselves.
         var dstClassRef = new CodeTypeReferenceExpression (
             new CodeTypeReference (type.FullName.Replace ('/', '.'), CodeTypeReferenceOptions.GlobalReference));
         foreach (var field in type.Fields) {
             var dstField = new CodeFieldReferenceExpression (dstClassRef, field.Name);
             var srcField = new CodeFieldReferenceExpression (srcClassRef, field.Name);
             // This simply assigns field regardless of whether it is int or int[].
             method.Statements.Add (new CodeAssignStatement (dstField, srcField));
         }
     }
 }
コード例 #27
0
 public CodeMemberProperty CreateProperty(string type, string propertyName)
 {
     var codeMemberProperty = new CodeMemberProperty
     {
         Name = propertyName,
         HasGet = true,
         HasSet = true,
         Attributes = MemberAttributes.Public,
         Type = new CodeTypeReference(type)
     };
     var fieldName = propertyName.MakeFirstCharLowerCase();
     var codeFieldReferenceExpression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
     var returnStatement = new CodeMethodReturnStatement(codeFieldReferenceExpression);
     codeMemberProperty.GetStatements.Add(returnStatement);
     var assignStatement = new CodeAssignStatement(codeFieldReferenceExpression, new CodePropertySetValueReferenceExpression());
     codeMemberProperty.SetStatements.Add(assignStatement);
     return codeMemberProperty;
 }
コード例 #28
0
        public static void GenerateConstructor(CodeTypeDeclaration classDecl)
        {
            CodeConstructor constructorMember = new CodeConstructor() ;

            constructorMember.Attributes = MemberAttributes.Public;

            CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference("IContext"), "context");
            constructorMember.Parameters.Add(parameter);

            CodeThisReferenceExpression thisExp = new CodeThisReferenceExpression();
            CodeFieldReferenceExpression ctxFieldExp = new CodeFieldReferenceExpression(thisExp, "context");

            CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression("context");
            CodeAssignStatement assignStatement = new CodeAssignStatement(ctxFieldExp, argExp);
            constructorMember.Statements.Add(assignStatement);

            classDecl.Members.Add(constructorMember);
        }
コード例 #29
0
        private CodeStatement BuildControlSkinAssignmentStatement(
            ControlBuilder builder, string skinID) {

            Type controlType = builder.ControlType;

            string keyVarName = GetMethodNameForBuilder(buildMethodPrefix, builder) + "_skinKey";

            // e.g.
            // private static object __BuildControl__control3_skinKey = PageTheme.CreateSkinKey(typeof({controlType}), {skinID});
            CodeMemberField field = new CodeMemberField(typeof(object), keyVarName);
            field.Attributes = MemberAttributes.Static | MemberAttributes.Private;
            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
            cmie.Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(PageTheme)), "CreateSkinKey");
            cmie.Parameters.Add(new CodeTypeOfExpression(controlType));
            cmie.Parameters.Add(new CodePrimitiveExpression(skinID));
            field.InitExpression = cmie;
            _sourceDataClass.Members.Add(field);

            // e.g. this.__namedControlSkins[keyVarName] =
            //          new System.Web.UI.ControlSkin(typeof(System.Web.UI.WebControls.Label),
            //          new System.Web.UI.ControlSkinDelegate(this.__BuildControl__control3));
            CodeFieldReferenceExpression varExpr = new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(),
                _controlSkinsVarName);

            CodeIndexerExpression indexerExpr = new CodeIndexerExpression(
                varExpr,
                new CodeExpression[] {
                    new CodeVariableReferenceExpression(keyVarName)
                }
            );

            CodeDelegateCreateExpression del = new CodeDelegateCreateExpression(
                                                            _controlSkinDelegateType,
                                                            new CodeThisReferenceExpression(),
                                                            GetMethodNameForBuilder(buildMethodPrefix, builder));
            CodeObjectCreateExpression valueExpr = new CodeObjectCreateExpression(_controlSkinType);
            valueExpr.Parameters.Add(new CodeTypeOfExpression(controlType));
            valueExpr.Parameters.Add(del);

            return new CodeAssignStatement(indexerExpr, valueExpr);
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: jaggedsoft/aesirtk
 private static void GenerateProperty(CodeTypeDeclaration codeType, string type, string name,
     out CodeMemberProperty codeProperty, CodeExpression defaultValue)
 {
     codeProperty = new CodeMemberProperty();
     CodeMemberField codeField = new CodeMemberField();
     codeField.Name = ToPrivateName(name);
     codeProperty.Name = ToPublicName(name);
     CodeTypeReference codeFieldType = new CodeTypeReference(type);
     codeProperty.Type = codeField.Type = codeFieldType;
     if(defaultValue != null) codeField.InitExpression = defaultValue;
     CodeFieldReferenceExpression codeFieldReference = new CodeFieldReferenceExpression(
         new CodeThisReferenceExpression(), codeField.Name);
     codeProperty.GetStatements.Add(new CodeMethodReturnStatement(codeFieldReference));
     codeProperty.SetStatements.Add(new CodeAssignStatement(codeFieldReference,
         new CodePropertySetValueReferenceExpression()));
     codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
     codeField.Attributes = MemberAttributes.Private;
     codeType.Members.Add(codeProperty);
     codeType.Members.Add(codeField);
 }
コード例 #31
0
        //System.CodeDom.CodeVariableDeclarationStatement mVecVariableDeclaration = new System.CodeDom.CodeVariableDeclarationStatement();
        public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Method context)
        {
            var strValueName = GCode_GetValueName(null, context);

            if (!context.Method.Statements.Contains(mVarDec))
            {
                mVarDec = new CodeAssignStatement(new CodeSnippetExpression(mValueType.FullName + " " + strValueName), CodeGenerateSystem.Program.GetDefaultValueExpressionFromType(mValueType));//, paramCodeName, CodeGenerateSystem.Program.GetDefaultValueExpressionFromType(ParamType));
                context.Method.Statements.Insert(0, mVarDec);
            }
            if (mCtrlvalue_VectorIn.HasLink)
            {
                if (!mCtrlvalue_VectorIn.GetLinkedObject(0, true).IsOnlyReturnValue)
                {
                    await mCtrlvalue_VectorIn.GetLinkedObject(0, true).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, mCtrlvalue_VectorIn.GetLinkedPinControl(0, true), context);
                }


                if (!codeStatementCollection.Contains(mAssignCode))
                {
                    mAssignCode = new CodeAssignStatement(new System.CodeDom.CodeVariableReferenceExpression(strValueName), mCtrlvalue_VectorIn.GetLinkedObject(0, true).GCode_CodeDom_GetValue(mCtrlvalue_VectorIn.GetLinkedPinControl(0, true), context));
                    codeStatementCollection.Add(mAssignCode);
                }
            }
            else
            {
                if (!codeStatementCollection.Contains(mAssignCode))
                {
                    mAssignCode      = new CodeAssignStatement();
                    mAssignCode.Left = new System.CodeDom.CodeVariableReferenceExpression(strValueName);
                    var paramExp = new System.CodeDom.CodeExpression[mLinkInDic.Count];
                    var param    = CSParam as AixConstructionParams;
                    if (param != null)
                    {
                        for (int i = 0; i < mLinkInDic.Count; i++)
                        {
                            paramExp[i] = new System.CodeDom.CodePrimitiveExpression(param.Value[i]);
                        }
                    }
                    mAssignCode.Right = new CodeObjectCreateExpression(mValueType, paramExp);
                    codeStatementCollection.Add(mAssignCode);
                }
            }

            foreach (var data in mLinkInDic)
            {
                var linkOI = data.Element;
                if (linkOI.HasLink)
                {
                    if (!linkOI.GetLinkedObject(0, true).IsOnlyReturnValue)
                    {
                        await linkOI.GetLinkedObject(0, true).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, linkOI.GetLinkedPinControl(0, true), context);
                    }

                    var fieldRef = new System.CodeDom.CodeFieldReferenceExpression();
                    fieldRef.TargetObject = new CodeVariableReferenceExpression(strValueName);
                    fieldRef.FieldName    = data.KeyName;
                    var statValAss = new System.CodeDom.CodeAssignStatement();
                    statValAss.Left  = fieldRef;
                    statValAss.Right = new CodeGenerateSystem.CodeDom.CodeCastExpression(typeof(float), linkOI.GetLinkedObject(0, true).GCode_CodeDom_GetValue(linkOI.GetLinkedPinControl(0, true), context));
                    codeStatementCollection.Add(statValAss);
                }
            }
        }
コード例 #32
0
 protected override void GenerateFieldReferenceExpression(System.CodeDom.CodeFieldReferenceExpression e)
 {
     GenerateExpression(e.TargetObject);
     Output.Write(".");
     Output.Write(e.FieldName);
 }