Exemplo n.º 1
0
        private void EmitReturnStatement(CodeMethodReturnStatement Return)
        {
            Depth++;

            Debug("Emitting return statement");

            if (Method.ReturnType != typeof(void))
            {
                Type Top;
                if (Return.Expression == null)
                {
                    // Default to an empty string if this method expects a return value
                    Generator.Emit(OpCodes.Ldstr, "");
                    Top = typeof(string);
                }
                else Top = EmitExpression(Return.Expression);

                if (Top != null)
                    ForceTopStack(Top, Method.ReturnType);
            }
            else if (Return.Expression != null)
                throw new CompileException(Return, "Can not return value from void method " + Method.Name);

            Generator.Emit(OpCodes.Ret);

            Depth--;
        }
Exemplo n.º 2
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeExpression expression = new CodeExpression ();
			CodeMethodReturnStatement cmrs = new CodeMethodReturnStatement (expression);
			Assert.AreSame (expression, cmrs.Expression, "Expression");
			cmrs.Expression = new CodeExpression ();
		}
Exemplo n.º 3
0
 private CodeStatement GenerateCallStatementC2J(GMethod method, CodeExpression invokeExpression)
 {
     CodeStatement call;
     if (method.IsConstructor || method.IsVoid)
     {
         call = new CodeExpressionStatement(invokeExpression);
     }
     else
     {
         if (method.ReturnType.IsPrimitive)
         {
             if (method.ReturnType.JVMSubst != null)
             {
                 invokeExpression = new CodeCastExpression(method.ReturnType.CLRReference, invokeExpression);
             }
             call = new CodeMethodReturnStatement(invokeExpression);
         }
         else
         {
             CodeMethodInvokeExpression conversionExpression = CreateConversionExpressionJ2CParam(method.ReturnType,
                                                                                             invokeExpression);
             call = new CodeMethodReturnStatement(conversionExpression);
         }
     }
     return call;
 }
 private void AddPropertyGroup(AssemblyBuilder assemblyBuilder, string groupName, string propertyNames, Hashtable properties, CodeTypeDeclaration type, CodeNamespace ns)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Name = groupName,
         Attributes = MemberAttributes.Public,
         HasGet = true,
         Type = new CodeTypeReference("ProfileGroup" + groupName)
     };
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = { TargetObject = new CodeThisReferenceExpression(), MethodName = "GetProfileGroup" }
     };
     expression.Parameters.Add(new CodePrimitiveExpression(property.Name));
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(new CodeCastExpression(property.Type, expression));
     property.GetStatements.Add(statement);
     type.Members.Add(property);
     CodeTypeDeclaration declaration = new CodeTypeDeclaration {
         Name = "ProfileGroup" + groupName
     };
     declaration.BaseTypes.Add(new CodeTypeReference(typeof(ProfileGroupBase)));
     foreach (string str in propertyNames.Split(new char[] { ';' }))
     {
         this.CreateCodeForProperty(assemblyBuilder, declaration, (ProfileNameTypeStruct) properties[str]);
     }
     ns.Types.Add(declaration);
 }
        /// <summary>
        /// Generates the <c>IRequestProvider.CreateRequest()</c> method.
        /// </summary>
        /// <returns><c>CodeMemberMethod</c> describing the method.</returns>
        internal CodeMemberMethod GenerateCreateRequestMethod()
        {
            var method = new CodeMemberMethod();

            method.Name = CreateRequestMethodName;
            method.ImplementationTypes.Add(typeof(IRequestProvider));
            method.ReturnType = new CodeTypeReference(typeof(IRequest));
            method.Attributes = MemberAttributes.Public;
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "resource"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "method"));

            //Google.Apis.Requests.Request request = this.genericService.CreateRequest(resource, method);
            method.Statements.Add(CreateRequestLocalVar());

            // if (string.IsNullOrEmpty(APIKey) == false)
            //     request = request.WithAPIKey(APIKey)
            method.Statements.Add(CreateWithApiKey());

            // return request.WithAuthentication(authenticator);
            var statement =
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeVariableReferenceExpression("request"), "WithAuthentication"),
                    new CodeVariableReferenceExpression(ServiceClassGenerator.AuthenticatorName));
            var returnStatment = new CodeMethodReturnStatement(statement);

            method.Statements.Add(returnStatment);
            return method;
        }
 private void AddMemberOverride(string name, Type type, CodeExpression expr) {
     CodeMemberProperty member = new CodeMemberProperty();
     member.Name = name;
     member.Attributes = MemberAttributes.Override | MemberAttributes.Family;
     member.Type = new CodeTypeReference(type.FullName);
     CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(expr);
     member.GetStatements.Add(returnStmt);
     _sourceDataClass.Members.Add(member);
 }
Exemplo n.º 7
0
		public override void Compile(IEnumerable<IColumInfoModel> columnInfos, Stream to = null)
		{
			if (string.IsNullOrEmpty(TableName))
			{
				TableName = TargetCsName;
			}

			var spAttribute = new CodeAttributeDeclaration(typeof(StoredProcedureAttribute).Name);
			_base.CustomAttributes.Add(spAttribute);

			if (_base.TypeParameters.Count == 0)
			{
				//_base.TypeParameters.Add(new CodeTypeParameter(typeof ().FullName));
			}

			//Create Caller
			var createFactoryMethod = new CodeMemberMethod();
			createFactoryMethod.Name = "Invoke" + TableName;
			createFactoryMethod.ReturnType = new CodeTypeReference(typeof(QueryFactoryResult));
			createFactoryMethod.CustomAttributes.Add(
				new CodeAttributeDeclaration(typeof(SelectFactoryMethodAttribute).FullName));

			//Create the Params
			string query = "EXEC " + TableName;

			var nameOfListOfParamater = "paramaters";
			var listOfParams = new CodeObjectCreateExpression(typeof(List<IQueryParameter>));
			var listOfParamscreator = new CodeVariableDeclarationStatement(typeof(List<IQueryParameter>), nameOfListOfParamater, listOfParams);
			createFactoryMethod.Statements.Add(listOfParamscreator);
			int i = 0;
			foreach (var item in _base.Members)
			{
				if (item is CodeMemberProperty)
				{
					var variable = item as CodeMemberProperty;
					var paramName = "param" + i++;
					query += " @" + paramName + " ";
					var createParams = new CodeObjectCreateExpression(typeof(QueryParameter),
						new CodePrimitiveExpression(paramName),
						new CodeVariableReferenceExpression(variable.Name));
					var addToList =
						new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(nameOfListOfParamater),
							"Add", createParams);

					createFactoryMethod.Statements.Add(addToList);
				}
			}

			//Finaly create the instance
			var createFactory = new CodeObjectCreateExpression(typeof(QueryFactoryResult),
				new CodePrimitiveExpression(query),
				new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(nameOfListOfParamater), "ToArray"));
			var queryFactoryVariable = new CodeMethodReturnStatement(createFactory);

			createFactoryMethod.Statements.Add(queryFactoryVariable);
			_base.Members.Add(createFactoryMethod);
		}
        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;
        }
Exemplo n.º 9
0
        // Generate a codedom return statement.
        public static CodeStatement Emit(Return r)
        {
            var codeMethodReturnStatement = new CodeMethodReturnStatement();

            // Attach the expression to return, if any.
            if(r.ChildExpressions.Count > 0)
                codeMethodReturnStatement.Expression = CodeDomEmitter.EmitCodeExpression(r.ChildExpressions[0]);

            return codeMethodReturnStatement;
        }
 internal void AddFactoryMethod(string typeToCreate)
 {
     CodeMemberMethod method = new CodeMemberMethod {
         Name = GetCreateMethodNameForType(typeToCreate),
         ReturnType = new CodeTypeReference(typeof(object)),
         Attributes = MemberAttributes.Static
     };
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(new CodeObjectCreateExpression(typeToCreate, new CodeExpression[0]));
     method.Statements.Add(statement);
     this._factoryClass.Members.Add(method);
 }
 public static CodeMethodReturnStatement Clone(this CodeMethodReturnStatement statement)
 {
     if (statement == null) return null;
     CodeMethodReturnStatement s = new CodeMethodReturnStatement();
     s.EndDirectives.AddRange(statement.EndDirectives);
     s.Expression = statement.Expression.Clone();
     s.LinePragma = statement.LinePragma;
     s.StartDirectives.AddRange(statement.StartDirectives);
     s.UserData.AddRange(statement.UserData);
     return s;
 }
 private void AddMemberOverride(string name, Type type, CodeExpression expr)
 {
     CodeMemberProperty property = new CodeMemberProperty {
         Name = name,
         Attributes = MemberAttributes.Family | MemberAttributes.Override,
         Type = new CodeTypeReference(type.FullName)
     };
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(expr);
     property.GetStatements.Add(statement);
     base._sourceDataClass.Members.Add(property);
 }
 public TypescriptMethodReturnStatement(
     IStatementFactory statementFactory,
     IExpressionFactory expressionFactory,
     CodeMethodReturnStatement statement,
     CodeGeneratorOptions options)
 {
     _statementFactory = statementFactory;
     _expressionFactory = expressionFactory;
     _statement = statement;
     _options = options;
 }
Exemplo n.º 14
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;
        }
 private void AddCodeForGetProfileForUser(CodeTypeDeclaration type)
 {
     CodeMemberMethod method = new CodeMemberMethod {
         Name = "GetProfile",
         Attributes = MemberAttributes.Public,
         ReturnType = new CodeTypeReference("ProfileCommon")
     };
     method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "username"));
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = { TargetObject = new CodeTypeReferenceExpression("ProfileBase"), MethodName = "Create" }
     };
     expression.Parameters.Add(new CodeArgumentReferenceExpression("username"));
     CodeMethodReturnStatement statement = new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, expression));
     MTConfigUtil.GetProfileAppConfig();
     method.Statements.Add(statement);
     type.Members.Add(method);
 }
Exemplo n.º 16
0
 public CodeMemberProperty CreateProperty(Type 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;
 }
Exemplo n.º 17
0
 public CodeMethodReturnStatement Return(CodeExpression expr)
 {
     CodeMethodReturnStatement st = new CodeMethodReturnStatement(expr);
     csc.Add(st);
     return st;
 }
Exemplo n.º 18
0
        // ReSharper disable once FunctionComplexityOverflow
        public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBinding)
        {
            CodeTypeMember member;

            var typeClassModel = TypeClassModel;
            var isArray = IsArray;
            var propertyType = PropertyType;
            var isNullableValueType = IsNullableValueType;
            var typeReference = TypeReference;
            var simpleType = propertyType as SimpleModel;

            var requiresBackingField = withDataBinding || DefaultValue != null || IsCollection || isArray;
            var backingField = new CodeMemberField(typeReference, OwningType.GetUniqueFieldName(this))
            {
                Attributes = MemberAttributes.Private
            };
            var ignoreAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlIgnoreAttribute)));
            var notMappedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(NotMappedAttribute)));
            backingField.CustomAttributes.Add(ignoreAttribute);

            if (requiresBackingField)
            {
                typeDeclaration.Members.Add(backingField);
            }

            if (DefaultValue == null)
            {
                var propertyName = isNullableValueType && Configuration.GenerateNullables ? Name + "Value" : Name;
                member = new CodeMemberField(typeReference, propertyName);
                var isPrivateSetter = IsCollection || isArray;
                if (requiresBackingField)
                {
                    member.Name += GetAccessors(member.Name, backingField.Name,
                        IsCollection || isArray ? PropertyValueTypeCode.Array : propertyType.GetPropertyValueTypeCode(),
                        isPrivateSetter, withDataBinding);
                }
                else
                {
                    // hack to generate automatic property
                    member.Name += isPrivateSetter ? " { get; private set; }" : " { get; set; }";
                }
            }
            else
            {
                var defaultValueExpression = propertyType.GetDefaultValueFor(DefaultValue);
                backingField.InitExpression = defaultValueExpression;

                member = new CodeMemberField(typeReference, Name);
                member.Name += GetAccessors(member.Name, backingField.Name, propertyType.GetPropertyValueTypeCode(), false, withDataBinding);

                if (IsNullable)
                {
                    if (!(defaultValueExpression is CodeObjectCreateExpression))
                    {
                        var defaultValueAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultValueAttribute)),
                            new CodeAttributeArgument(defaultValueExpression));
                        member.CustomAttributes.Add(defaultValueAttribute);
                    }
                }
            }

            member.Attributes = MemberAttributes.Public;
            typeDeclaration.Members.Add(member);

            AddDocs(member);

            if (IsDeprecated)
            {
                // From .NET 3.5 XmlSerializer doesn't serialize objects with [Obsolete] >(
                //var deprecatedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute)));
                //member.CustomAttributes.Add(deprecatedAttribute);
            }

            if (isNullableValueType)
            {
                var specifiedName = Configuration.GenerateNullables ? Name + "Value" : Name;
                var specifiedMember = new CodeMemberField(typeof(bool), specifiedName + "Specified { get; set; }");
                specifiedMember.CustomAttributes.Add(ignoreAttribute);
                if (Configuration.EntityFramework && Configuration.GenerateNullables) specifiedMember.CustomAttributes.Add(notMappedAttribute);
                specifiedMember.Attributes = MemberAttributes.Public;
                var specifiedDocs = new[] { new DocumentationModel { Language = "en", Text = string.Format("Gets or sets a value indicating whether the {0} property is specified.", Name) },
                    new DocumentationModel { Language = "de", Text = string.Format("Ruft einen Wert ab, der angibt, ob die {0}-Eigenschaft spezifiziert ist, oder legt diesen fest.", Name) } };
                specifiedMember.Comments.AddRange(DocumentationModel.GetComments(specifiedDocs).ToArray());
                typeDeclaration.Members.Add(specifiedMember);

                if (Configuration.GenerateNullables)
                {
                    // public X? Name
                    // {
                    //      get { return NameSpecified ? NameValue : null; }
                    //      set
                    //      {
                    //          NameValue = value.GetValueOrDefault();
                    //          NameSpecified = value.HasValue;
                    //      }
                    // }

                    var nullableType = new CodeTypeReference(typeof(Nullable<>));
                    nullableType.TypeArguments.Add(typeReference);
                    var nullableMember = new CodeMemberProperty
                    {
                        Type = nullableType,
                        Name = Name,
                        HasSet = true,
                        HasGet = true,
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    };
                    nullableMember.CustomAttributes.Add(ignoreAttribute);
                    nullableMember.Comments.AddRange(member.Comments);

                    var specifiedExpression = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), specifiedName + "Specified");
                    var valueExpression = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), Name + "Value");
                    var conditionStatement = new CodeConditionStatement(specifiedExpression,
                        new CodeStatement[] { new CodeMethodReturnStatement(valueExpression) },
                        new CodeStatement[] { new CodeMethodReturnStatement(new CodePrimitiveExpression(null)) });
                    nullableMember.GetStatements.Add(conditionStatement);

                    var getValueOrDefaultExpression = new CodeMethodInvokeExpression(new CodePropertySetValueReferenceExpression(), "GetValueOrDefault");
                    var setValueStatement = new CodeAssignStatement(valueExpression, getValueOrDefaultExpression);
                    var hasValueExpression = new CodePropertyReferenceExpression(new CodePropertySetValueReferenceExpression(), "HasValue");
                    var setSpecifiedStatement = new CodeAssignStatement(specifiedExpression, hasValueExpression);

                    var statements = new List<CodeStatement>();
                    if (withDataBinding)
                    {
                        var ifNotEquals = new CodeConditionStatement(
                            new CodeBinaryOperatorExpression(
                                new CodeMethodInvokeExpression(valueExpression, "Equals", getValueOrDefaultExpression),
                                CodeBinaryOperatorType.ValueEquality,
                                new CodePrimitiveExpression(false)
                                ),
                            setValueStatement,
                            setSpecifiedStatement,
                            new CodeExpressionStatement(new CodeMethodInvokeExpression(null, "OnPropertyChanged",
                                new CodePrimitiveExpression(Name)))
                            );
                        statements.Add(ifNotEquals);
                    }
                    else
                    {
                        statements.Add(setValueStatement);
                        statements.Add(setSpecifiedStatement);
                    }

                    nullableMember.SetStatements.AddRange(statements.ToArray());

                    typeDeclaration.Members.Add(nullableMember);

                    var editorBrowsableAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute)));
                    editorBrowsableAttribute.Arguments.Add(new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EditorBrowsableState)), "Never")));
                    specifiedMember.CustomAttributes.Add(editorBrowsableAttribute);
                    member.CustomAttributes.Add(editorBrowsableAttribute);
                    if (Configuration.EntityFramework) member.CustomAttributes.Add(notMappedAttribute);
                }
            }
            else if ((IsCollection || isArray) && IsNullable && !IsAttribute)
            {
                var specifiedProperty = new CodeMemberProperty
                {
                    Type = new CodeTypeReference(typeof(bool)),
                    Name = Name + "Specified",
                    HasSet = false,
                    HasGet = true,
                };
                specifiedProperty.CustomAttributes.Add(ignoreAttribute);
                if (Configuration.EntityFramework) specifiedProperty.CustomAttributes.Add(notMappedAttribute);
                specifiedProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                var listReference = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), Name);
                var countReference = new CodePropertyReferenceExpression(listReference, "Count");
                var notZeroExpression = new CodeBinaryOperatorExpression(countReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(0));
                var returnStatement = new CodeMethodReturnStatement(notZeroExpression);
                specifiedProperty.GetStatements.Add(returnStatement);

                var specifiedDocs = new[] { new DocumentationModel { Language = "en", Text = string.Format("Gets a value indicating whether the {0} collection is empty.", Name) },
                    new DocumentationModel { Language = "de", Text = string.Format("Ruft einen Wert ab, der angibt, ob die {0}-Collection leer ist.", Name) } };
                specifiedProperty.Comments.AddRange(DocumentationModel.GetComments(specifiedDocs).ToArray());

                typeDeclaration.Members.Add(specifiedProperty);
            }

            var attribute = GetAttribute(isArray);
            member.CustomAttributes.Add(attribute);

            // initialize List<>
            if (IsCollection || isArray)
            {
                var constructor = typeDeclaration.Members.OfType<CodeConstructor>().FirstOrDefault();
                if (constructor == null)
                {
                    constructor = new CodeConstructor { Attributes = MemberAttributes.Public | MemberAttributes.Final };
                    var constructorDocs = new[] { new DocumentationModel { Language = "en", Text = string.Format(@"Initializes a new instance of the <see cref=""{0}"" /> class.", typeDeclaration.Name) },
                        new DocumentationModel { Language = "de", Text = string.Format(@"Initialisiert eine neue Instanz der <see cref=""{0}"" /> Klasse.", typeDeclaration.Name) } };
                    constructor.Comments.AddRange(DocumentationModel.GetComments(constructorDocs).ToArray());
                    typeDeclaration.Members.Add(constructor);
                }
                var listReference = requiresBackingField ? (CodeExpression)new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name) :
                    new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), Name);
                var initTypeReference = propertyType.GetReferenceFor(OwningType.Namespace, true, true);
                var initExpression = new CodeObjectCreateExpression(initTypeReference);
                constructor.Statements.Add(new CodeAssignStatement(listReference, initExpression));
            }

            if (isArray)
            {
                var arrayItemProperty = typeClassModel.Properties[0];
                var propertyAttribute = arrayItemProperty.GetAttribute(false);
                // HACK: repackage as ArrayItemAttribute
                var arrayItemAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlArrayItemAttribute)),
                    propertyAttribute.Arguments.Cast<CodeAttributeArgument>().Where(x => !string.Equals(x.Name, "Order", StringComparison.Ordinal)).ToArray());
                member.CustomAttributes.Add(arrayItemAttribute);
            }

            if (IsKey)
            {
                var keyAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(KeyAttribute)));
                member.CustomAttributes.Add(keyAttribute);
            }

            if (IsAny && Configuration.EntityFramework)
            {
                member.CustomAttributes.Add(notMappedAttribute);
            }
        }
 internal void GenerateProcessMethod(BrowserDefinition bd, CodeTypeDeclaration ctd, string prefix)
 {
     CodeMemberMethod cmm = new CodeMemberMethod {
         Name = prefix + bd.Name + "Process",
         ReturnType = new CodeTypeReference(typeof(bool)),
         Attributes = MemberAttributes.Private
     };
     CodeParameterDeclarationExpression expression = new CodeParameterDeclarationExpression(typeof(NameValueCollection), "headers");
     cmm.Parameters.Add(expression);
     expression = new CodeParameterDeclarationExpression(typeof(HttpBrowserCapabilities), "browserCaps");
     cmm.Parameters.Add(expression);
     bool regexWorkerGenerated = false;
     this.GenerateIdentificationCode(bd, cmm, ref regexWorkerGenerated);
     this.GenerateCapturesCode(bd, cmm, ref regexWorkerGenerated);
     this.GenerateSetCapabilitiesCode(bd, cmm, ref regexWorkerGenerated);
     this.GenerateSetAdaptersCode(bd, cmm);
     if (bd.IsDeviceNode)
     {
         CodeMethodInvokeExpression expression2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("browserCaps"), "AddBrowser", new CodeExpression[0]);
         expression2.Parameters.Add(new CodePrimitiveExpression(bd.ID));
         cmm.Statements.Add(expression2);
     }
     foreach (BrowserDefinition definition in bd.RefGateways)
     {
         this.AddComment("ref gateways, parent=" + bd.ID, cmm);
         this.GenerateSingleProcessCall(definition, cmm);
     }
     if (this.GenerateOverrides && (prefix.Length == 0))
     {
         string methodName = prefix + bd.Name + "ProcessGateways";
         this.GenerateChildProcessMethod(methodName, ctd, false);
         this.GenerateChildProcessInvokeExpression(methodName, cmm, false);
     }
     foreach (BrowserDefinition definition2 in bd.Gateways)
     {
         this.AddComment("gateway, parent=" + bd.ID, cmm);
         this.GenerateSingleProcessCall(definition2, cmm);
     }
     if (this.GenerateOverrides)
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(bool), "ignoreApplicationBrowsers", new CodePrimitiveExpression(bd.Browsers.Count != 0));
         cmm.Statements.Add(statement);
     }
     if (bd.Browsers.Count > 0)
     {
         CodeStatementCollection stmts = cmm.Statements;
         this.AddComment("browser, parent=" + bd.ID, cmm);
         foreach (BrowserDefinition definition3 in bd.Browsers)
         {
             stmts = this.GenerateTrackedSingleProcessCall(stmts, definition3, cmm, prefix);
         }
         if (this.GenerateOverrides)
         {
             CodeAssignStatement statement2 = new CodeAssignStatement {
                 Left = new CodeVariableReferenceExpression("ignoreApplicationBrowsers"),
                 Right = new CodePrimitiveExpression(false)
             };
             stmts.Add(statement2);
         }
     }
     foreach (BrowserDefinition definition4 in bd.RefBrowsers)
     {
         this.AddComment("ref browsers, parent=" + bd.ID, cmm);
         if (definition4.IsDefaultBrowser)
         {
             this.GenerateSingleProcessCall(definition4, cmm, "Default");
         }
         else
         {
             this.GenerateSingleProcessCall(definition4, cmm);
         }
     }
     if (this.GenerateOverrides)
     {
         string str2 = prefix + bd.Name + "ProcessBrowsers";
         this.GenerateChildProcessMethod(str2, ctd, true);
         this.GenerateChildProcessInvokeExpression(str2, cmm, true);
     }
     CodeMethodReturnStatement statement3 = new CodeMethodReturnStatement(new CodePrimitiveExpression(true));
     cmm.Statements.Add(statement3);
     ctd.Members.Add(cmm);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Adds a method to the class. This method multiplies values stored 
        /// in both fields.
        /// </summary>
        public void AddMethod()
        {
            // Declaring a ToString method
            CodeMemberMethod toStringMethod = new CodeMemberMethod();
            toStringMethod.Attributes =
                MemberAttributes.Public | MemberAttributes.Override;
            toStringMethod.Name = "ToString";
            toStringMethod.ReturnType =
                new CodeTypeReference(typeof(System.String));

            CodeFieldReferenceExpression widthReference =
                new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), "Width");
            CodeFieldReferenceExpression heightReference =
                new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), "Height");
            CodeFieldReferenceExpression areaReference =
                new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), "Area");

            // Declaring a return statement for method ToString.
            CodeMethodReturnStatement returnStatement =
                new CodeMethodReturnStatement();

            // This statement returns a string representation of the width,
            // height, and area.
            string formattedOutput = "The object:" + Environment.NewLine +
                " width = {0}," + Environment.NewLine +
                " height = {1}," + Environment.NewLine +
                " area = {2}";
            returnStatement.Expression =
                new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("System.String"), "Format",
                new CodePrimitiveExpression(formattedOutput),
                widthReference, heightReference, areaReference);
            toStringMethod.Statements.Add(returnStatement);
            targetClass.Members.Add(toStringMethod);
        }
        public override object Visit(ReturnStatement returnStatement, object data)
        {
            ProcessSpecials(returnStatement.Specials);

            CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement((CodeExpression)returnStatement.ReturnExpression.AcceptVisitor(this,data));

            AddStmt(returnStmt);

            return returnStmt;
        }
Exemplo n.º 22
0
        public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(System.CodeDom.CodeTypeDeclaration codeClass, System.CodeDom.CodeStatementCollection codeStatementCollection, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Method context)
        {
            MethodInvokeParameterControl retCtrl = null;
            Dictionary <BaseNodeControl, System.CodeDom.CodeExpression> paramCodeExps = new Dictionary <BaseNodeControl, System.CodeDom.CodeExpression>();

            foreach (var paramNode in mChildNodes)
            {
                if (paramNode is MethodInvokeParameterControl)
                {
                    var pm    = paramNode as MethodInvokeParameterControl;
                    var param = pm.CSParam as MethodInvokeParameterControl.MethodInvokeParameterConstructionParams;
                    if (param.ParamInfo.ParamName == "Return")
                    {
                        retCtrl = pm;
                        continue;
                    }
                    if (pm.HasLink())
                    {
                        await pm.GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, pm.ParamPin, context);

                        var exp = new CodeGenerateSystem.CodeDom.CodeCastExpression(param.ParamInfo.ParameterType, pm.GCode_CodeDom_GetValue(pm.ParamPin, context));
                        paramCodeExps[paramNode] = exp;
                        codeStatementCollection.Add(new System.CodeDom.CodeAssignStatement(
                                                        new System.CodeDom.CodeVariableReferenceExpression(param.ParamInfo.ParamName),
                                                        exp));
                    }
                    else if (mTemplateClassInstance != null)
                    {
                        var    proInfo = mTemplateClassInstance.GetType().GetProperty(param.ParamInfo.ParamName);
                        object proValue;
                        if (proInfo == null)
                        {
                            proValue = CodeGenerateSystem.Program.GetDefaultValueFromType(param.ParamInfo.ParameterType);
                        }
                        else
                        {
                            proValue = proInfo.GetValue(mTemplateClassInstance);
                        }
                        var valueExp = Program.GetValueCode(codeStatementCollection, param.ParamInfo.ParameterType, proValue);
                        paramCodeExps[paramNode] = valueExp;
                        codeStatementCollection.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeVariableReferenceExpression(param.ParamInfo.ParamName), valueExp));
                    }
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }

            if (retCtrl != null)
            {
                if (retCtrl.HasLink())
                {
                    await retCtrl.GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, retCtrl.ParamPin, context);
                }

                System.CodeDom.CodeExpression retExp = null;
                if (retCtrl.HasLink())
                {
                    var retStatement = new System.CodeDom.CodeMethodReturnStatement();
                    retExp = retCtrl.GCode_CodeDom_GetValue(retCtrl.ParamPin, context);
                    paramCodeExps[retCtrl] = retExp;
                }
                else if (mTemplateClassInstance != null)
                {
                    var    param   = retCtrl.CSParam as MethodInvokeParameterControl.MethodInvokeParameterConstructionParams;
                    var    proInfo = mTemplateClassInstance.GetType().GetProperty("Return");
                    object proValue;
                    if (proInfo == null)
                    {
                        proValue = CodeGenerateSystem.Program.GetDefaultValueFromType(param.ParamInfo.ParameterType);
                    }
                    else
                    {
                        proValue = proInfo.GetValue(mTemplateClassInstance);
                    }
                    retExp = Program.GetValueCode(codeStatementCollection, param.ParamInfo.ParameterType, proValue);
                    paramCodeExps[retCtrl] = retExp;
                }

                #region Debug
                var debugCodes = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(codeStatementCollection);
                foreach (var paramNode in mChildNodes)
                {
                    if (paramNode is MethodInvokeParameterControl)
                    {
                        var pm = paramNode as MethodInvokeParameterControl;
                        System.CodeDom.CodeExpression exp;
                        if (paramCodeExps.TryGetValue(paramNode, out exp))
                        {
                            CodeDomNode.BreakPoint.GetGatherDataValueCodeStatement(debugCodes, pm.ParamPin.GetLinkPinKeyName(), exp, pm.GCode_GetTypeString(pm.ParamPin, context), context);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("未实现");
                    }
                }
                var breakCondStatement = CodeDomNode.BreakPoint.BreakCodeStatement(codeClass, debugCodes, HostNodesContainer.GUID, Id);
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(codeStatementCollection, debugCodes);
                #endregion

                var returnParam = CSParam as ReturnConstructParam;
                foreach (var param in returnParam.MethodInfo.Params)
                {
                    // ref或out,需要将displayType造成的临时变量再赋给原函数参数
                    if ((param.FieldDirection == FieldDirection.Out || param.FieldDirection == FieldDirection.Ref) && param.ParameterDisplayType != null)
                    {
                        codeStatementCollection.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("temp___" + param.ParamName), new CodeGenerateSystem.CodeDom.CodeCastExpression(param.ParameterType, new CodeVariableReferenceExpression(param.ParamName))));
                    }
                }
                if (returnParam.MethodInfo.ReturnType.BaseType == typeof(System.Threading.Tasks.Task))
                {
                    var genericType = returnParam.MethodInfo.ReturnType.GetGenericArguments()[0];
                    codeStatementCollection.Add(new System.CodeDom.CodeMethodReturnStatement(new CodeGenerateSystem.CodeDom.CodeCastExpression(genericType, retExp)));
                }
                else
                {
                    codeStatementCollection.Add(new System.CodeDom.CodeMethodReturnStatement(new CodeGenerateSystem.CodeDom.CodeCastExpression(returnParam.MethodInfo.ReturnType, retExp)));
                }
            }
            else
            {
                #region Debug
                var debugCodes         = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(codeStatementCollection);
                var breakCondStatement = CodeDomNode.BreakPoint.BreakCodeStatement(codeClass, debugCodes, HostNodesContainer.GUID, Id);
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(codeStatementCollection, debugCodes);
                #endregion

                var returnParam = CSParam as ReturnConstructParam;
                foreach (var param in returnParam.MethodInfo.Params)
                {
                    // ref或out,需要将displayType造成的临时变量再赋给原函数参数
                    if ((param.FieldDirection == FieldDirection.Out || param.FieldDirection == FieldDirection.Ref) && param.ParameterDisplayType != null)
                    {
                        codeStatementCollection.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("temp___" + param.ParamName), new CodeGenerateSystem.CodeDom.CodeCastExpression(param.ParameterType, new CodeVariableReferenceExpression(param.ParamName))));
                    }
                }
                codeStatementCollection.Add(new System.CodeDom.CodeMethodReturnStatement());
            }
        }
Exemplo n.º 23
0
 protected override void GenerateMethodReturnStatement(System.CodeDom.CodeMethodReturnStatement e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
        /// <summary>
        /// Generate Code to put the views in the generated code.
        /// </summary>
        /// <param name="typeDeclaration"></param>
        /// <param name="generatedViews"></param>
        /// <returns></returns>
        private static void CreateAndAddGetViewAtMethod(CodeTypeDeclaration typeDeclaration, Dictionary<EntitySetBase, string> generatedViews)
        {

            //Add the views to a method
            CodeMemberMethod getViewAtMethod = new CodeMemberMethod();
            getViewAtMethod.Name = EntityViewGenerationConstants.GetViewAtMethodName;
            getViewAtMethod.ReturnType = new CodeTypeReference(typeof(KeyValuePair<,>).MakeGenericType(new Type[] { typeof(string), typeof(string) }));
            CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "index");
            getViewAtMethod.Parameters.Add(parameter);
            getViewAtMethod.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryStartElement, true /*docComment*/));
            getViewAtMethod.Comments.Add(new CodeCommentStatement(Strings.GetViewAtMethodComments, true /*docComment*/));
            getViewAtMethod.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryEndElement, true /*docComment*/));

            getViewAtMethod.Attributes = MemberAttributes.Family | MemberAttributes.Override;

            typeDeclaration.Members.Add(getViewAtMethod);
            
            int index = 0;
            CodeVariableReferenceExpression indexParameterReference = new CodeVariableReferenceExpression(getViewAtMethod.Parameters[0].Name);

            foreach (KeyValuePair<EntitySetBase, string> generatedViewPair in generatedViews)
            {
                // the CodeDom does not support the following scenarios
                // 1. switch statement
                // 2. if(){} else if(){}
                // The original design here was to have the following code,
                // if() { else { if(){} } }
                // but this had some drawbacks as described in TFS workitem 590996
                // Given the not supported scenarios in CodeDom, we choose only use if statement in this case

                // if(index == 0)
                CodeConditionStatement currentIf = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                indexParameterReference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(index)));

                getViewAtMethod.Statements.Add(currentIf);

                EntitySetBase entitySet = generatedViewPair.Key;
                string extentFullName = GetExtentFullName(entitySet);
                CodeMemberMethod viewMethod = CreateViewReturnMethod(extentFullName, index, generatedViewPair.Value);
                typeDeclaration.Members.Add(viewMethod);

                // return GetNorthwindContext_Customers();
                CodeMethodReturnStatement returnViewMethodCall = new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, viewMethod.Name)));
                currentIf.TrueStatements.Add(returnViewMethodCall);

                index++;
            }
            
            // if an invalid index is asked for throw
            getViewAtMethod.Statements.Add(new CodeThrowExceptionStatement(
                                            new CodeObjectCreateExpression(new CodeTypeReference(typeof(IndexOutOfRangeException)))));
        }
		protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
		{
			Output.WriteLine("[CodeMethodReturnStatement: {0}]", e.ToString());
		}
Exemplo n.º 26
0
		void AddProfileClassGroupProperty (string groupName, string memberName, CodeTypeDeclaration profileClass)
		{			
			CodeMemberProperty property = new CodeMemberProperty ();
			property.Name = memberName;
			property.Type = new CodeTypeReference (groupName);
			property.Attributes = MemberAttributes.Public;

			CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
			CodeCastExpression cast = new CodeCastExpression ();
			ret.Expression = cast;

			CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
				new CodeThisReferenceExpression (),
				"GetProfileGroup");
			CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
				mref,
				new CodeExpression[] { new CodePrimitiveExpression (memberName) }
			);
			cast.TargetType = new CodeTypeReference (groupName);
			cast.Expression = minvoke;
			property.GetStatements.Add (ret);
			
			profileClass.Members.Add (property);
		}
Exemplo n.º 27
0
 private void CheckOccurrence(CodeStatementCollection getStatements)
 {
     Debug.Assert(!this.IsList);
     CodeStatement returnStatement = null;
     if (IsNullable && DefaultValue == null)
     {
         if (typeRef.IsValueType)
         {
             // Need to return T?, since parseValue handles only T,
             // checking for null
             returnStatement = new CodeMethodReturnStatement(
                 new CodePrimitiveExpression(null));
         }
     }
     else if (VerifyRequired)
     {
         Debug.Assert(this.occursInSchema == Occurs.One);
         string origin =
             this.propertyOrigin == SchemaOrigin.Element ?
                 "Element" :
             this.propertyOrigin == SchemaOrigin.Attribute ?
                 "Attribute":
             // otherwise
                 null;
         returnStatement = new CodeThrowExceptionStatement(new CodeObjectCreateExpression(Constants.LinqToXsdException, new CodePrimitiveExpression("Missing required " + origin)));
     }
     if (returnStatement != null) {
         getStatements.Add(
             new CodeConditionStatement(
                 new CodeBinaryOperatorExpression(
                     new CodeVariableReferenceExpression("x"),
                     CodeBinaryOperatorType.IdentityEquality,
                     new CodePrimitiveExpression(null)),
                 returnStatement));
     }
 }
Exemplo n.º 28
0
 protected override void GenerateMethodReturnStatement(CodeMethodReturnStatement e)
 {
     if (e.Expression != null)
     {
         base.Output.Write("Return ");
         base.GenerateExpression(e.Expression);
         base.Output.WriteLine("");
     }
     else
     {
         base.Output.WriteLine("Return");
     }
 }
Exemplo n.º 29
0
        public CodeMemberProperty CreateProperty(Type type, string propertyName, bool fieldIsNull, bool useLazy = true)
        {
            bool setFieldAsNullable = fieldIsNull && IsNullable(type);
            var codeMemberProperty = new CodeMemberProperty
            {
                Name = propertyName,
                HasGet = true,
                HasSet = true,
                Attributes = MemberAttributes.Public,
                Type =
                     (setFieldAsNullable
                          ? new CodeTypeReference(typeof(Nullable))
                          : new CodeTypeReference(type))
            };
            if (setFieldAsNullable)
                codeMemberProperty.Type.TypeArguments.Add(type);

            string 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);
            if (!useLazy)
                codeMemberProperty.Attributes = codeMemberProperty.Attributes | MemberAttributes.Final;
            return codeMemberProperty;
        }
Exemplo n.º 30
0
        public override object VisitReturnStatement(ReturnStatement returnStatement, object data)
        {
            CodeMethodReturnStatement returnStmt;
            if (returnStatement.Expression.IsNull)
                returnStmt = new CodeMethodReturnStatement();
            else
                returnStmt = new CodeMethodReturnStatement((CodeExpression)returnStatement.Expression.AcceptVisitor(this,data));

            AddStmt(returnStmt);

            return returnStmt;
        }
Exemplo n.º 31
0
        internal CodeMemberProperty CreatePropertyDeclaration(CodeMemberField field, string name, string typeName) {
            CodeMemberProperty prop = new CodeMemberProperty();
            prop.Type = new CodeTypeReference(typeName);
            prop.Name = name;
            prop.Attributes = (prop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            //add get
            CodeMethodReturnStatement ret = new CodeMethodReturnStatement();
            ret.Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
            prop.GetStatements.Add(ret);
   
            CodeAssignStatement propertySet = new CodeAssignStatement();
            CodeExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
            CodeExpression right = new CodePropertySetValueReferenceExpression();
            propertySet.Left = left;
            propertySet.Right = right;

            if (EnableDataBinding)
            {
                prop.SetStatements.Add(propertySet);
                prop.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), RaisePropertyChangedEventMethod.Name, new CodePrimitiveExpression(name)));
            }
            else
                prop.SetStatements.Add(propertySet);

            return prop;
        }
Exemplo n.º 32
0
		void AddProfileClassProperty (ProfileSection ps, CodeTypeDeclaration profileClass, ProfilePropertySettings pset)
		{
			string name = pset.Name;
			if (String.IsNullOrEmpty (name))
				throw new HttpException ("Profile property 'Name' attribute cannot be null.");
			CodeMemberProperty property = new CodeMemberProperty ();
			string typeName = pset.Type;
			if (typeName == "string")
				typeName = "System.String";
			property.Name = name;
			property.Type = GetProfilePropertyType (typeName);
			property.Attributes = MemberAttributes.Public;
			
			CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();
			GetProfileProviderAttribute (ps, collection, pset.Provider);
			GetProfileSettingsSerializeAsAttribute (ps, collection, pset.SerializeAs);

			property.CustomAttributes = collection;
			CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
			CodeCastExpression cast = new CodeCastExpression ();
			ret.Expression = cast;

			CodeMethodReferenceExpression mref = new CodeMethodReferenceExpression (
				new CodeThisReferenceExpression (),
				"GetPropertyValue");
			CodeMethodInvokeExpression minvoke = new CodeMethodInvokeExpression (
				mref,
				new CodeExpression[] { new CodePrimitiveExpression (name) }
			);
			cast.TargetType = new CodeTypeReference (typeName);
			cast.Expression = minvoke;
			property.GetStatements.Add (ret);

			if (!pset.ReadOnly) {
				mref = new CodeMethodReferenceExpression (
					new CodeThisReferenceExpression (),
					"SetPropertyValue");
				minvoke = new CodeMethodInvokeExpression (
					mref,
					new CodeExpression[] { new CodePrimitiveExpression (name), new CodeSnippetExpression ("value") }
				);
				property.SetStatements.Add (minvoke);
			}
			
			
			profileClass.Members.Add (property);
		}