Наследование: System.CodeDom.CodeExpression
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression;
     CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
     RootContext context = manager.Context[typeof(RootContext)] as RootContext;
     CodeStatementCollection statements = new CodeStatementCollection();
     if ((declaration != null) && (context != null))
     {
         CodeMemberField field = new CodeMemberField(typeof(IContainer), "components") {
             Attributes = MemberAttributes.Private
         };
         declaration.Members.Add(field);
         expression = new CodeFieldReferenceExpression(context.Expression, "components");
     }
     else
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(IContainer), "components");
         statements.Add(statement);
         expression = new CodeVariableReferenceExpression("components");
     }
     base.SetExpression(manager, value, expression);
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(typeof(Container), new CodeExpression[0]);
     CodeAssignStatement statement2 = new CodeAssignStatement(expression, right);
     statement2.UserData["IContainer"] = "IContainer";
     statements.Add(statement2);
     return statements;
 }
Пример #2
0
        static void AddEntryPoint()
        {
            CodeEntryPointMethod start = new CodeEntryPointMethod();
            CodeObjectCreateExpression objectCreate =
                new CodeObjectCreateExpression(
                new CodeTypeReference("CodeDOMCreatedClass"),
                new CodePrimitiveExpression(5.3),
                new CodePrimitiveExpression(6.9));

            // Add the statement:
            // "CodeDOMCreatedClass testClass =
            //     new CodeDOMCreatedClass(5.3, 6.9);"
            start.Statements.Add(new CodeVariableDeclarationStatement(
                new CodeTypeReference("CodeDOMCreatedClass"), "testClass",
                objectCreate));

            // Creat the expression:
            // "testClass.ToString()"
            CodeMethodInvokeExpression toStringInvoke =
                new CodeMethodInvokeExpression(
                new CodeVariableReferenceExpression("testClass"), "ToString");

            // Add a System.Console.WriteLine statement with the previous
            // expression as a parameter.
            start.Statements.Add(new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("System.Console"),
                "WriteLine", toStringInvoke));
            targetClass.Members.Add(start);
        }
		protected CodeExpression CreateNewWizardStepReference(WizardControllerTreeNode node, string wizardStepPage)
		{
			CodeExpression createMethodSignature = new CodeObjectCreateExpression(
				source[typeof (MethodSignature)],
				new CodeExpression[]
				{
					new CodeTypeOfExpression(node.FullName),
					new CodePrimitiveExpression(node.Name),
					new CodeArrayCreateExpression(source[typeof (Type)], 0)
				});

			var constructionArguments = new[]
			{
				new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), naming.ToMemberVariableName(serviceIdentifier)),
				new CodeTypeOfExpression(node.FullName),
				new CodePrimitiveExpression(node.Area),
				new CodePrimitiveExpression(naming.ToControllerName(node.Name)),
				new CodePrimitiveExpression(wizardStepPage),
				createMethodSignature,
				new CodeArrayCreateExpression(source[typeof (ActionArgument)], 0)
			};

			return new CodeMethodInvokeExpression(
				new CodeMethodReferenceExpression(
					new CodePropertyReferenceExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), naming.ToMemberVariableName(serviceIdentifier)),
						"ControllerReferenceFactory"),
					"CreateActionReference"),
				constructionArguments);
		}
Пример #4
0
        // Generates a codedom instantiation expression: new foo() or new foo[x].
        public static CodeExpression Emit(Instantiation instantiation)
        {
            // Array instantiation needs a different treatment.
            if (instantiation.IsArray)
            {
                var c = new CodeArrayCreateExpression();

                c.CreateType = new CodeTypeReference(instantiation.Name);
                c.SizeExpression = CodeDomEmitter.EmitCodeExpression(instantiation.Parameters.ChildExpressions[0]);
                return c;
            }
            else // Non-array instantiation
            {
                var c = new CodeObjectCreateExpression();

                // The type that is being created
                var createType = new CodeTypeReference(instantiation.Name);

                // Apply the generic type names, if any.
                foreach (var g in instantiation.GenericTypes)
                {
                    createType.TypeArguments.Add(new CodeTypeReference(g));
                }
                c.CreateType = createType;

                // Translate the instantiation parameters.
                foreach (var a in instantiation.Parameters.ChildExpressions)
                    c.Parameters.Add(CodeDomEmitter.EmitCodeExpression(a));

                return c;
            }
        }
        public override void OnProcessGeneratedCode(ControlBuilder controlBuilder, CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod, System.Collections.IDictionary additionalState)
        {
            // only run this once during page compilation, and only use this one builder (so that we don't get master pages, etc.)
            if (controlBuilder.GetType() == typeof(FileLevelPageControlBuilder))
            {
                // the page will only contain one namespace and one type
                var ns = codeCompileUnit.Namespaces.Cast<CodeNamespace>().FirstOrDefault();
                if (ns != null)
                {
                    var type = ns.Types.Cast<CodeTypeDeclaration>().FirstOrDefault();
                    if (type != null)
                    {
                        /* When this is output, it will inject this into every page:
                         *
                         * protected override PageStatePersister PageStatePersister {
                         *   get { return new CompressedHiddenFieldPageStatePersister(this); }
                         * }
                         *
                         */
                        CodeMemberProperty property = new CodeMemberProperty()
                        {
                            Name = "PageStatePersister",
                            HasGet = true,
                            Attributes = MemberAttributes.Override | MemberAttributes.Family,
                            Type = new CodeTypeReference(typeof(PageStatePersister))
                        };
                        var newObj = new CodeObjectCreateExpression(typeof(CompressedHiddenFieldPageStatePersister), new CodeThisReferenceExpression());
                        property.GetStatements.Add(new CodeMethodReturnStatement(newObj));
                        type.Members.Add(property);
                    }
                }
            }

            base.OnProcessGeneratedCode(controlBuilder, codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod, additionalState);
        }
 internal static void AddCallbackImplementation(CodeTypeDeclaration codeClass, string callbackName, string handlerName, string handlerArgs, bool methodHasOutParameters)
 {
     CodeFlags[] parameterFlags = new CodeFlags[1];
     CodeMemberMethod method = AddMethod(codeClass, callbackName, parameterFlags, new string[] { typeof(object).FullName }, new string[] { "arg" }, typeof(void).FullName, null, (CodeFlags) 0);
     CodeEventReferenceExpression left = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), handlerName);
     CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
     CodeStatement[] trueStatements = new CodeStatement[2];
     trueStatements[0] = new CodeVariableDeclarationStatement(typeof(InvokeCompletedEventArgs), "invokeArgs", new CodeCastExpression(typeof(InvokeCompletedEventArgs), new CodeArgumentReferenceExpression("arg")));
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression("invokeArgs");
     CodeObjectCreateExpression expression4 = new CodeObjectCreateExpression();
     if (methodHasOutParameters)
     {
         expression4.CreateType = new CodeTypeReference(handlerArgs);
         expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Results"));
     }
     else
     {
         expression4.CreateType = new CodeTypeReference(typeof(AsyncCompletedEventArgs));
     }
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Error"));
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Cancelled"));
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "UserState"));
     trueStatements[1] = new CodeExpressionStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), handlerName), new CodeExpression[] { new CodeThisReferenceExpression(), expression4 }));
     method.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[0]));
 }
Пример #7
0
        public override object Serialize(IDesignerSerializationManager manager, object value) {
            var baseSerializer = (CodeDomSerializer)manager
                .GetSerializer(typeof(ResourceManagerSetter).BaseType, typeof(CodeDomSerializer));
            object codeObject = baseSerializer.Serialize(manager, value);

            var statements = codeObject as CodeStatementCollection;
            if (statements != null) {
                CodeExpression leftCodeExpression = new CodeVariableReferenceExpression("resources");
                var classTypeDeclaration = (CodeTypeDeclaration)manager.GetService(typeof(CodeTypeDeclaration));
                CodeExpression typeofExpression = new CodeTypeOfExpression(classTypeDeclaration.Name);
                CodeExpression rightCodeExpression =
                    new CodeObjectCreateExpression(typeof(XafComponentResourceManager),
                                                                  new[] { typeofExpression });
                //CodeExpression rightCodeExpression =
                //    new CodeTypeReferenceExpression(
                //        "new DevExpress.ExpressApp.Win.Templates"),
                //        "XafComponentResourceManager", new[] { typeofExpression });

                statements.Insert(0, new CodeAssignStatement(leftCodeExpression, rightCodeExpression));
            }

            return codeObject;


        }
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeObjectCreateExpression coce = new CodeObjectCreateExpression ();
			Assert.AreEqual ("System.Void", coce.CreateType.BaseType, "CreateType.BaseType");
			coce.CreateType = new CodeTypeReference ("System.Int32");
			Assert.AreEqual (0, coce.Parameters.Count, "Parameters");
		}
        public void AssignParametersCheckCreatorParameters()
        {
            var testClass = new CodeTypeDeclaration();
            var creator = new CodeObjectCreateExpression();

            // standard parameterless ctor, "public ComposeMeCtorVoid()"
            testObject.BuildTestObject(MemberVisibility.Public);
            testObject.AssignParameters(testClass, creator);
            var actualCreatorParameters = creator.Parameters.OfType<CodeFieldReferenceExpression>().ToArray();
            Assert.Count(0, actualCreatorParameters);

            // with a constructor from "public ComposeMeTwoCtor(string para1, int para2)"
            testClass = new CodeTypeDeclaration();
            CreateTestObject(typeof(ComposeMeTwoCtor));
            testObject.BuildTestObject(MemberVisibility.Public);
            testObject.AssignParameters(testClass, creator);

            actualCreatorParameters = creator.Parameters.OfType<CodeFieldReferenceExpression>().ToArray();
            Assert.Count(2, actualCreatorParameters);

            var expected = "para1";
            var actual = actualCreatorParameters[0].FieldName;
            Assert.AreEqual(expected, actual);

            expected = "para2";
            actual = actualCreatorParameters[1].FieldName;
            Assert.AreEqual(expected, actual);
        }
        private void Process(ref CodeObject target, CodeObject parent, int indent)
        {
            CodeMethodInvokeExpression methodInvokeExpr = target as CodeMethodInvokeExpression;

            if (methodInvokeExpr != null &&
                methodInvokeExpr.Method.TargetObject == null &&
                StringUtils.CaseInsensitiveEquals(methodInvokeExpr.Method.MethodName, "CreateObject") &&
                methodInvokeExpr.Parameters.Count == 1)
            {
                CodePrimitiveExpression primitiveExpr = methodInvokeExpr.Parameters[0] as CodePrimitiveExpression;

                if (primitiveExpr != null)
                {
                    string progId = primitiveExpr.Value as string;

                    if (progId != null)
                    {
                        Type type = (_importer == null
                                         ? Type.GetTypeFromProgID(progId)
                                         : _importer.ImportProgId(progId));

                        if (type != null)
                        {
                            target = new CodeObjectCreateExpression(Utils.CreateTypeReference(type));
                        }
                    }
                }
            }
        }
Пример #11
0
        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;
        }
Пример #12
0
        public static Tuple<CodeVariableDeclarationStatement, CodeVariableReferenceExpression> CreateVariable(CodeTypeReference typeReference, string name, params CodeExpression[] constructorParameters)
        {
            CodeObjectCreateExpression initializer = new CodeObjectCreateExpression(typeReference, constructorParameters);
            CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeReference, name, initializer);
            CodeVariableReferenceExpression reference = new CodeVariableReferenceExpression(name);

            return new Tuple<CodeVariableDeclarationStatement, CodeVariableReferenceExpression>(statement, reference);
        }
Пример #13
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeTypeReference create = new CodeTypeReference ("System.Int32");
			CodeExpression[] parameters = new CodeExpression[1] { new CodeExpression () };
			CodeObjectCreateExpression coce = new CodeObjectCreateExpression (create, parameters);
			Assert.AreSame (create, coce.CreateType, "CreateType");
			coce.CreateType = new CodeTypeReference ("System.Void");
			Assert.AreEqual (1, coce.Parameters.Count, "Parameters");
		}
 public static CodeObjectCreateExpression Clone(this CodeObjectCreateExpression expression)
 {
     if (expression == null) return null;
     CodeObjectCreateExpression e = new CodeObjectCreateExpression();
     e.CreateType = expression.CreateType.Clone();
     e.Parameters.AddRange(expression.Parameters.Clone());
     e.UserData.AddRange(expression.UserData);
     return e;
 }
Пример #15
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 void BuildControlSkinMember()
 {
     int count = this._controlSkinBuilderEntryList.Count;
     CodeMemberField field = new CodeMemberField(typeof(HybridDictionary).FullName, "__controlSkins");
     CodeObjectCreateExpression expression = new CodeObjectCreateExpression(typeof(HybridDictionary), new CodeExpression[0]);
     expression.Parameters.Add(new CodePrimitiveExpression(count));
     field.InitExpression = expression;
     base._sourceDataClass.Members.Add(field);
 }
Пример #17
0
 public void Init()
 {
     functionalConstructor = null;
     staticConstructor = null;
     hasElementWildCards = false;
     contentModelExpression = null;
     if (propertyNameTypeTable != null) {
         propertyNameTypeTable.Clear();
     }
 }
		private CodeStatement createChildContainerStatement(CodeVariableReferenceExpression picoContainer,
		                                                    CodeVariableReferenceExpression childContainer)
		{
			CodeExpression[] arguments = new CodeExpression[] {picoContainer};
			CodeExpression rightHandSide = new CodeObjectCreateExpression(Constants.DefaultPicoContainerType, arguments);

			return new CodeVariableDeclarationStatement(Constants.DefaultPicoContainerType,
			                                            childContainer.VariableName,
			                                            rightHandSide);
		}
        /// <summary>
        /// Generates code for value
        /// </summary>
        /// <param name="parentClass">The parent class.</param>
        /// <param name="method">The method.</param>
        /// <param name="value">The value.</param>
        /// <param name="baseName">Name of the base.</param>
        /// <param name="dictionary">The dictionary.</param>
        /// <returns></returns>
        public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null)
        {                        
            Color color = (Color)value;
            CodeObjectCreateExpression colorExpr = new CodeObjectCreateExpression(
                    "ColorW",
                    new CodePrimitiveExpression(color.R),
                    new CodePrimitiveExpression(color.G),
                    new CodePrimitiveExpression(color.B),
                    new CodePrimitiveExpression(color.A));

            return colorExpr;
        }
 public TypescriptObjectCreateExpression(
     IExpressionFactory expressionFactory, 
     CodeObjectCreateExpression codeExpression, 
     CodeGeneratorOptions options, 
     ITypescriptTypeMapper typescriptTypeMapper)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     _typescriptTypeMapper = typescriptTypeMapper;
     System.Diagnostics.Debug.WriteLine("TypescriptObjectCreateExpression Created");
 }
 internal override CodeExpression Clone(CodeExpression expression)
 {
     CodeObjectCreateExpression expression2 = (CodeObjectCreateExpression) expression;
     CodeObjectCreateExpression expression3 = new CodeObjectCreateExpression {
         CreateType = TypeReferenceExpression.CloneType(expression2.CreateType)
     };
     foreach (CodeExpression expression4 in expression2.Parameters)
     {
         expression3.Parameters.Add(RuleExpressionWalker.Clone(expression4));
     }
     return expression3;
 }
        internal static CodeExpression MaterializeSimpleTypeDef(
            ClrSimpleTypeInfo typeInfo, 
            Dictionary<XmlSchemaObject, string> nameMappings,
            LinqToXsdSettings settings)  
        {
            CodeObjectCreateExpression simpleTypeCreate = null;
            CodeExpressionCollection expressions = null;
            switch(typeInfo.Variety) {
                case XmlSchemaDatatypeVariety.Atomic:
                    simpleTypeCreate = new CodeObjectCreateExpression(
                        Constants.AtomicSimpleTypeValidator);
                    expressions = simpleTypeCreate.Parameters;
                    expressions.Add(CreateGetBuiltInSimpleType(typeInfo.TypeCode));
                    expressions.Add(CreateFacets(typeInfo));
                break;
                
                case XmlSchemaDatatypeVariety.List:
                    simpleTypeCreate = new CodeObjectCreateExpression(
                        Constants.ListSimpleTypeValidator);
                    expressions = simpleTypeCreate.Parameters;
                    expressions.Add(CreateGetBuiltInSimpleType(typeInfo.TypeCode));
                    expressions.Add(CreateFacets(typeInfo));
                    
                    ListSimpleTypeInfo listType = typeInfo as ListSimpleTypeInfo;
                    ClrSimpleTypeInfo itemType = listType.ItemType;
                    expressions.Add(CreateSimpleTypeDef(
                        itemType, nameMappings, settings, true));
                break;
                
                case XmlSchemaDatatypeVariety.Union:
                    simpleTypeCreate = new CodeObjectCreateExpression(
                        Constants.UnionSimpleTypeValidator);
                    expressions = simpleTypeCreate.Parameters;
                    expressions.Add(CreateGetBuiltInSimpleType(typeInfo.TypeCode));
                    expressions.Add(CreateFacets(typeInfo));

                    UnionSimpleTypeInfo unionType = typeInfo as UnionSimpleTypeInfo;
                    CodeArrayCreateExpression memberTypeCreate = 
                        new CodeArrayCreateExpression();
                    memberTypeCreate.CreateType = new CodeTypeReference(
                        Constants.SimpleTypeValidator);
                    foreach (ClrSimpleTypeInfo st in unionType.MemberTypes) 
                    {
                        memberTypeCreate.Initializers.Add(CreateSimpleTypeDef(
                            st, nameMappings, settings, true));
                    }
                    expressions.Add(memberTypeCreate);
                break;
            }
            return simpleTypeCreate;
        }
        private void SetupAsyncTestClass(TestClassGenerationContext generationContext)
        {
            generationContext.TestClass.BaseTypes.Add(new CodeTypeReference(ASYNCTEST_INTERFACE));

            //AsyncTestRunner.RegisterAsyncTestExecutor(testRunner, new TechTalk.SpecFlow.Async.SilverlightAsyncTestExecutor(this));

            var nawSilverlightAsyncTestExecutorExpr = new CodeObjectCreateExpression("TechTalk.SpecFlow.Async.SilverlightAsyncTestExecutor", new CodeThisReferenceExpression());

            var registerAsyncExpression = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression(typeof(AsyncTestRunner)), 
                "RegisterAsyncTestExecutor", 
                new CodeVariableReferenceExpression("testRunner"),
                nawSilverlightAsyncTestExecutorExpr);

            generationContext.TestInitializeMethod.Statements.Add(new CodeExpressionStatement(registerAsyncExpression));
        }
		public void Constructor0 ()
		{
			CodeObjectCreateExpression coce = new CodeObjectCreateExpression ();

			Assert.IsNotNull (coce.CreateType, "#1");
			Assert.AreEqual (typeof (void).FullName, coce.CreateType.BaseType, "#2");
			Assert.IsNotNull (coce.Parameters, "#3");
			Assert.AreEqual (0, coce.Parameters.Count, "#4");

			CodeTypeReference type = new CodeTypeReference ("mono");
			coce.CreateType = type;
			Assert.IsNotNull (coce.CreateType, "#8");
			Assert.AreSame (type, coce.CreateType, "#9");

			coce.CreateType = null;
			Assert.IsNotNull (coce.CreateType, "#10");
			Assert.AreEqual (typeof (void).FullName, coce.CreateType.BaseType, "#11");
		}
Пример #25
0
        private void GenerateCode()
        {
            keys.ToObservable();
            var cgo = new CodeGeneratorOptions
                          {
                              BracingStyle = "C",
                              BlankLinesBetweenMembers = false
                          };
            using (var provider = new CSharpCodeProvider())
            {
                var method = new CodeMemberMethod
                {
                    Name = "KeyStream",
                    ReturnType = new CodeTypeReference(typeof(IObservable<InterceptKeyEventArgs>))
                };

                var player =
                    new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(KeyPlayer)), "keys",
                    new CodeObjectCreateExpression(typeof(KeyPlayer)));
                method.Statements.Add(player);
                foreach (var interceptKeyEventArgse in keys)
                {
                    var key = new CodeObjectCreateExpression(new CodeTypeReference(typeof(InterceptKeyEventArgs)),
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(Keys)), interceptKeyEventArgse.Key.ToString()),
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(KeyDirection)), interceptKeyEventArgse.KeyDirection.ToString()),
                    new CodePrimitiveExpression(interceptKeyEventArgse.AltPressed),
                    new CodePrimitiveExpression(interceptKeyEventArgse.ControlPressed),
                    new CodePrimitiveExpression(interceptKeyEventArgse.ShiftPressed));

                    var keyPress = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("keys"), "Add", key);
                    method.Statements.Add(keyPress);
                }
                method.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("keys")));

                var sb = new StringBuilder();
                using(var stringWriter = new StringWriter(sb))
                {
                    provider.GenerateCodeFromMember(method, stringWriter, cgo);
                }
                textBox.Text = sb.ToString();
            }
        }
 private CodeStatement BuildControlSkinAssignmentStatement(ControlBuilder builder, string skinID)
 {
     Type controlType = builder.ControlType;
     string name = base.GetMethodNameForBuilder(BaseTemplateCodeDomTreeGenerator.buildMethodPrefix, builder) + "_skinKey";
     CodeMemberField field = new CodeMemberField(typeof(object), name) {
         Attributes = MemberAttributes.Private | MemberAttributes.Static
     };
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression {
         Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(PageTheme)), "CreateSkinKey")
     };
     expression.Parameters.Add(new CodeTypeOfExpression(controlType));
     expression.Parameters.Add(new CodePrimitiveExpression(skinID));
     field.InitExpression = expression;
     base._sourceDataClass.Members.Add(field);
     CodeFieldReferenceExpression targetObject = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "__controlSkins");
     CodeIndexerExpression left = new CodeIndexerExpression(targetObject, new CodeExpression[] { new CodeVariableReferenceExpression(name) });
     CodeDelegateCreateExpression expression4 = new CodeDelegateCreateExpression(this._controlSkinDelegateType, new CodeThisReferenceExpression(), base.GetMethodNameForBuilder(BaseTemplateCodeDomTreeGenerator.buildMethodPrefix, builder));
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(this._controlSkinType, new CodeExpression[0]);
     right.Parameters.Add(new CodeTypeOfExpression(controlType));
     right.Parameters.Add(expression4);
     return new CodeAssignStatement(left, right);
 }
		public void Constructor1 ()
		{
			CodeTypeReference type = new CodeTypeReference ("mono");
			CodeExpression expression1 = new CodeExpression ();
			CodeExpression expression2 = new CodeExpression ();

			CodeObjectCreateExpression coce = new CodeObjectCreateExpression (
				type, expression1, expression2);
			Assert.IsNotNull (coce.CreateType, "#1");
			Assert.AreSame (type, coce.CreateType, "#2");
			Assert.IsNotNull (coce.Parameters, "#3");
			Assert.AreEqual (2, coce.Parameters.Count, "#4");
			Assert.AreEqual (0, coce.Parameters.IndexOf(expression1), "#5");
			Assert.AreEqual (1, coce.Parameters.IndexOf(expression2), "#6");

			coce = new CodeObjectCreateExpression ((CodeTypeReference) null, 
				expression1);
			Assert.IsNotNull (coce.CreateType, "#7");
			Assert.AreEqual (typeof (void).FullName, coce.CreateType.BaseType, "#8");
			Assert.IsNotNull (coce.Parameters, "#9");
			Assert.AreEqual (1, coce.Parameters.Count, "#10");
			Assert.AreEqual (0, coce.Parameters.IndexOf(expression1), "#11");
		}
		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;
		}
        /// <summary>
        /// Generates code for value
        /// </summary>
        /// <param name="parentClass">The parent class.</param>
        /// <param name="method">The method.</param>
        /// <param name="value">The value.</param>
        /// <param name="baseName">Name of the base.</param>
        /// <param name="dictionary">The dictionary.</param>
        /// <returns></returns>
        public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null)
        {
            CodeExpression valueExpression = null;
            if (value != null)
            {
                Thickness thickness = (Thickness)value;

                if (thickness.Left == thickness.Top && thickness.Top == thickness.Right && thickness.Right == thickness.Bottom)
                {
                    valueExpression = new CodeObjectCreateExpression("Thickness", new CodePrimitiveExpression((float)thickness.Left));
                }
                else
                {
                    valueExpression = new CodeObjectCreateExpression(
                                "Thickness",
                                new CodePrimitiveExpression((float)thickness.Left),
                                new CodePrimitiveExpression((float)thickness.Top),
                                new CodePrimitiveExpression((float)thickness.Right),
                                new CodePrimitiveExpression((float)thickness.Bottom));
                }
            }

            return valueExpression;
        }
        private void GenerateCodeFromObjectCreateExpression(CodeObjectCreateExpression e, TextWriter w,
            CodeGeneratorOptions o)
        {
            w.Write("New-Object -TypeName " + e.CreateType.BaseType);

            if (e.Parameters.Count > 0)
            {
                w.Write(" -ArgumentList @(");
                int count = e.Parameters.Count;
                foreach (CodeExpression parameter in e.Parameters)
                {
                    count--;
                    GenerateCodeFromExpression(parameter, w, o);
                    if (count > 0)
                    {
                        w.Write(",");
                    }
                }
                w.Write(")");
            }
        }
Пример #31
0
 protected override void GenerateObjectCreateExpression(System.CodeDom.CodeObjectCreateExpression e)
 {
     Output.Write("new ");
     OutputType(e.CreateType);
     OutputParameters(e.Parameters);
 }