Inheritance: System.CodeDom.CodeExpression
Example #1
0
        Type EmitPrimitive(CodePrimitiveExpression Primitive)
        {
            Type T;
            if(Primitive.Value == null) T = null;
            else T = Primitive.Value.GetType();

            if(T != null && T.IsArray)
            {
                var Contents = Primitive.Value as object[];
                Type Element = T.GetElementType();
                Generator.Emit(OpCodes.Ldc_I4, Contents.Length);
                Generator.Emit(OpCodes.Newarr, Element);

                int i = 0;
                foreach(var Value in Contents)
                {
                    Generator.Emit(OpCodes.Dup);
                    Generator.Emit(OpCodes.Ldc_I4, i);

                    EmitLiteral(Element, Value);
                    Generator.Emit(OpCodes.Stelem_Ref);

                    i++;
                }

                return T;
            }
            else return EmitLiteral(T, Primitive.Value);
        }
		public void Constructor1_Deny_Unrestricted ()
		{
			object o = new object ();
			CodePrimitiveExpression cpe = new CodePrimitiveExpression (o);
			Assert.AreSame (o, cpe.Value, "Value");
			cpe.Value = new object ();
		}
        private static CodeExpressionStatement getInvokeDetailStatement(RecordStep step, string dataClass)
        {
            CodeExpressionStatement statement = new CodeExpressionStatement();
            CodeExpression[] paras;
            if (step.ActionParams != null)
            {
                paras = new CodeExpression[step.ActionParams.Count];
                ///判断是否参数化函数代码
                if(dataClass == null)
                {
                    for (int i = 0; i < step.ActionParams.Count; i++)
                    {
                        paras[i] = new CodePrimitiveExpression(step.ActionParams[i].Value);
                    }
                }
                else
                {
                    for (int i = 0; i < step.ActionParams.Count; i++)
                    {
                        paras[i] = step.ActionParams[i].GetVariableReference(dataClass);
                    }
                }

            }
            else
            {
                paras = new CodeExpression[0];
            }

            CodeMethodInvokeExpression method = new CodeMethodInvokeExpression(step.CompInfo.FindMethod, step.ActionName, paras);
            statement.Expression = method;
            return statement;
        }
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            if (!entry.Expression.Contains(","))
              {
            throw new ArgumentException("Must include two numbers separated by a comma.");
              }
              else
              {
            // get two numbers
            string[] numbers = entry.Expression.Split(',');
            if (numbers.Length != 2)
            {
              throw new ArgumentException("Only include two numbers");
            }
            else
            {
              int lowerLimit, upperLimit;
              if (Int32.TryParse(numbers[0], out lowerLimit) && Int32.TryParse(numbers[1], out upperLimit))
              {
            CodeTypeReferenceExpression typeRef = new CodeTypeReferenceExpression(this.GetType());
            CodeExpression[] methodParameters = new CodeExpression[2];
            methodParameters[0] = new CodePrimitiveExpression(lowerLimit);
            methodParameters[1] = new CodePrimitiveExpression(upperLimit);

            return new CodeMethodInvokeExpression(typeRef, "GetRandomNumber", methodParameters);
              }
              else
              {
            throw new ArgumentException("Use valid Integers");
              }
            }
              }
        }
Example #5
0
        protected CodeExpression ConvertTo(string value, Type type)
        {
            var valueExpression = new CodePrimitiveExpression(value);

            var converter = TypeDescriptor.GetConverter(type);

            if (type == typeof(string) || type == typeof(object))
                return valueExpression;

            if (type == typeof(double))
                return new CodePrimitiveExpression(double.Parse(value, CultureInfo.InvariantCulture));

            if (type == typeof(BindingBase))
            {
                var bindingParser = new BindingParser(State);
                var bindingVariableName = bindingParser.Parse(value);
                return new CodeVariableReferenceExpression(bindingVariableName);
            }

            // there is no conversion availabe, the generated code won't compile, but there is nothing we can do about that
            if (converter == null)
                return valueExpression;

            var conversion = new CodeCastExpression(
                type.Name,
                new CodeMethodInvokeExpression(
                    new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("TypeDescriptor"), "GetConverter",
                                                   new CodeTypeOfExpression(type.Name)), "ConvertFromInvariantString",
                    new CodePrimitiveExpression(value)));

            return conversion;
        }
        public void SetRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> arguments, IEnumerable<string> tags, bool isIgnored)
        {
            var args = arguments.Select(
              arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList();

            // addressing ReSharper bug: TestCase attribute with empty string[] param causes inconclusive result - https://github.com/techtalk/SpecFlow/issues/116
            bool hasExampleTags = tags.Any();
            var exampleTagExpressionList = tags.Select(t => new CodePrimitiveExpression(t));
            CodeExpression exampleTagsExpression = hasExampleTags ?
                (CodeExpression)new CodePrimitiveExpression(null) :
                new CodeArrayCreateExpression(typeof(string[]), exampleTagExpressionList.ToArray());
            args.Add(new CodeAttributeArgument(exampleTagsExpression));

            // adds 'Category' named parameter so that NUnit also understands that this test case belongs to the given categories
            if (hasExampleTags)
            {
                CodeExpression exampleTagsStringExpr = new CodePrimitiveExpression(string.Join(",", tags.ToArray()));
                args.Add(new CodeAttributeArgument("Category", exampleTagsStringExpr));
            }

            if (isIgnored)
                args.Add(new CodeAttributeArgument("Ignored", new CodePrimitiveExpression(true)));

            CodeDomHelper.AddAttribute(testMethod, ROW_ATTR, args.ToArray());
        }
		protected override void CreateConstructor (CodeStatementCollection localVars,
							CodeStatementCollection trueStmt)
		{
			if (pageParser.ClientTarget != null) {
				CodeExpression prop;
				prop = new CodePropertyReferenceExpression (thisRef, "ClientTarget");
				CodeExpression ct = new CodePrimitiveExpression (pageParser.ClientTarget);
				if (localVars == null)
					localVars = new CodeStatementCollection ();
				localVars.Add (new CodeAssignStatement (prop, ct));
			}

#if NET_2_0
			if (pageParser.MasterPageFile != null) {
				CodeExpression prop;
				prop = new CodePropertyReferenceExpression (thisRef, "MasterPageFile");
				CodeExpression ct = new CodePrimitiveExpression (pageParser.MasterPageFile);
				if (localVars == null)
					localVars = new CodeStatementCollection ();
				localVars.Add (new CodeAssignStatement (prop, ct));
			}
#endif

			base.CreateConstructor (localVars, trueStmt);
		}
        private static string AppendCreateDictionaryLocalVariable(string dictionary, CodeDomClassBuilder builder)
        {
            var parser = new AttributeParser(dictionary);
            parser.Parse();


            var keyValuePairType = new CodeTypeReference(typeof(KeyValuePair<string,object>));

            var createDictionaryMethod = new CodeMethodInvokeExpression();


            foreach (var attribute in parser.Attributes)
            {

                var newKeyValueExpression = new CodeObjectCreateExpression {CreateType = keyValuePairType};

                var keyExpression = new CodePrimitiveExpression {Value = attribute.Name};
                newKeyValueExpression.Parameters.Add(keyExpression);

                if (attribute.Type == ParsedAttributeType.String)
                {
                    AppendStringDictValue(attribute, newKeyValueExpression);
                }
                else
                {
                    newKeyValueExpression.Parameters.Add(new CodeSnippetExpression
                                                             {
                                                                 Value = attribute.Value

                                                             });
                }

                createDictionaryMethod.Parameters.Add(newKeyValueExpression);
            }



            var getDictionaryMethod = new CodeMethodReferenceExpression
                                          {
                                              MethodName = "GetDictionaryFromKeyValue",
                                              TargetObject =
                                                  new CodeVariableReferenceExpression
                                                      {
                                                          VariableName = "NHamlMonoRailView"
                                                      }
                                          };
            createDictionaryMethod.Method = getDictionaryMethod;

            var variableName = string.Format("nhamlTempDictionary{0}", tempDictionaryCount);
            tempDictionaryCount++;
            var dictionaryDecleration = new CodeVariableDeclarationStatement
                             {
                                 InitExpression = createDictionaryMethod,
                                 Name = variableName,
                                 Type = new CodeTypeReference(typeof (IDictionary<string, object>))
                             };
            builder.RenderMethod.Statements.Add(dictionaryDecleration);
            return variableName;
        }
 public TypescriptPrimitiveExpression(
     CodePrimitiveExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptPrimitiveExpression Created");
 }
Example #10
0
        public static CodeAttributeArgument GetStringArrayAttributeArgument(string[] values)
        {
            CodeExpression[] initializers = new CodeExpression[values.Length];
            for (int i = 0; i < values.Length; i++)
                initializers[i] = new CodePrimitiveExpression(values[i]);

            return new CodeAttributeArgument(new CodeArrayCreateExpression(typeof(string), initializers));
        }
 private static CodeExpression CreateDataArray(byte[] data)
 {
     CodeExpression[] initializers = new CodeExpression[data.Length];
     for (int i = 0; i < data.Length; i++)
     {
         initializers[i] = new CodePrimitiveExpression(data[i]);
     }
     return new CodeArrayCreateExpression(typeof(byte), initializers);
 }
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            string property = (string) parsedData;

            CodePrimitiveExpression prim = new CodePrimitiveExpression(property);
            CodeExpression[] args = new[] {prim};
            CodeTypeReferenceExpression refType = new CodeTypeReferenceExpression(this.GetType());
            return new CodeMethodInvokeExpression(refType, "GetProperty", args);
        }
        private static void AddXmlEnumAttribute(CodeTypeMember member)
        {
            CodeTypeReference attributeType = new CodeTypeReference(typeof (XmlEnumAttribute));
            CodePrimitiveExpression argumentValue = new CodePrimitiveExpression(member.Name);
            CodeAttributeArgument argument = new CodeAttributeArgument(argumentValue);
            CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(attributeType, argument);

            member.CustomAttributes.Add(attribute);
        }
 private static void AddRootElementName(CodeTypeMember type)
 {
     foreach (CodeAttributeDeclaration attribute in type.CustomAttributes)
         if (attribute.Name == typeof (XmlRootAttribute).FullName)
         {
             CodePrimitiveExpression value = new CodePrimitiveExpression(type.Name);
             CodeAttributeArgument argument = new CodeAttributeArgument("", value);
             attribute.Arguments.Insert(0, argument);
         }
 }
 /// <summary>
 /// When overridden in a derived class, returns code that is used during page execution to obtain the evaluated expression.
 /// </summary>
 /// <param name="entry">The object that represents information about the property bound to by the expression.</param>
 /// <param name="parsedData">The object containing parsed data as returned by <see cref="M:System.Web.Compilation.ExpressionBuilder.ParseExpression(System.String,System.Type,System.Web.Compilation.ExpressionBuilderContext)" />.</param>
 /// <param name="context">Contextual information for the evaluation of the expression.</param>
 /// <returns>
 /// A <see cref="T:System.CodeDom.CodeExpression" /> that is used for property assignment.
 /// </returns>
 public override CodeExpression GetCodeExpression( BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context )
 {
     // from http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.getcodeexpression.aspx
     Type type1 = entry.DeclaringType;
     PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties( type1 )[entry.PropertyInfo.Name];
     CodeExpression[] expressionArray1 = new CodeExpression[3];
     expressionArray1[0] = new CodePrimitiveExpression( entry.Expression.Trim() );
     expressionArray1[1] = new CodeTypeOfExpression( type1 );
     expressionArray1[2] = new CodePrimitiveExpression( entry.Name );
     return new CodeCastExpression( descriptor1.PropertyType, new CodeMethodInvokeExpression( new CodeTypeReferenceExpression( base.GetType() ), "GetEvalData", expressionArray1 ) );
 }
Example #16
0
        /// <summary>Creates a code expression that creates a byte array of data.</summary>
        /// <param name="data">The data to translate.</param>
        /// <returns>The code expression representing the array.</returns>
        private static CodeExpression CreateDataArray(byte [] data)
        {
            // Create an array of code expressions, each one a byte primitive
            CodeExpression [] initializers = new CodeExpression[data.Length];
            for(int i=0; i<data.Length; i++)
            {
                initializers[i] = new CodePrimitiveExpression(data[i]);
            }

            // Create the array of bytes used the created initialization list
            return new CodeArrayCreateExpression(typeof(byte), initializers);
        }
        public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            _log.Write(_id, SPTraceLogger.TraceSeverity.InformationEvent, "GetCodeExpression", "Info", "Called");

            CodeTypeReferenceExpression thisType = new CodeTypeReferenceExpression(base.GetType());

            CodePrimitiveExpression expression = new CodePrimitiveExpression(entry.Expression.Trim().ToString());

            string evaluationMethod = "GetKeyValue";

            return new CodeMethodInvokeExpression(thisType, evaluationMethod, new CodeExpression[] { expression });
        }
 internal static void GenerateConstructorStatements(CodeConstructor ctor, string url, string appSettingUrlKey, string appSettingBaseUrl, bool soap11)
 {
     bool flag = (url != null) && (url.Length > 0);
     bool flag2 = (appSettingUrlKey != null) && (appSettingUrlKey.Length > 0);
     CodeAssignStatement statement = null;
     if (flag || flag2)
     {
         CodeExpression expression;
         CodePropertyReferenceExpression left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Url");
         if (flag)
         {
             expression = new CodePrimitiveExpression(url);
             statement = new CodeAssignStatement(left, expression);
         }
         if (flag && !flag2)
         {
             ctor.Statements.Add(statement);
         }
         else if (flag2)
         {
             CodeVariableReferenceExpression expression3 = new CodeVariableReferenceExpression("urlSetting");
             CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(typeof(ConfigurationManager));
             CodePropertyReferenceExpression expression5 = new CodePropertyReferenceExpression(targetObject, "AppSettings");
             expression = new CodeIndexerExpression(expression5, new CodeExpression[] { new CodePrimitiveExpression(appSettingUrlKey) });
             ctor.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "urlSetting", expression));
             if ((appSettingBaseUrl == null) || (appSettingBaseUrl.Length == 0))
             {
                 expression = expression3;
             }
             else
             {
                 if ((url == null) || (url.Length == 0))
                 {
                     throw new ArgumentException(Res.GetString("IfAppSettingBaseUrlArgumentIsSpecifiedThen0"));
                 }
                 string str = new Uri(appSettingBaseUrl).MakeRelative(new Uri(url));
                 CodeExpression[] parameters = new CodeExpression[] { expression3, new CodePrimitiveExpression(str) };
                 expression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), "Concat", parameters);
             }
             CodeStatement[] trueStatements = new CodeStatement[] { new CodeAssignStatement(left, expression) };
             CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
             if (flag)
             {
                 ctor.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[] { statement }));
             }
             else
             {
                 ctor.Statements.Add(new CodeConditionStatement(condition, trueStatements));
             }
         }
     }
 }
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            var expression = new CodeExpression[3];

            expression[0] = new CodePrimitiveExpression(entry.Expression.Trim());
            expression[1] = new CodeTypeOfExpression(typeof(string));
            expression[2] = new CodePrimitiveExpression(entry.Name);

            return new CodeCastExpression(typeof(string),
                                          new CodeMethodInvokeExpression(
                                              new CodeTypeReferenceExpression(GetType()), "GetEvalData",
                                              expression));
        }
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator,
			CodeTypeMemberCollection members)
		{
			string type = (string)table["$key"];
			string className = "TYPE_" + Guid.NewGuid().ToString("N");

			CodeTypeDeclaration classCode = new CodeTypeDeclaration(className);

			classCode.Comments.Add(new CodeCommentStatement("Descriptor of " + type));


			classCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Descriptor of " + type));
			
			classCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));


			classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed;
			
			classCode.BaseTypes.Add(typeof(HardwiredUserDataDescriptor));

			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = MemberAttributes.Assembly;
			ctor.BaseConstructorArgs.Add(new CodeTypeOfExpression(type));

			classCode.Members.Add(ctor);

			generator.DispatchTablePairs(table.Get("members").Table,
				classCode.Members, (key, exp) =>
				{
					var mname = new CodePrimitiveExpression(key);

					ctor.Statements.Add(new CodeMethodInvokeExpression(
						new CodeThisReferenceExpression(), "AddMember", mname, exp));
				});

			generator.DispatchTablePairs(table.Get("metamembers").Table,
				classCode.Members, (key, exp) =>
				{
					var mname = new CodePrimitiveExpression(key);
					
					ctor.Statements.Add(new CodeMethodInvokeExpression(
						new CodeThisReferenceExpression(), "AddMetaMember", mname, exp));
				});

			members.Add(classCode);

			return new CodeExpression[] {
					new CodeObjectCreateExpression(className)
			};
		}
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {

            CodeExpression expression = new CodePrimitiveExpression(value);

            if (value == null
                || value is bool
                || value is char
                || value is int
                || value is float
                || value is double)
            {

                // work aroundf for J#, since they don't support auto-boxing of value types yet.
                CodeDomProvider codeProvider = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
                if (codeProvider != null && String.Equals(codeProvider.FileExtension, JSharpFileExtension))
                {
                    // See if we are boxing - if so, insert a cast.
                    ExpressionContext cxt = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                    //Debug.Assert(cxt != null, "No expression context on stack - J# boxing cast will not be inserted");
                    if (cxt != null)
                    {
                        if (cxt.ExpressionType == typeof(object))
                        {
                            expression = new CodeCastExpression(value.GetType(), expression);
                            expression.UserData.Add("CastIsBoxing", true);
                        }
                    }
                }
                return expression;
            }

            String stringValue = value as string;
            if (stringValue != null)
            {
                // WinWS: The commented code breaks us when we have long strings
                //if (stringValue.Length > 200)
                //{
                // return SerializeToResourceExpression(manager, stringValue);
                //}
                //else 
                return expression;
            }

            // generate a cast for non-int types because we won't parse them properly otherwise because we won't know to convert
            // them to the narrow form.
            //
            return new CodeCastExpression(new CodeTypeReference(value.GetType()), expression);
        }
        internal static CodeMemberProperty GenerateStringConstantPropertyOverride(string propertyName,
                                                                                  string returnValue)
        {
            var property = new CodeMemberProperty();
            property.Name = propertyName;
            property.Type = new CodeTypeReference(typeof(string));
            property.Attributes = MemberAttributes.Family | MemberAttributes.Override; // "protected".
            property.HasGet = true;

            // get { return "..."; }
            var returnString = new CodePrimitiveExpression(returnValue);
            property.GetStatements.Add(new CodeMethodReturnStatement(returnString));

            return property;
        }
Example #23
0
        /// <summary>Initializes the extension</summary>
        /// <param name="parameters">Initialization parameters: This class expects following parameters:
        /// <list type="table"><listheader><term>Parameter</term><description>Description</description></listheader>
        /// <item><term><c>PropertyName</c></term><description>Name of property to add attribute to. Required.</description></item>
        /// <item><term><c>TypeName</c></term><description>Name of type property <c>PropertyName</c> is property of. Required.</description></item>
        /// <item><term><c>Name</c></term><description>Name of the attribute</description></item>
        /// <item><term><c>p-&lt;number></c></term><description>Positional attribute constructor parameter. Optional. See remarks.</description></item>
        /// <item><term><c>p-&lt;string></c></term><description>Named attribute parameter. Optional. See remarks.</description></item>
        /// </list></param>
        /// <remarks>
        /// Positional and named parameters of constructor have name in form p-&lt;number or name> and value in form "&lt;TypeName> &lt;value>".
        /// TypeName can be one of supported attribute parameter types (<see cref="String"/>, <see cref="Byte"/>, <see cref="SByte"/>, <see cref="Int16"/>, <see cref="UInt16"/>, <see cref="Int32"/>, <see cref="UInt32"/>, <see cref="Int64"/>, <see cref="UInt64"/>, <see cref="Decimnal"/>, <see cref="Single"/>, <see cref="Double"/>, <see cref="Boolean"/>, <see cref="DateTime"/>, <see cref="Char"/>, <see cref="Type"/>).
        /// If it is not one of them it's treated a name of enumeration type. For supported types value is parsed in invariant culture to that type using appropriate <c>Parse</c> method.
        /// With exception of <see cref="String"/> which is used directly and <see cref="Type"/> where value part is treated as type name.
        /// For enumerations value part is treated as name of enumeration memner of enumeration specified in type part.
        /// <para>
        /// Positional parameters are added as constuctor parameters in order of their position numbers. Missing position numbers are ignored. Skipped optional parameters are not supported.
        /// Named parameters are added at the end of parameters list as named parameters.
        /// </para></remarks>
        /// <exception cref="KeyNotFoundException">A required parameter is not present in the <paramref name="parameters"/> dictionary.</exception>
        /// <exception cref="FormatException">Value of numeric type cannot be parsed.</exception>
        /// <exception cref="OverflowException">Value of numeric type is out of range of given numberic type.</exception>
        public void Initialize(System.Collections.Generic.IDictionary<string, string> parameters)
        {
            propertyName = parameters["PropertyName"];
            typeName = parameters["TypeName"];
            attributeName = parameters["Name"];
            //Params in arguments name p-Name or p-Number
            //Content typename-space-value (typename cannot contain space)
            List<CodeAttributeArgument> namedParams = new List<CodeAttributeArgument>();
            Dictionary<int, CodeAttributeArgument> posParams = new Dictionary<int, CodeAttributeArgument>();
            foreach (var item in parameters) {
                if (item.Key.StartsWith("p-")) {
                    string pName = item.Key.Substring(2);
                    CodeExpression pValue;
                    int pnum;
                    string TypeName = item.Value.Substring(0, item.Value.IndexOf(' '));
                    string valuePart = item.Value.Substring(item.Value.IndexOf(' ') + 1);
                    switch (TypeName) {
                        case "System.String": pValue = new CodePrimitiveExpression(valuePart); break;
                        case "System.Byte": pValue = new CodePrimitiveExpression(byte.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.SByte": pValue = new CodePrimitiveExpression(SByte.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Int16": pValue = new CodePrimitiveExpression(Int16.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.UInt16": pValue = new CodePrimitiveExpression(UInt16.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Int32": pValue = new CodePrimitiveExpression(Int32.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.UInt32": pValue = new CodePrimitiveExpression(UInt32.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Int64": pValue = new CodePrimitiveExpression(Int64.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.UInt64": pValue = new CodePrimitiveExpression(UInt64.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Decimal": pValue = new CodePrimitiveExpression(Decimal.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Single": pValue = new CodePrimitiveExpression(Single.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Double": pValue = new CodePrimitiveExpression(Double.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;
                        case "System.Boolean": pValue = new CodePrimitiveExpression(bool.Parse(valuePart)); break;
                        case "System.DateTime": pValue = new CodePrimitiveExpression((DateTime)new XAttribute("x", valuePart)); break;
                        case "System.Char": pValue = new CodePrimitiveExpression(valuePart[0]); break;
                        case "System.Type": pValue = new CodeTypeOfExpression(valuePart); break;
                        default://Enum
                            pValue = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(TypeName), valuePart); break;
                    }

                    if (int.TryParse(pName, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out pnum)) {
                        posParams.Add(pnum, new CodeAttributeArgument(pValue));
                    } else {
                        namedParams.Add(new CodeAttributeArgument(pName, pValue));
                    }
                }
            }
            attrParams.AddRange(from itm in posParams orderby itm.Key select itm.Value);
            attrParams.AddRange(namedParams);
        }
        public static void AddArgument(this CodeAttributeDeclaration attribute, string name, string value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            CodeExpression expression;
            // Use convention that if string starts with $ its a const
            if (value.StartsWith(SnippetIndicator.ToString()))
            {
                expression = new CodeSnippetExpression(value.TrimStart(SnippetIndicator));
            }
            else
            {
                expression = new CodePrimitiveExpression(value);
            }
            attribute.AddArgument(name, expression);
        }
Example #25
0
 private static void LoadFieldElement(XmlElement element, CodeTypeDeclaration codeType,
     out CodeMemberProperty codeProperty)
 {
     XmlAttributeCollection attr = element.Attributes;
     string type = element.GetAttribute("type"), name = element.GetAttribute("name");
     if(type == "string") type = "System.String";
     else if(type == "int") type = "System.Int32";
     CodeExpression defaultValue = null;
     if(element.HasAttribute("default")) {
         string defaultString = element.GetAttribute("default");
         if(type == "System.String")
             defaultValue = new CodePrimitiveExpression(defaultString);
         if(type == "System.Int32")
             defaultValue = new CodePrimitiveExpression(int.Parse(defaultString));
     }
     GenerateProperty(codeType, type, name, out codeProperty, defaultValue);
 }
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator,
			CodeTypeMemberCollection members)
		{
			List<CodeExpression> initializers = new List<CodeExpression>();

			generator.DispatchTablePairs(table.Get("overloads").Table, members, exp =>
			{
				initializers.Add(exp);
			});

			var name = new CodePrimitiveExpression((table["name"] as string));
			var type = new CodeTypeOfExpression(table["decltype"] as string);

			var array = new CodeArrayCreateExpression(typeof(IOverloadableMemberDescriptor), initializers.ToArray());

			return new CodeExpression[] {
					new CodeObjectCreateExpression(typeof(OverloadedMethodMemberDescriptor), name, type, array)
			};
		}
Example #27
0
    public static System.CodeDom.CodeCompileUnit BuildGraph()
    {
        System.CodeDom.CodeCompileUnit CompileUnit = new System.CodeDom.CodeCompileUnit();

        System.CodeDom.CodeNamespace nSpace = new System.CodeDom.CodeNamespace("HelloWorldViaCodeDOM");
        CompileUnit.Namespaces.Add(nSpace);

        nSpace.Imports.Add(new System.CodeDom.CodeNamespaceImport("System"));

        System.CodeDom.CodeTypeDeclaration clsStartup = new System.CodeDom.CodeTypeDeclaration("Startup");
        nSpace.Types.Add(clsStartup);

        System.CodeDom.CodeEntryPointMethod        main   = new System.CodeDom.CodeEntryPointMethod();
        System.CodeDom.CodePrimitiveExpression     exp    = new System.CodeDom.CodePrimitiveExpression("Hello World!");
        System.CodeDom.CodeTypeReferenceExpression refExp = new System.CodeDom.CodeTypeReferenceExpression("System.Console");
        System.CodeDom.CodeMethodInvokeExpression  invoke = new System.CodeDom.CodeMethodInvokeExpression(refExp, "WriteLine", exp);
        main.Statements.Add(new System.CodeDom.CodeExpressionStatement(invoke));

        clsStartup.Members.Add(main);

        return(CompileUnit);
    }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression = new CodePrimitiveExpression(value);
     if ((((value == null) || (value is bool)) || ((value is char) || (value is int))) || ((value is float) || (value is double)))
     {
         CodeDomProvider service = manager.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if ((service != null) && string.Equals(service.FileExtension, JSharpFileExtension))
         {
             ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
             if ((context != null) && (context.ExpressionType == typeof(object)))
             {
                 expression = new CodeCastExpression(value.GetType(), expression);
                 expression.UserData.Add("CastIsBoxing", true);
             }
         }
         return expression;
     }
     if (value is string)
     {
         return expression;
     }
     return new CodeCastExpression(new CodeTypeReference(value.GetType()), expression);
 }
		public HardwireParameterDescriptor(Table tpar)
		{
			CodeExpression ename = new CodePrimitiveExpression(tpar.Get("name").String);
			CodeExpression etype = new CodeTypeOfExpression(tpar.Get("origtype").String);
			CodeExpression hasDefaultValue = new CodePrimitiveExpression(tpar.Get("default").Boolean);
			CodeExpression defaultValue = tpar.Get("default").Boolean ? (CodeExpression)(new CodeObjectCreateExpression(typeof(DefaultValue))) :
				(CodeExpression)(new CodePrimitiveExpression(null));
			CodeExpression isOut = new CodePrimitiveExpression(tpar.Get("out").Boolean);
			CodeExpression isRef = new CodePrimitiveExpression(tpar.Get("ref").Boolean);
			CodeExpression isVarArg = new CodePrimitiveExpression(tpar.Get("varargs").Boolean);
			CodeExpression restrictType = tpar.Get("restricted").Boolean ? (CodeExpression)(new CodeTypeOfExpression(tpar.Get("type").String)) :
				(CodeExpression)(new CodePrimitiveExpression(null));

			Expression = new CodeObjectCreateExpression(typeof(ParameterDescriptor), new CodeExpression[] {
					ename, etype, hasDefaultValue, defaultValue, isOut, isRef,
					isVarArg }
			);

			ParamType = tpar.Get("origtype").String;
			HasDefaultValue = tpar.Get("default").Boolean;
			IsOut = tpar.Get("out").Boolean;
			IsRef = tpar.Get("ref").Boolean;
		}
 CodeExpression[] GetExpressionList(ArrayList expressionList)
 {
     if (expressionList == null) {
         return new CodeExpression[0];
     }
     CodeExpression[] list = new CodeExpression[expressionList.Count];
     for (int i = 0; i < expressionList.Count; ++i) {
         list[i] = (CodeExpression)((Expression)expressionList[i]).AcceptVisitor(this, null);
         if (list[i] == null) {
             list[i] = new CodePrimitiveExpression(0);
         }
     }
     return list;
 }
 private void GenerateCodeFromPrimitiveExpression(CodePrimitiveExpression e, TextWriter w, CodeGeneratorOptions o)
 {
     if (e.Value is string)
     {
         w.Write("'{0}'", e.Value);
     }
     else if (e.Value is bool)
     {
         w.Write(((bool)e.Value) ? "$true" : "$false");
     }
     else
     {
         w.Write("{0}", e.Value);
     }
 }
Example #32
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);
                }
            }
        }