Inheritance: CodeTypeMember
        public CodeTypeDeclaration CreateClass()
        {
            CodeTypeDeclaration declaration = new CodeTypeDeclaration(_helperClassName);

            declaration.IsClass = true;
            declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            declaration.BaseTypes.Add(typeof(DataProviderHelperBase));
            declaration.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(EditorBrowsableAttribute)),
                    new CodeAttributeArgument(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(EditorBrowsableState)),
                            EditorBrowsableState.Never.ToString()
                        )
                    )
                )
            );

            AddConstructor(declaration);
            AddInterfaceTypeProperty(declaration);
            AddDataIdTypeProperty(declaration);
            AddCreateDataIdFunctionMethod(declaration);
            AddValidateDataTypeMethod(declaration);
            AddCreateNewElementMethod(declaration);

            return declaration;
        }
Ejemplo n.º 2
0
        public void DecorateClass(CodeTypeDeclaration typeDeclaration,
            ISchema schema,
            IDictionary<JsonSchema, SchemaImplementationDetails> implDetails,
            INestedClassProvider internalClassProvider)
        {
            typeDeclaration.ThrowIfNull("typeDeclaration");
            schema.ThrowIfNull("schema");
            implDetails.ThrowIfNull("implDetails");
            internalClassProvider.ThrowIfNull("internalClassProvider");

            JsonSchema details = schema.SchemaDetails;
            details.ThrowIfNull("schemaDetails");

            // Check if this decorator can be applied to the schema);
            if (details.Type != JsonSchemaType.Array)
            {
                return;
            }

            if (details.Items == null || details.Items.Count != 1)
            {
                logger.Warning("Found array scheme of unhandled type. {0}", details);
                return; // not supported
            }

            // Generate or find the nested type
            JsonSchema itemScheme = details.Items[0];
            SchemaImplementationDetails implDetail = implDetails[itemScheme];
            implDetail.ProposedName = "Entry"; // Change the name to a custom one.
            CodeTypeReference item = SchemaDecoratorUtil.GetCodeType(itemScheme, implDetail, internalClassProvider);

            // Insert the base type before any interface declaration
            var baseType = string.Format("List<{0}>", item.BaseType);
            typeDeclaration.BaseTypes.Insert(0, new CodeTypeReference(baseType));
        }
        private void EmitField(CodeTypeDeclaration typeDecl, CodeTypeReference fieldType, bool hasDefault)
        {
            CodeMemberField memberField = new CodeMemberField(fieldType, Utils.FieldNameFromPropName(Item.Name));
            memberField.Attributes = MemberAttributes.Private;

            AttributeEmitter.AddGeneratedCodeAttribute(memberField);

            if (hasDefault)
            {
                if (this.Generator.UseDataServiceCollection)
                {
                    // new DataServiceCollection<T>(null, System.Data.Services.Client.TrackingMode.None, null, null, null);
                    // declare type is DataServiceCollection<T>
                    Debug.Assert(fieldType.TypeArguments.Count == 1, "Declare type is non generic.");

                    // new DataServiceCollection<[type]>(null, TrackingMode.None)
                    memberField.InitExpression = new CodeObjectCreateExpression(
                        fieldType,
                        new CodePrimitiveExpression(null),
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(System.Data.Services.Client.TrackingMode)),
                            "None"));
                }
                else
                {
                    memberField.InitExpression = new CodeObjectCreateExpression(fieldType);
                }
            }

            typeDecl.Members.Add(memberField);
        }
Ejemplo n.º 4
0
        public void GenerateCodeTypeDeclaration(CodeDomProvider provider, CodeGeneratorOptions generatorOptions,
                                                string wrapperName, out CodeTypeDeclaration ctd, out string ns)
        {
            var registerAtt = new CodeTypeReference(wrapperName + ".Foundation.RegisterAttribute");

            ctd = new System.CodeDom.CodeTypeDeclaration()
            {
                IsPartial = true,
            };

            if (Outlets.Any(o => o.IsDesigner) || Actions.Any(a => a.IsDesigner))
            {
                AddWarningDisablePragmas(ctd, provider);
            }

            var dotIdx = CliName.LastIndexOf('.');

            if (dotIdx > 0)
            {
                ns       = CliName.Substring(0, dotIdx);
                ctd.Name = CliName.Substring(dotIdx + 1);
            }
            else
            {
                ctd.Name = CliName;
                ns       = null;
            }
            if (IsRegisteredInDesigner)
            {
                AddAttribute(ctd.CustomAttributes, registerAtt, ObjCName);
            }

            GenerateActionsOutlets(provider, ctd, wrapperName);
        }
Ejemplo n.º 5
0
        private static void AddConstructor(CodeTypeDeclaration declaration)
        {
            CodeConstructor constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Public;

            constructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(IDbConnection), "connection"));

            constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("connection"));

            constructor.CustomAttributes.Add(new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
                ));

            constructor.Statements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression(SqlDataContextHelperClassName),
                    new CodeObjectCreateExpression(
                        typeof(SqlDataContextHelperClass),
                        new CodeExpression[] {
                            new CodeThisReferenceExpression()
                        }
                    )
                ));

            declaration.Members.Add(constructor);
        }
        internal CodeTypeMemberCollection GenerateParameterProperty(IParameter parameter,
            IMethod method,
            CodeTypeDeclaration resourceClass,
            IEnumerable<string> usedNames)
        {
            // Get the name and return type of this parameter.
            string name = parameter.Name;
            CodeTypeReference returnType = ResourceBaseGenerator.GetParameterTypeReference(
                resourceClass, parameter);

            // Generate the property and field.
            CodeTypeMemberCollection newMembers = DecoratorUtil.CreateAutoProperty(
                name, parameter.Description, returnType, usedNames, parameter.IsRequired);

            // Add the KeyAttribute to the property.
            foreach (CodeTypeMember member in newMembers)
            {
                CodeMemberProperty property = member as CodeMemberProperty;
                if (property == null)
                {
                    continue;
                }

                // Declare the RequestParameter attribute.
                CodeTypeReference attributeType = new CodeTypeReference(typeof(RequestParameterAttribute));
                CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(attributeType);
                attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(parameter.Name)));
                property.CustomAttributes.Add(attribute);
            }

            return newMembers;
        }
        protected override void ProcessProperty(CodeTypeDeclaration type, CodeMemberField field, CodeMemberProperty property)
        {
            if (property.Type.ArrayElementType == null) return; // Is array?

            if (property.Name == "Items" || property.Name == "ItemsElementName") return;

            CodeTypeReference genericType = new CodeTypeReference("System.Collections.Generic.List", new CodeTypeReference(property.Type.BaseType));

            property.Type = genericType;
            if (field != null) {
                field.Type = genericType;

                property.GetStatements.Insert(0,
                    // if
                    new CodeConditionStatement(
                        // field == null
                        new CodeBinaryOperatorExpression(
                            new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name),
                            CodeBinaryOperatorType.IdentityEquality,
                            new CodePrimitiveExpression(null)),
                        // field = new List<T>();
                        new CodeAssignStatement(
                            new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name),
                            new CodeObjectCreateExpression(genericType))));
            }
        }
 internal CodeTypeDeclaration GenerateAdapterManager(DesignDataSource dataSource, CodeTypeDeclaration dataSourceClass)
 {
     TypeAttributes @public = TypeAttributes.Public;
     foreach (DesignTable table in dataSource.DesignTables)
     {
         if ((table.DataAccessorModifier & TypeAttributes.Public) != TypeAttributes.Public)
         {
             @public = table.DataAccessorModifier;
         }
     }
     CodeTypeDeclaration dataComponentClass = CodeGenHelper.Class("TableAdapterManager", true, @public);
     dataComponentClass.Comments.Add(CodeGenHelper.Comment("TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios", true));
     dataComponentClass.BaseTypes.Add(CodeGenHelper.GlobalType(typeof(Component)));
     dataComponentClass.CustomAttributes.Add(CodeGenHelper.AttributeDecl("System.ComponentModel.DesignerCategoryAttribute", CodeGenHelper.Str("code")));
     dataComponentClass.CustomAttributes.Add(CodeGenHelper.AttributeDecl("System.ComponentModel.ToolboxItem", CodeGenHelper.Primitive(true)));
     dataComponentClass.CustomAttributes.Add(CodeGenHelper.AttributeDecl("System.ComponentModel.DesignerAttribute", CodeGenHelper.Str("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")));
     dataComponentClass.CustomAttributes.Add(CodeGenHelper.AttributeDecl(typeof(HelpKeywordAttribute).FullName, CodeGenHelper.Str("vs.data.TableAdapterManager")));
     new TableAdapterManagerMethodGenerator(this.dataSourceGenerator, dataSource, dataSourceClass).AddEverything(dataComponentClass);
     try
     {
         CodeGenerator.ValidateIdentifiers(dataComponentClass);
     }
     catch (Exception)
     {
     }
     return dataComponentClass;
 }
 protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value)
 {
     if (manager == null)
     {
         throw new ArgumentNullException("manager");
     }
     if (typeDecl == null)
     {
         throw new ArgumentNullException("typeDecl");
     }
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod;
     if (method == null)
     {
         method = new CodeMemberMethod {
             Name = "InitializeComponent",
             Attributes = MemberAttributes.Private
         };
         typeDecl.UserData[_initMethodKey] = method;
         CodeConstructor constructor = new CodeConstructor {
             Attributes = MemberAttributes.Public
         };
         constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitializeComponent", new CodeExpression[0]));
         typeDecl.Members.Add(constructor);
     }
     return method;
 }
 public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)
 {
     if (!String.IsNullOrWhiteSpace(Inherits))
     {
         derivedType.BaseTypes[0] = new CodeTypeReference(Inherits);
     }
 }
Ejemplo n.º 11
0
        public CodeObject CreateCodeObject()
        {
            var conditions = _types
                .Select(CreateNumberSetValueCondition)
                .Concat(_types
                    .Concat(_arrayTypes)
                    .Select(CreateArraySetValueCondition));

            var firstCondition = conditions.First();
            var currentCondition = firstCondition;

            foreach (var condition in conditions.Skip(1))
            {
                currentCondition.FalseStatements.Add(condition);
                currentCondition = condition;
            }

            currentCondition.FalseStatements.Add(CodeHelper.Return(CodeHelper.False()));

            var type = new CodeTypeDeclaration("AphidObject") { IsPartial = true };
            type.Members.Add(TrySetProperty(firstCondition));

            var ns = new CodeNamespace();
            ns.Imports.Add(new CodeNamespaceImport("System.Linq"));
            ns.Name = "Components.Aphid.Interpreter";
            ns.Types.Add(type);

            var unit = new CodeCompileUnit();
            unit.Namespaces.Add(ns);

            return unit;
        }
Ejemplo n.º 12
0
        public System.CodeDom.CodeTypeDeclaration ProcessImportedType(
            System.CodeDom.CodeTypeDeclaration typeDeclaration,
            System.CodeDom.CodeCompileUnit compileUnit
            )
        {
            Console.WriteLine("ProcessImportedType called for {0}.", typeDeclaration.Name);
            object typeCustomData = typeDeclaration.UserData[typeof(IDataContractSurrogate)];

            if (typeDeclaration.Comments.Count == 0)
            {
                typeDeclaration.Comments.AddRange(Formatter.FormatComments(typeCustomData.ToString()));
            }

            foreach (CodeTypeMember member in typeDeclaration.Members)
            {
                object memberCustomData = member.UserData[typeof(IDataContractSurrogate)];
                if (memberCustomData != null &&
                    memberCustomData is string &&
                    member.Comments.Count == 0)
                {
                    member.Comments.AddRange(
                        Formatter.FormatComments(memberCustomData.ToString())
                        );
                }
            }
            return(typeDeclaration);
        }
Ejemplo n.º 13
0
        public CodeTypeDeclaration ToClass()
        {
            var cs = new CodeTypeDeclaration(this.Name.Substring(0, this.Name.Length - 1));
            cs.IsClass = true;
            cs.IsPartial = true;
            //cs.TypeAttributes = (cs.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NotPublic;

            var pks = (from c in this.Columns
                      where c.IsPrimaryKey
                      select c).ToArray();

            if (pks.Length == 1 && pks[0].Type == "System.Guid" && pks[0].Member == "ID")
            {
                cs.BaseTypes.Add("IStandardRecord");
            }
            else
            {
                cs.BaseTypes.Add("IRecord");
            }

            cs.Members.Add(RegisterColums());

            var indexer = GetIndexer();

            cs.Members.Add(indexer);

            return cs;
        }
Ejemplo n.º 14
0
        public void SetTestFixtureSetup(CodeMemberMethod fixtureSetupMethod)
        {
            // xUnit uses IUseFixture<T> on the class

            fixtureSetupMethod.Attributes |= MemberAttributes.Static;

            _currentFixtureTypeDeclaration = new CodeTypeDeclaration("FixtureData");
            _currentTestTypeDeclaration.Members.Add(_currentFixtureTypeDeclaration);

            var fixtureDataType = 
                CodeDomHelper.CreateNestedTypeReference(_currentTestTypeDeclaration, _currentFixtureTypeDeclaration.Name);
            
            var useFixtureType = new CodeTypeReference(IUSEFIXTURE_INTERFACE, fixtureDataType);
            CodeDomHelper.SetTypeReferenceAsInterface(useFixtureType);

            _currentTestTypeDeclaration.BaseTypes.Add(useFixtureType);

            // public void SetFixture(T) { } // explicit interface implementation for generic interfaces does not work with codedom

            CodeMemberMethod setFixtureMethod = new CodeMemberMethod();
            setFixtureMethod.Attributes = MemberAttributes.Public;
            setFixtureMethod.Name = "SetFixture";
            setFixtureMethod.Parameters.Add(new CodeParameterDeclarationExpression(fixtureDataType, "fixtureData"));
            setFixtureMethod.ImplementationTypes.Add(useFixtureType);
            _currentTestTypeDeclaration.Members.Add(setFixtureMethod);

            // public <_currentFixtureTypeDeclaration>() { <fixtureSetupMethod>(); }
            CodeConstructor ctorMethod = new CodeConstructor();
            ctorMethod.Attributes = MemberAttributes.Public;
            _currentFixtureTypeDeclaration.Members.Add(ctorMethod);
            ctorMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(new CodeTypeReference(_currentTestTypeDeclaration.Name)),
                    fixtureSetupMethod.Name));
        }
 public void SetUp()
 {
     Generator = new StructureGenerator(Configuration);
     Configuration = CodeGeneratorConfiguration.Create().MediaTypes;
     Candidate = Type = new CodeTypeDeclaration();
     ContentType = new MediaType();
 }
        /// <summary>Modifies the code document object model prior to the contract generation process.</summary>
        /// <param name="context">The code generated context to use to modify the code document prior to generation.</param>
        public void GenerateContract(ServiceContractGenerationContext context)
        {
            // Disable generation of the Event-Based Async Pattern, which has a conflicting naming scheme.
            context.ServiceContractGenerator.Options &= ~ServiceContractGenerationOptions.EventBasedAsynchronousMethods;

            string contractName = context.Contract.Name;
            string clientTypeName = TaskAsyncWsdlImportExtension.DeriveClientTypeName(contractName);

            // Look up the client class, and create it if it doesn't already exist.
            if (TaskAsyncWsdlImportExtension.FindClientType(clientTypeName, context.ServiceContractGenerator.TargetCompileUnit.Namespaces) == null)
            {
                // Create the new type
                CodeTypeDeclaration newClient = new CodeTypeDeclaration(clientTypeName)
                {
                    Attributes = MemberAttributes.Public,
                    IsPartial = true
                };
                newClient.BaseTypes.Add(new CodeTypeReference(typeof(ClientBase<>)) { TypeArguments = { new CodeTypeReference(contractName) } });
                newClient.BaseTypes.Add(new CodeTypeReference(contractName));

                // Add the new type to the right namespace
                CodeNamespace contractNamespace = (from ns in context.ServiceContractGenerator.TargetCompileUnit.Namespaces.Cast<CodeNamespace>()
                                                   from type in ns.Types.Cast<CodeTypeDeclaration>()
                                                   where type == context.ContractType
                                                   select ns).FirstOrDefault();
                contractNamespace.Types.Add(newClient);
            }
        }
Ejemplo n.º 17
0
        public void Correct(CodeTypeDeclaration typeDecl)
        {
            foreach (CodeTypeMember typeMember in typeDecl.Members)
            {
                if (typeMember is CodeMemberMethod)
                {
                    CodeMemberMethod memberMethod = (CodeMemberMethod) typeMember;
                    CodeObjectSource source = Utils.GetTypeReferenceSource(memberMethod.ReturnType);

                    if (source == null || source.Target != typeof (void) || source.ArrayRanks.Length > 0)
                    {
                        CorrectStatements(memberMethod.Name, memberMethod.Statements, memberMethod.ReturnType);
                    }
                }
                else if (typeMember is CodeMemberProperty)
                {
                    CodeMemberProperty memberProperty = (CodeMemberProperty) typeMember;

                    if (memberProperty.HasGet)
                    {
                        CorrectStatements(memberProperty.Name, memberProperty.GetStatements, memberProperty.Type);
                    }

                    if (memberProperty.HasSet)
                    {
                        ProcessSetStatements(memberProperty.Name, memberProperty.SetStatements);
                    }
                }
                else if (typeMember is CodeTypeDeclaration)
                {
                    Correct((CodeTypeDeclaration) typeMember);
                }
            }
        }
Ejemplo n.º 18
0
        static CodeNamespace BuildProgram()
        {
            // namespaceの作成
            var ns = new CodeNamespace("MetaWorld");
            // import編成
            var systemImport = new CodeNamespaceImport("System");
            // class作成
            var programClass = new CodeTypeDeclaration("Program");

            // mainメソッドの定義
            var methodMain = new CodeMemberMethod()
            {
                Attributes = MemberAttributes.Static,
                Name = "Main"
            };
            methodMain.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeSnippetExpression("Console"),
                    "WriteLine",
                    new CodePrimitiveExpression("Hello World")
                    )
                );

            // コード構造の編成
            programClass.Members.Add(methodMain);
            ns.Imports.Add(systemImport);
            ns.Types.Add(programClass);
            return ns;
        }
		public void CodeSnippetBlankLines ()
		{
			var opt = new CodeGeneratorOptions () {
				BlankLinesBetweenMembers = false,
				VerbatimOrder = false
			};

			var ccu = new CodeCompileUnit ();
			var ns = new CodeNamespace ("Foo");
			ccu.Namespaces.Add (ns);
			var t = new CodeTypeDeclaration ("Bar");
			ns.Types.Add (t);

			t.Members.Add (new CodeSnippetTypeMember ("#line hidden"));
			t.Members.Add (new CodeSnippetTypeMember ("#line hidden2"));
	
			t.Members.Add (new CodeMemberMethod () { Name = "Foo" });

			using (var sw = new StringWriter ()) {
				new CSharpCodeProvider ().GenerateCodeFromCompileUnit (ccu, sw, opt);
				var str = sw.ToString ();

				Assert.IsFalse (str.Contains ("hidden2private"), "#0");
				Assert.IsTrue (str.Contains( "#line hidden#line hidden2"), "#1");
			}
		}
Ejemplo n.º 20
0
        internal static CodeTypeReference GetParameterTypeReference(CodeTypeDeclaration classDeclaration,
            IParameter param)
        {
            Type underlyingType = GetParameterType(param);
            CodeTypeReference paramTypeRef = new CodeTypeReference(underlyingType);
            bool isValueType = underlyingType.IsValueType;

            // Check if we need to declare a custom type for this parameter.
            // If the parameter is an enum, try finding the matching enumeration in the current class
            if (!param.EnumValues.IsNullOrEmpty())
            {
                // Naming scheme: MethodnameParametername
                CodeTypeReference enumReference = DecoratorUtil.FindFittingEnumeration(
                    classDeclaration, param.EnumValues, param.EnumValueDescriptions);

                if (enumReference != null)
                {
                    paramTypeRef = enumReference;
                    isValueType = true;
                }
            }

            // Check if this is an optional value parameter.
            if (isValueType && !param.IsRequired)
            {
                paramTypeRef = new CodeTypeReference(typeof(Nullable<>))
                {
                    TypeArguments = { paramTypeRef.BaseType }
                };
                // An optional value parameter has to be nullable.
            }

            return paramTypeRef;
        }
        public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() {
            const string expectedPropertyCode = @"
protected Foo.Bar ApplicationInstance {
    get {
        return ((Foo.Bar)(Context.ApplicationInstance));
    }
}
";

            // Arrange
            CodeCompileUnit generatedCode = new CodeCompileUnit();
            CodeNamespace generatedNamespace = new CodeNamespace();
            CodeTypeDeclaration generatedClass = new CodeTypeDeclaration();
            CodeMemberMethod executeMethod = new CodeMemberMethod();
            WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") {
                GlobalAsaxTypeName = "Foo.Bar"
            };

            // Act
            host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod);

            // Assert
            CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty;
            Assert.IsNotNull(property);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            StringBuilder builder = new StringBuilder();
            using(StringWriter writer = new StringWriter(builder)) {
                provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions());
            }

            Assert.AreEqual(expectedPropertyCode, builder.ToString());
        }
Ejemplo n.º 22
0
        private CodeTypeDeclaration CreateClass(ClassDefinition table)
        {
            CodeTypeDeclaration type = new CodeTypeDeclaration();

            type.Name = table.ToString();
            type.IsClass = true;
            type.IsPartial = true;
            type.BaseTypes.Add(new CodeTypeReference(typeof(CsDO.Lib.DataObject)));
            type.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable",
                    new CodeAttributeArgument[] { }));
            if (!String.IsNullOrEmpty(table.Alias) && !table.Table.Equals(table.Alias))
            {
                type.CustomAttributes.Add(new CodeAttributeDeclaration("Table",
                    new CodeAttributeArgument[] {
                            new CodeAttributeArgument(new CodePrimitiveExpression(table.Table))
                        }));
            }

            #region class comments
            type.Comments.AddRange(InsertDocumentation(Documetation.Remarks, new string[]
                {
                    "Persistence class that maps table '" + table + "'",
                    "Warning: Each property maps a column, use the attribute",
                    "Column to mark properties that should not be persisted."
                }));
            type.Comments.AddRange(InsertDocumentation(Documetation.SeeAlso, new string[] { "Column" }));
            #endregion

            return type;
        }
Ejemplo n.º 23
0
        public void BuildTest()
        {
            var typeMember = new CodeMemberMethod() { Name = "TypeMemberTest" };
            var propData = mocks.Stub<IBuilderData>();
            Expect.Call(buildcontext.TypeMember).Return(typeMember);
            //Expect.Call(buildcontext.GetBuilderData("Property")).Return(propData);

            // is not relevant ... just a devel-testing call to
            // "var userData = context.GetBuilderData<BuildParametersOfPropertyBuilder>(this);"
            Expect.Call(buildcontext.GetBuilderData<BuildParametersOfPropertyBuilder>(testObject)).Return(null);
            Expect.Call(buildcontext.GetBuilderData("Property")).Return(propData).Repeat.Any();
            var testClass = new CodeTypeDeclaration("TheClass");
            Expect.Call(buildcontext.TestClassDeclaration).Return(testClass).Repeat.Any();
            //Expect.Call(buildcontext.IsProperty).Return(true);
            mocks.ReplayAll();

            testObject.Build(this.buildcontext);

            // Todo: check if only the ending "Test" gets replaced.
            var expected = "TypeMemberNormalBehavior";
            var actual = typeMember.Name;
            Assert.AreEqual(expected, actual);

            mocks.VerifyAll();
        }
        /// <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)
        {
            string bitmapVarName = baseName + "_bm";

            BitmapImage bitmap = value as BitmapImage;
            return CodeComHelper.GenerateBitmapImageValue(method, bitmap.UriSource, bitmapVarName);
        }
Ejemplo n.º 25
0
        public CodeDomEntity(JToken structualType, string targetNamespace)
        {
            this.targetNamespace = targetNamespace;
            outputFileName = string.Format("{0}.cs", structualType["shortName"].Value<string>());
            this.structualType = structualType;
            targetUnit = new CodeCompileUnit();
            CodeNamespace breezeEntities = new CodeNamespace(targetNamespace);
            breezeEntities.Imports.Add(new CodeNamespaceImport("System"));
            breezeEntities.Imports.Add(new CodeNamespaceImport("Breeze.Sharp"));
            breezeEntities.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            targetClass = new CodeTypeDeclaration(structualType["shortName"].Value<string>());
            if (structualType["baseTypeName"] != null)
            {
                //use base class from the base type (it will still be BaseEntity)
                string baseType = structualType["baseTypeName"].Value<string>();
                targetClass.BaseTypes.Add(new CodeTypeReference(baseType.Substring(0, baseType.IndexOf(':'))));
            }
            else
            {
                //this entity type has no base class so use BaseEntity
                targetClass.BaseTypes.Add(new CodeTypeReference("BaseEntity"));
            }

            targetClass.IsClass = true;
            targetClass.TypeAttributes = TypeAttributes.Public;
            breezeEntities.Types.Add(targetClass);
            targetUnit.Namespaces.Add(breezeEntities);
        }
 internal void AddFunctionsToDataComponent(CodeTypeDeclaration classDeclaration, bool isFunctionsDataComponent)
 {
     if (this.designTable == null)
     {
         throw new InternalException("Design Table should not be null.");
     }
     if ((!isFunctionsDataComponent && (this.designTable.MainSource != null)) && ((((DbSource) this.designTable.MainSource).QueryType != QueryType.Rowset) || (((DbSource) this.designTable.MainSource).CommandOperation != CommandOperation.Select)))
     {
         this.AddFunctionToDataComponent(classDeclaration, (DbSource) this.designTable.MainSource, 0, isFunctionsDataComponent);
     }
     if (this.designTable.Sources != null)
     {
         int commandIndex = 1;
         if (isFunctionsDataComponent)
         {
             commandIndex = 0;
         }
         foreach (Source source in this.designTable.Sources)
         {
             if ((((DbSource) source).QueryType != QueryType.Rowset) || (((DbSource) source).CommandOperation != CommandOperation.Select))
             {
                 this.AddFunctionToDataComponent(classDeclaration, (DbSource) source, commandIndex, isFunctionsDataComponent);
             }
             commandIndex++;
         }
     }
 }
		static CodeTypeDeclaration CreatePartialClass (SteticCompilationUnit globalUnit, List<SteticCompilationUnit> units, GenerationOptions options, string name)
		{
			SteticCompilationUnit unit;
			
			if (options.GenerateSingleFile)
				unit = globalUnit;
			else {
				unit = new SteticCompilationUnit (name);
				units.Add (unit);
			}
			
			string ns = "";
			int i = name.LastIndexOf ('.');
			if (i != -1) {
				ns = name.Substring (0, i);
				name = name.Substring (i+1);
			}
			
			CodeTypeDeclaration type = new CodeTypeDeclaration (name);
			type.IsPartial = true;
			type.Attributes = MemberAttributes.Public;
			type.TypeAttributes = TypeAttributes.Public;
			
			CodeNamespace cns = new CodeNamespace (ns);
			cns.Types.Add (type);
			unit.Namespaces.Add (cns);
			return type;
		}
Ejemplo n.º 28
0
 private void CreateClass()
 {
     myclass = new CodeTypeDeclaration("myclass");
     myclass.IsClass = true;
     myclass.Attributes = MemberAttributes.Public;
     mynamespace.Types.Add(myclass);
 }
        public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
        {
            var types = codeUnit.Namespaces[0].Types;
            var attributes = new HashSet<string>();
            foreach (var type in types.Cast<CodeTypeDeclaration>().
                                 Where(type => type.IsClass && !type.IsContextType()))
            {
                attributes.Clear();
                var @struct = new CodeTypeDeclaration {
                    Name = AttributeConstsStructName, 
                    IsStruct = true, 
                    TypeAttributes = TypeAttributes.Public
                };

                foreach (var member in from CodeTypeMember member in type.Members 
                                       let prop = member as CodeMemberProperty 
                                       where prop != null 
                                       select prop)
                {
                    CreateAttributeConstForProperty(@struct, member, attributes);
                }

                if (attributes.Any())
                {
                    type.Members.Insert(0, GenerateTypeWithoutEmptyLines(@struct));
                }
            }
        }
 private void AddFunctionToDataComponent(CodeTypeDeclaration classDeclaration, DbSource dbSource, int commandIndex, bool isFunctionsDataComponent)
 {
     FunctionGenerator generator;
     if (!this.DeclarationsOnly || (dbSource.Modifier == MemberAttributes.Public))
     {
         generator = new FunctionGenerator(this.codeGenerator) {
             DeclarationOnly = this.declarationsOnly,
             MethodSource = dbSource,
             CommandIndex = commandIndex,
             DesignTable = this.designTable,
             IsFunctionsDataComponent = isFunctionsDataComponent
         };
         if (generator.MethodSource.Connection != null)
         {
             generator.ProviderFactory = ProviderManager.GetFactory(generator.MethodSource.Connection.Provider);
             goto Label_00A5;
         }
         if (this.designTable.Connection != null)
         {
             generator.ProviderFactory = ProviderManager.GetFactory(this.designTable.Connection.Provider);
             goto Label_00A5;
         }
     }
     return;
 Label_00A5:
     generator.MethodName = dbSource.GeneratorSourceName;
     generator.ParameterOption = this.languageSupportsNullables ? ParameterGenerationOption.ClrTypes : ParameterGenerationOption.Objects;
     CodeMemberMethod method = generator.Generate();
     if (method != null)
     {
         classDeclaration.Members.Add(method);
     }
 }
Ejemplo n.º 31
0
        public void CanCreateDataTableAssignment()
        {
            CodeNamespace nsdecl = new CodeNamespace("My.Data");
            CodeTypeDeclaration cdecl = new CodeTypeDeclaration("ResultSet");
            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "GetData";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            method.ReturnType = new CodeTypeReference("System.Data.DataTable");
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name"));
            method.Statements.Add(new CodeVariableDeclarationStatement(
                typeof(DataTable),
                "result",
                new CodeObjectCreateExpression(typeof(DataTable))));
            cdecl.Members.Add(method);
            method.Statements.Add(
                new CodeVariableDeclarationStatement(
                    typeof(DataColumnCollection),
                    "columns",
                    new CodePropertyReferenceExpression(
                        new CodeVariableReferenceExpression("result"),
                        "Columns")));
            method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("columns"), "Add", new CodeTypeOfExpression(typeof(string)), new CodeSnippetExpression("name")));

            nsdecl.Types.Add(cdecl);
            CSharpCodeProvider provider = new CSharpCodeProvider();
            provider.GenerateCodeFromNamespace(nsdecl, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());
        }
        /// <summary>
        /// Generates code
        /// </summary>
        /// <param name="source">The dependence object</param>
        /// <param name="classType">Type of the class.</param>
        /// <param name="initMethod">The initialize method.</param>
        /// <param name="generateField"></param>
        /// <returns></returns>
        public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod initMethod, bool generateField)
        {
            CodeExpression fieldReference = base.Generate(source, classType, initMethod, generateField);
            CodeComHelper.GenerateEnumField<Stretch>(initMethod, fieldReference, source, ImageButton.ImageStretchProperty);

            ImageButton imageButton = source as ImageButton;
            BitmapImage bitmap = imageButton.ImageNormal as BitmapImage;
            if (bitmap != null)
            {
                CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_normal_bm", ImageButton.ImageNormalProperty);
            }

            bitmap = imageButton.ImageDisabled as BitmapImage;
            if (bitmap != null)
            {
                CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_disabled_bm", ImageButton.ImageDisabledProperty);
            }

            bitmap = imageButton.ImageHover as BitmapImage;
            if (bitmap != null)
            {
                CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_hover_bm", ImageButton.ImageHoverProperty);
            }

            bitmap = imageButton.ImagePressed as BitmapImage;
            if (bitmap != null)
            {
                CodeComHelper.GenerateBitmapImageField(initMethod, fieldReference, source, bitmap.UriSource, imageButton.Name + "_pressed_bm", ImageButton.ImagePressedProperty);
            }

            return fieldReference;
        }
Ejemplo n.º 33
0
        public override void GCode_CodeDom_GenerateCode(System.CodeDom.CodeTypeDeclaration codeClass, System.CodeDom.CodeStatementCollection codeStatementCollection, CodeGenerateSystem.Base.LinkControl element, CodeGenerateSystem.Base.GenerateCodeContext_Method context)
        {
            var linkOI = GetLinkObjInfo(mResultMethod);

            if (linkOI.HasLink)
            {
                int i = 0;
                for (; i < linkOI.LinkInfos.Count; i++)
                {
                    var linkInfo = linkOI.LinkInfos[i];
                    if (mbFromObject)
                    {
                        if (linkInfo.m_linkToObjectInfo == linkOI)
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (linkInfo.m_linkFromObjectInfo == linkOI)
                        {
                            break;
                        }
                    }
                }
                if (!linkOI.GetLinkObject(i, mbFromObject).IsOnlyReturnValue)
                {
                    linkOI.GetLinkObject(i, mbFromObject).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, linkOI.GetLinkElement(i, mbFromObject), context);
                }
            }
        }
Ejemplo n.º 34
0
        public void SetUp()
        {
            buildData                 = new BuildDataDictionary();
            this.typeDeclarations     = new CodeTypeDeclarationCollection();
            this.testClassDeclaration = new System.CodeDom.CodeTypeDeclaration();
            typeDeclarations.Add(this.testClassDeclaration);

            this.namespaceDetector = new NStub.CSharp.NamespaceDetector(typeDeclarations);
            this.testObject        = new CodeTypeSetup(this.namespaceDetector, buildData, this.testClassDeclaration);
        }
Ejemplo n.º 35
0
    //</snippet4>

    public System.CodeDom.CodeTypeDeclaration ProcessImportedType(
        System.CodeDom.CodeTypeDeclaration typeDeclaration,
        System.CodeDom.CodeCompileUnit compileUnit)
    {
        // Console.WriteLine("ProcessImportedType invoked")
        // Not used in this sample.
        // You could use this method to construct an entirely new CLR
        // type when a certain type is imported, or modify a
        // generated type in some way.
        return(typeDeclaration);
    }
Ejemplo n.º 36
0
 protected override void GenerateMethod(System.CodeDom.CodeMemberMethod e, System.CodeDom.CodeTypeDeclaration c)
 {
     if (e.ReturnType.BaseType == string_consts.void_type)
     {
         Output.Write("procedure ");
     }
     else
     {
         Output.Write("function ");
     }
     OutputMethodSignature(e.Attributes, e.ReturnType, e.Name, e.Parameters, false, false);
     GenerateBlock(e.Statements);
     Output.WriteLine(";");
 }
Ejemplo n.º 37
0
 //<snippet7>
 public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
 {
     Console.WriteLine("ProcessImportedType");
     foreach (CodeTypeMember member in typeDeclaration.Members)
     {
         object memberCustomData = member.UserData[typeof(IDataContractSurrogate)];
         if (memberCustomData != null &&
             memberCustomData is string &&
             ((string)memberCustomData == "private"))
         {
             member.Attributes = ((member.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private);
         }
     }
     return(typeDeclaration);
 }
Ejemplo n.º 38
0
        public void GenerateCodeTypeDeclaration(CodeDomProvider provider, CodeGeneratorOptions generatorOptions,
                                                string wrapperName, out CodeTypeDeclaration ctd, out string ns)
        {
            var registerAtt = new CodeTypeReference(wrapperName + ".Foundation.RegisterAttribute");
            var connectAtt  = new CodeTypeReference(wrapperName + ".Foundation.ConnectAttribute");
            var exportAtt   = new CodeTypeReference(wrapperName + ".Foundation.ExportAttribute");

            ctd = new System.CodeDom.CodeTypeDeclaration()
            {
                IsPartial = true,
            };

            if (Outlets.Any(o => o.IsDesigner) || Actions.Any(a => a.IsDesigner))
            {
                AddWarningDisablePragmas(ctd, provider);
            }

            var dotIdx = CliName.LastIndexOf('.');

            if (dotIdx > 0)
            {
                ns       = CliName.Substring(0, dotIdx);
                ctd.Name = CliName.Substring(dotIdx + 1);
            }
            else
            {
                ctd.Name = CliName;
                ns       = null;
            }
            AddAttribute(ctd.CustomAttributes, registerAtt, ObjCName);

            foreach (var a in Actions)
            {
                if (a.IsDesigner)
                {
                    GenerateAction(exportAtt, ctd, a, provider, generatorOptions);
                }
            }

            foreach (var o in Outlets)
            {
                if (o.IsDesigner)
                {
                    AddOutletProperty(connectAtt, ctd, o.CliName, new CodeTypeReference(o.CliType));
                }
            }
        }
Ejemplo n.º 39
0
    public static System.CodeDom.CodeCompileUnit BuildGraph(System.Xml.XmlDocument xmlMetaData,
                                                            string tableName)
    {
        System.Xml.XmlNodeList             nodeList;
        System.CodeDom.CodeCompileUnit     compileUnit = new System.CodeDom.CodeCompileUnit();
        System.CodeDom.CodeNamespace       nSpace;
        System.CodeDom.CodeTypeDeclaration clsTable;

        nodeList = xmlMetaData.SelectNodes("/DataSet/Table[@Name='" + tableName + "']/Column");

        nSpace = new System.CodeDom.CodeNamespace("ClassViaCodeDOM");
        compileUnit.Namespaces.Add(nSpace);

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

        clsTable = new System.CodeDom.CodeTypeDeclaration(tableName);
        nSpace.Types.Add(clsTable);

        System.CodeDom.CodeMemberField field;
        foreach (System.Xml.XmlNode node in nodeList)
        {
            field            = new System.CodeDom.CodeMemberField();
            field.Name       = "m_" + node.Attributes["Name"].Value;
            field.Attributes = System.CodeDom.MemberAttributes.Private;
            field.Type       = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value);
            clsTable.Members.Add(field);
        }

        System.CodeDom.CodeMemberProperty prop;
        string name;

        foreach (System.Xml.XmlNode node in nodeList)
        {
            prop            = new System.CodeDom.CodeMemberProperty();
            name            = node.Attributes["Name"].Value;
            prop.Name       = name;
            prop.Attributes = System.CodeDom.MemberAttributes.Public;
            prop.Type       = new System.CodeDom.CodeTypeReference(node.Attributes["Type"].Value);
            prop.GetStatements.Add(new System.CodeDom.CodeMethodReturnStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name)));
            prop.SetStatements.Add(new System.CodeDom.CodeAssignStatement(new System.CodeDom.CodeFieldReferenceExpression(new System.CodeDom.CodeThisReferenceExpression(), "m_" + name), new System.CodeDom.CodePropertySetValueReferenceExpression()));
            clsTable.Members.Add(prop);
        }
        return(compileUnit);
    }
Ejemplo n.º 40
0
 protected override void GenerateMethod(System.CodeDom.CodeMemberMethod e, System.CodeDom.CodeTypeDeclaration c)
 {
     if (e.Name == "InitializeComponent" && own_output || !own_output && e.Name != "InitializeComponent")
     {
         if (e.ReturnType.BaseType == string_consts.void_type)
         {
             Output.Write("procedure ");
         }
         else
         {
             Output.Write("function ");
         }
         OutputMethodSignature(e.Attributes, e.ReturnType, e.Name, e.Parameters, false, false);
         GenerateBlock(e.Statements);
         Output.WriteLine(";");
     }
     else if (!own_output && e.Name == "InitializeComponent")
     {
         Output.WriteLine(string.Format("{{$include {0}}}", UnitName + "." + c.Name + ".inc"));
     }
 }
Ejemplo n.º 41
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);
    }
Ejemplo n.º 42
0
 public int Add(CodeTypeDeclaration value) => List.Add(value);
Ejemplo n.º 43
0
 public bool Contains(CodeTypeDeclaration value) => List.Contains(value);
Ejemplo n.º 44
0
 public int IndexOf(CodeTypeDeclaration value) => List.IndexOf(value);
Ejemplo n.º 45
0
 public void Insert(int index, CodeTypeDeclaration value) => List.Insert(index, value);
Ejemplo n.º 46
0
        public static System.CodeDom.CodeCompileUnit GenerateCodeBehind(AspNetAppProject project,
                                                                        string filename,
                                                                        AspNetParsedDocument document,
                                                                        List <CodeBehindWarning> errors)
        {
            string className = document.Info.InheritedClass;

            if (document.HasErrors)
            {
                AddFail(errors, document, document.Errors.Where(x => x.ErrorType == ErrorType.Error).First());
                return(null);
            }

            if (string.IsNullOrEmpty(className))
            {
                return(null);
            }

            var refman = new DocumentReferenceManager(project)
            {
                Doc = document
            };
            var memberList = new MemberListVisitor(document, refman);

            document.RootNode.AcceptVisit(memberList);

            var err = memberList.Errors.Where(x => x.ErrorType == ErrorType.Error).FirstOrDefault();

            if (err != null)
            {
                AddFail(errors, document, err);
                return(null);
            }

            //initialise the generated type
            var ccu      = new CodeCompileUnit();
            var namespac = new CodeNamespace();

            ccu.Namespaces.Add(namespac);
            var typeDecl = new System.CodeDom.CodeTypeDeclaration()
            {
                IsClass   = true,
                IsPartial = true,
            };

            namespac.Types.Add(typeDecl);

            //name the class and namespace
            int    namespaceSplit = className.LastIndexOf('.');
            string namespaceName  = null;

            if (namespaceSplit > -1)
            {
                namespac.Name = project.StripImplicitNamespace(className.Substring(0, namespaceSplit));
                typeDecl.Name = className.Substring(namespaceSplit + 1);
            }
            else
            {
                typeDecl.Name = className;
            }

            string masterTypeName = null;

            if (!String.IsNullOrEmpty(document.Info.MasterPageTypeName))
            {
                masterTypeName = document.Info.MasterPageTypeName;
            }
            else if (!String.IsNullOrEmpty(document.Info.MasterPageTypeVPath))
            {
                try {
                    ProjectFile          resolvedMaster       = project.ResolveVirtualPath(document.Info.MasterPageTypeVPath, document.FileName);
                    AspNetParsedDocument masterParsedDocument = null;
                    if (resolvedMaster != null)
                    {
                        masterParsedDocument = ProjectDomService.Parse(project, resolvedMaster.FilePath) as AspNetParsedDocument;
                    }
                    if (masterParsedDocument != null && !String.IsNullOrEmpty(masterParsedDocument.Info.InheritedClass))
                    {
                        masterTypeName = masterParsedDocument.Info.InheritedClass;
                    }
                    else
                    {
                        errors.Add(new CodeBehindWarning(String.Format("Could not find type for master '{0}'",
                                                                       document.Info.MasterPageTypeVPath),
                                                         document.FileName));
                    }
                } catch (Exception ex) {
                    errors.Add(new CodeBehindWarning(String.Format("Could not find type for master '{0}'",
                                                                   document.Info.MasterPageTypeVPath),
                                                     document.FileName));
                    LoggingService.LogWarning("Error resolving master page type", ex);
                }
            }

            if (masterTypeName != null)
            {
                var masterProp = new CodeMemberProperty()
                {
                    Name       = "Master",
                    Type       = new CodeTypeReference(masterTypeName),
                    HasGet     = true,
                    HasSet     = false,
                    Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.New
                                 | System.CodeDom.MemberAttributes.Final,
                };
                masterProp.GetStatements.Add(new System.CodeDom.CodeMethodReturnStatement(
                                                 new System.CodeDom.CodeCastExpression(masterTypeName,
                                                                                       new System.CodeDom.CodePropertyReferenceExpression(
                                                                                           new System.CodeDom.CodeBaseReferenceExpression(), "Master"))));
                typeDecl.Members.Add(masterProp);
            }

            //shortcut building the existing members type map
            if (memberList.Members.Count == 0)
            {
                return(ccu);
            }

            var dom     = refman.TypeCtx.ProjectDom;
            var cls     = dom.GetType(className);
            var members = GetDesignerMembers(memberList.Members.Values, cls, filename, dom, dom);

            //add fields for each control in the page

            foreach (var member in members)
            {
                var type = new CodeTypeReference(member.Type.FullName);
                typeDecl.Members.Add(new CodeMemberField(type, member.Name)
                {
                    Attributes = MemberAttributes.Family
                });
            }
            return(ccu);
        }
 /// <devdoc>
 /// <para>Gets a value indicating whether the
 ///    <see cref='System.CodeDom.CodeTypeDeclarationCollection'/> contains the specified <see cref='System.CodeDom.CodeTypeDeclaration'/>.</para>
 /// </devdoc>
 public bool Contains(CodeTypeDeclaration value)
 {
     return(List.Contains(value));
 }
 /// <devdoc>
 ///    <para>Adds a <see cref='System.CodeDom.CodeTypeDeclaration'/> with the specified value to the
 ///    <see cref='System.CodeDom.CodeTypeDeclarationCollection'/> .</para>
 /// </devdoc>
 public int Add(CodeTypeDeclaration value)
 {
     return(List.Add(value));
 }
Ejemplo n.º 49
0
 protected override void GenerateConstructor(System.CodeDom.CodeConstructor e, System.CodeDom.CodeTypeDeclaration c)
 {
     //Output.Write("constructor");
     //OutputMethodSignature(e.Attributes, e.ReturnType, "", e.Parameters, false, false);
     //GenerateBlock(e.Statements);
     //Output.WriteLine(";");
 }
Ejemplo n.º 50
0
 protected override void GenerateEntryPointMethod(System.CodeDom.CodeEntryPointMethod e, System.CodeDom.CodeTypeDeclaration c)
 {
     //ничего не делаем
 }
Ejemplo n.º 51
0
 protected override void GenerateProperty(System.CodeDom.CodeMemberProperty e, System.CodeDom.CodeTypeDeclaration c)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Ejemplo n.º 52
0
 protected override void GenerateTypeEnd(System.CodeDom.CodeTypeDeclaration e)
 {
     //Output.WriteLine("end;");
     Indent--;
 }
Ejemplo n.º 53
0
 protected override void GenerateTypeStart(System.CodeDom.CodeTypeDeclaration e)
 {
     //Output.WriteLine("type " + e.Name + " = class" + "(" + e.BaseTypes[0].BaseType + ")");
     Indent++;
 }
Ejemplo n.º 54
0
        // Create a CodeDOM graph.
        static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu)
        {
            //<Snippet8>
            if (!provider.Supports(GeneratorSupport.GenericTypeReference |
                                   GeneratorSupport.GenericTypeDeclaration))
            {
                // Return if the generator does not support generics.
                return;
            }
            //</Snippet8>

            CodeNamespace ns = new CodeNamespace("DemoNamespace");

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            cu.Namespaces.Add(ns);

            // Declare a generic class.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration();

            class1.Name = "MyDictionary";
            class1.BaseTypes.Add(new CodeTypeReference("Dictionary",
                                                       new CodeTypeReference[] {
                new CodeTypeReference("TKey"),
                new CodeTypeReference("TValue"),
            }));
            //<Snippet2>
            //<Snippet10>
            CodeTypeParameter kType = new CodeTypeParameter("TKey");

            //</Snippet2>
            //<Snippet3>
            kType.HasConstructorConstraint = true;
            //</Snippet3>
            //<Snippet4>
            kType.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            //</Snippet4>
            //<Snippet5>
            kType.CustomAttributes.Add(new CodeAttributeDeclaration(
                                           "System.ComponentModel.DescriptionAttribute",
                                           new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));
            //</Snippet5>

            CodeTypeReference iComparableT = new CodeTypeReference("IComparable");

            iComparableT.TypeArguments.Add(new CodeTypeReference(kType));

            kType.Constraints.Add(iComparableT);

            CodeTypeParameter vType = new CodeTypeParameter("TValue");

            vType.Constraints.Add(new CodeTypeReference(typeof(IList <System.String>)));
            vType.CustomAttributes.Add(new CodeAttributeDeclaration(
                                           "System.ComponentModel.DescriptionAttribute",
                                           new CodeAttributeArgument(new CodePrimitiveExpression("ValueType"))));

            class1.TypeParameters.Add(kType);
            class1.TypeParameters.Add(vType);
            //</Snippet10>

            ns.Types.Add(class1);

            //<Snippet6>
            // Declare a generic method.
            CodeMemberMethod  printMethod = new CodeMemberMethod();
            CodeTypeParameter sType       = new CodeTypeParameter("S");

            sType.HasConstructorConstraint = true;
            CodeTypeParameter tType = new CodeTypeParameter("T");

            sType.HasConstructorConstraint = true;

            printMethod.Name = "Print";
            printMethod.TypeParameters.Add(sType);
            printMethod.TypeParameters.Add(tType);

            //</Snippet6>
            //<Snippet7>
            printMethod.Statements.Add(ConsoleWriteLineStatement(
                                           new CodeDefaultValueExpression(new CodeTypeReference("T"))));
            printMethod.Statements.Add(ConsoleWriteLineStatement(
                                           new CodeDefaultValueExpression(new CodeTypeReference("S"))));
            //</Snippet7>

            printMethod.Attributes = MemberAttributes.Public;
            class1.Members.Add(printMethod);

            CodeTypeDeclaration class2 = new CodeTypeDeclaration();

            class2.Name = "Demo";

            CodeEntryPointMethod methodMain = new CodeEntryPointMethod();

            CodeTypeReference myClass = new CodeTypeReference(
                "MyDictionary",
                new CodeTypeReference[] {
                new CodeTypeReference(typeof(int)),
                new CodeTypeReference("List",
                                      new CodeTypeReference[]
                                      { new CodeTypeReference("System.String") })
            });

            methodMain.Statements.Add(
                new CodeVariableDeclarationStatement(myClass,
                                                     "dict",
                                                     new CodeObjectCreateExpression(myClass)));

            methodMain.Statements.Add(ConsoleWriteLineStatement(
                                          new CodePropertyReferenceExpression(
                                              new CodeVariableReferenceExpression("dict"),
                                              "Count")));

//<Snippet9>
            methodMain.Statements.Add(new CodeExpressionStatement(
                                          new CodeMethodInvokeExpression(
                                              new CodeMethodReferenceExpression(
                                                  new CodeVariableReferenceExpression("dict"),
                                                  "Print",
                                                  new CodeTypeReference[] {
                new CodeTypeReference("System.Decimal"),
                new CodeTypeReference("System.Int32"),
            }),
                                              new CodeExpression[0])));

//</Snippet9>
            string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary <int,
                                                                                      System.Collections.Generic.List <string> >[]).FullName;

            CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName);

            methodMain.Statements.Add(
                new CodeVariableDeclarationStatement(dictionaryType, "dict2",
                                                     new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] {
                new CodePrimitiveExpression(null)
            })));

            methodMain.Statements.Add(ConsoleWriteLineStatement(
                                          new CodePropertyReferenceExpression(
                                              new CodeVariableReferenceExpression("dict2"),
                                              "Length")));

            class2.Members.Add(methodMain);
            ns.Types.Add(class2);
        }
Ejemplo n.º 55
0
        // Create a CodeDOM graph.
        static void CreateGraph(CodeCompileUnit cu)
        {
            //<Snippet2>
            cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start,
                                                           "Compile Unit Region"));
            //</Snippet2>
            //<Snippet3>
            cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End,
                                                         string.Empty));
            //</Snippet3>
            //<Snippet4>
            CodeChecksumPragma pragma1 = new CodeChecksumPragma();

            //</Snippet4>
            //<Snippet5>
            pragma1.FileName = "c:\\temp\\test\\OuterLinePragma.txt";
            //</Snippet5>
            //<Snippet6>
            pragma1.ChecksumAlgorithmId = HashMD5;
            //</Snippet6>
            //<Snippet7>
            pragma1.ChecksumData = new byte[] { 0xAA, 0xAA };
            //</Snippet7>
            cu.StartDirectives.Add(pragma1);
            //<Snippet8>
            CodeChecksumPragma pragma2 = new CodeChecksumPragma("test.txt", HashSHA1, new byte[] { 0xBB, 0xBB, 0xBB });

            //</Snippet8>
            cu.StartDirectives.Add(pragma2);

            CodeNamespace ns = new CodeNamespace("Namespace1");

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.IO"));
            cu.Namespaces.Add(ns);
            ns.Comments.Add(new CodeCommentStatement("Namespace Comment"));
            CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1");

            ns.Types.Add(cd);

            cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
            cd.LinePragma = new CodeLinePragma("c:\\temp\\test\\OuterLinePragma.txt", 300);

            CodeMemberMethod method1 = new CodeMemberMethod();

            method1.Name       = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            CodeMemberMethod method2 = new CodeMemberMethod();

            method2.Name       = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));

            cd.Members.Add(method1);
            cd.Members.Add(method2);

            cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start,
                                                           "Outer Type Region"));

            cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End,
                                                         string.Empty));

            CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");

            cd.Members.Add(field1);
            field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));

            //<Snippet9>
            CodeRegionDirective codeRegionDirective1 = new CodeRegionDirective(CodeRegionMode.Start,
                                                                               "Field Region");

            //</Snippet9>
            //<Snippet10>
            field1.StartDirectives.Add(codeRegionDirective1);
            //</Snippet10>
            CodeRegionDirective codeRegionDirective2 = new CodeRegionDirective(CodeRegionMode.End,
                                                                               "");

            //<Snippet11>
            codeRegionDirective2.RegionMode = CodeRegionMode.End;
            //</Snippet11>
            //<Snippet12>
            codeRegionDirective2.RegionText = string.Empty;
            //</Snippet12>
            //<Snippet13>
            field1.EndDirectives.Add(codeRegionDirective2);
            //</Snippet13>

            //<Snippet16>
            CodeSnippetStatement snippet1 = new CodeSnippetStatement();

            snippet1.Value = "            Console.WriteLine(field1);";

            CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");

            regionStart.RegionText = "Snippet Region";
            regionStart.RegionMode = CodeRegionMode.Start;
            snippet1.StartDirectives.Add(regionStart);
            snippet1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            //</Snippet16>

            // CodeStatement example
            CodeConstructor constructor1 = new CodeConstructor();

            constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            CodeStatement codeAssignStatement1 = new CodeAssignStatement(
                new CodeFieldReferenceExpression(
                    new CodeThisReferenceExpression(),
                    "field1"),
                new CodePrimitiveExpression("value1"));

            //<Snippet14>
            codeAssignStatement1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
            //</Snippet14>
            cd.Members.Add(constructor1);
            //<Snippet15>
            codeAssignStatement1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            //</Snippet15>
            method2.Statements.Add(codeAssignStatement1);
            method2.Statements.Add(snippet1);
        }
Ejemplo n.º 56
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());
            }
        }
 /// <devdoc>
 ///    <para>Returns the index of a <see cref='System.CodeDom.CodeTypeDeclaration'/> in
 ///       the <see cref='System.CodeDom.CodeTypeDeclarationCollection'/> .</para>
 /// </devdoc>
 public int IndexOf(CodeTypeDeclaration value)
 {
     return(List.IndexOf(value));
 }
Ejemplo n.º 58
0
 public void Remove(CodeTypeDeclaration value) => List.Remove(value);
Ejemplo n.º 59
0
        private void GenerateClassForBinding()
        {
            try
            {
                if (((this.bindingCount == 1) && (this.service != null)) && (this.Style != ServiceDescriptionImportStyle.ServerInterface))
                {
                    this.className = XmlConvert.DecodeName(this.service.Name);
                }
                else
                {
                    this.className = this.binding.Name;
                    if (this.Style == ServiceDescriptionImportStyle.ServerInterface)
                    {
                        this.className = "I" + CodeIdentifier.MakePascal(this.className);
                    }
                }
                this.className = XmlConvert.DecodeName(this.className);
                this.className = this.ClassNames.AddUnique(CodeIdentifier.MakeValid(this.className), null);
                this.codeClass = this.BeginClass();
                int num = 0;
                for (int i = 0; i < this.portType.Operations.Count; i++)
                {
                    CodeMemberMethod method;
                    this.MoveToOperation(this.portType.Operations[i]);
                    if (!this.IsOperationFlowSupported(this.operation.Messages.Flow))
                    {
                        switch (this.operation.Messages.Flow)
                        {
                        case OperationFlow.OneWay:
                        {
                            this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("OneWayIsNotSupported0"));
                            continue;
                        }

                        case OperationFlow.Notification:
                        {
                            this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("NotificationIsNotSupported0"));
                            continue;
                        }

                        case OperationFlow.RequestResponse:
                        {
                            this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("RequestResponseIsNotSupported0"));
                            continue;
                        }

                        case OperationFlow.SolicitResponse:
                        {
                            this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("SolicitResponseIsNotSupported0"));
                            continue;
                        }
                        }
                    }
                    try
                    {
                        method = this.GenerateMethod();
                    }
                    catch (Exception exception)
                    {
                        if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
                        {
                            throw;
                        }
                        throw new InvalidOperationException(System.Web.Services.Res.GetString("UnableToImportOperation1", new object[] { this.operation.Name }), exception);
                    }
                    if (method != null)
                    {
                        this.AddExtensionWarningComments(this.codeClass.Comments, this.operationBinding.Extensions);
                        if (this.operationBinding.Input != null)
                        {
                            this.AddExtensionWarningComments(this.codeClass.Comments, this.operationBinding.Input.Extensions);
                        }
                        if (this.operationBinding.Output != null)
                        {
                            this.AddExtensionWarningComments(this.codeClass.Comments, this.operationBinding.Output.Extensions);
                        }
                        num++;
                    }
                }
                if ((((((this.ServiceImporter.CodeGenerationOptions & CodeGenerationOptions.GenerateNewAsync) != CodeGenerationOptions.None) && this.ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareEvents)) && this.ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareDelegates)) && (num > 0)) && (this.Style == ServiceDescriptionImportStyle.Client))
                {
                    CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection();
                    string           identifier = "CancelAsync";
                    string           methodName = this.MethodNames.AddUnique(identifier, identifier);
                    CodeMemberMethod method2    = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, methodName, new CodeFlags[1], new string[] { typeof(object).FullName }, new string[] { "userState" }, typeof(void).FullName, metadata, CodeFlags.IsPublic | ((identifier != methodName) ? ((CodeFlags)0) : CodeFlags.IsNew));
                    method2.Comments.Add(new CodeCommentStatement(System.Web.Services.Res.GetString("CodeRemarks"), true));
                    CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), identifier, new CodeExpression[0]);
                    expression.Parameters.Add(new CodeArgumentReferenceExpression("userState"));
                    method2.Statements.Add(expression);
                }
                this.EndClass();
                if (this.portType.Operations.Count == 0)
                {
                    this.NoMethodsGeneratedWarning();
                }
                this.AddExtensionWarningComments(this.codeClass.Comments, this.binding.Extensions);
                if (this.port != null)
                {
                    this.AddExtensionWarningComments(this.codeClass.Comments, this.port.Extensions);
                }
                this.codeNamespace.Types.Add(this.codeClass);
            }
            catch (Exception exception2)
            {
                if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException))
                {
                    throw;
                }
                throw new InvalidOperationException(System.Web.Services.Res.GetString("UnableToImportBindingFromNamespace2", new object[] { this.binding.Name, this.binding.ServiceDescription.TargetNamespace }), exception2);
            }
        }
Ejemplo n.º 60
0
        private void RunText1(string codes)
        {
            List <string> UsingList = new List <string>()
            {
                "System",
                "System.Windows.Forms",
            };
            List <string> ImportList = new List <string>()
            {
                "System.dll",
                "System.Windows.Forms.dll",
            };

            CodeMemberMethod pMethod = new CodeMemberMethod();

            pMethod.Name       = "TestFunction";
            pMethod.Attributes = MemberAttributes.Public;
            pMethod.Parameters.Add(new
                                   CodeParameterDeclarationExpression(typeof(string), "msg"));
            pMethod.ReturnType = new CodeTypeReference(typeof(void));
            pMethod.Statements.Add(new CodeSnippetStatement(codes));
            //new CodeSnippetExpression(" MessageBox.Show(msg);"));

            CodeTypeDeclaration pClass =
                new System.CodeDom.CodeTypeDeclaration("MyTestClass");

            pClass.Attributes = MemberAttributes.Public;
            pClass.Members.Add(pMethod);

            CodeNamespace pNamespace = new CodeNamespace("CodeTextExecTest");

            pNamespace.Types.Add(pClass);
            foreach (string item in UsingList)
            {
                pNamespace.Imports.Add(new CodeNamespaceImport(item));
            }

            //Create compile unit
            CodeCompileUnit pUnit = new CodeCompileUnit();

            pUnit.Namespaces.Add(pNamespace);

            //Make compilation parameters
            CompilerParameters pParams =
                new CompilerParameters(ImportList.ToArray());

            pParams.GenerateInMemory = true;
            //Compile
            var             provider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults pResults = provider.CompileAssemblyFromDom(pParams, pUnit);

            if (pResults.Errors != null && pResults.Errors.Count > 0)
            {
                foreach (CompilerError pError in pResults.Errors)
                {
                    MessageBox.Show(pError.ToString());
                }
            }
            else
            {
                var result = (dynamic)pResults.CompiledAssembly.CreateInstance("CodeTextExecTest.MyTestClass");

                result.TestFunction("23939889");
            }
        }