Inheritance: CodeTypeMember
        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));
                }
            }
        }
        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));
        }
        /// <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);
            }
        }
Example #4
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 override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)
 {
     if (!String.IsNullOrWhiteSpace(Inherits))
     {
         derivedType.BaseTypes[0] = new CodeTypeReference(Inherits);
     }
 }
        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;
        }
        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);
                }
            }
        }
		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;
		}
        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);
        }
Example #11
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;
        }
        /// <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);
        }
Example #13
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();
        }
        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;
        }
		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");
			}
		}
 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++;
         }
     }
 }
        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);
        }
 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);
     }
 }
        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))));
            }
        }
        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());
        }
Example #21
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;
        }
        /// <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;
        }
Example #23
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;
        }
 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;
 }
Example #25
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;
        }
        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());
        }
 public void SetUp()
 {
     Generator = new StructureGenerator(Configuration);
     Configuration = CodeGeneratorConfiguration.Create().MediaTypes;
     Candidate = Type = new CodeTypeDeclaration();
     ContentType = new MediaType();
 }
 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;
 }
        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 CreateClass()
 {
     myclass = new CodeTypeDeclaration("myclass");
     myclass.IsClass = true;
     myclass.Attributes = MemberAttributes.Public;
     mynamespace.Types.Add(myclass);
 }