Наследование: CodeTypeMember
Пример #1
0
        // Creates the codedom expression for a class variable, and attaches it to the given type.
        public static void Emit(CodeTypeDeclaration codeTypeDeclaration, ClassVariable classVariable)
        {
            var codeField = new CodeMemberField();
            codeTypeDeclaration.Members.Add(codeField);
            codeField.Name = classVariable.Name;
            codeField.Type = new CodeTypeReference(classVariable.TypeName);

            // Translate it's accessibility
            var attr = MemberAttributes.Public;
            switch(classVariable.Accessibility)
            {
                case Accessibility.Internal:
                    attr = MemberAttributes.FamilyAndAssembly;
                    break;
                case Accessibility.Private:
                    attr = MemberAttributes.Private;
                    break;
                case Accessibility.Protected:
                    attr = MemberAttributes.Family;
                    break;
            }

            // shared = static
            if (classVariable.IsShared)
                attr |= MemberAttributes.Static;

            // Final = const
            if (classVariable.IsFinal)
                attr |= MemberAttributes.Const;

            codeField.Attributes = attr;
        }
Пример #2
0
 internal static CodeMemberField AddFieldDeclaration(CodeTypeDeclaration type, MemberAttributes memberAttribute, string fieldType, string fieldName)
 {
     CodeMemberField cmf = new CodeMemberField(fieldType, fieldName);
     cmf.Attributes = memberAttribute;
     type.Members.Add(cmf);
     return cmf;
 }
Пример #3
0
        /// <summary>
        /// Compose additional items of the test TearDown method.
        /// </summary>
        /// <param name="teardownMethod">A reference to the TearDown method of the test.</param>
        /// <param name="testObjectMemberField">The member field of the object under test.</param>
        /// <param name="testObjectName">The name of the object under test.</param>
        /// <param name="testObjectType">Type of the object under test(OuT).</param>
        protected override void ComposeTestTearDownMethod(
            CodeMemberMethod teardownMethod,
            CodeMemberField testObjectMemberField,
            string testObjectName,
            Type testObjectType)
        {
            /*var invokeExpression = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Assert"),
                "AreEqual",
                //new CodePrimitiveExpression("expected")
                new CodeFieldReferenceExpression(testObjectMemberField, "bla")
                , new CodeVariableReferenceExpression("actual"));*/
            var fieldRef1 =
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), testObjectMemberField.Name);

            // var objectCreate1 = new CodeObjectCreateExpression(testObjectName, new CodeExpression[] { });
            var as1 =
                new CodeAssignStatement(fieldRef1, new CodePrimitiveExpression(null));

            // new CodeAssignStatement(fieldRef1, objectCreate1);

            // Creates a statement using a code expression.
            // var expressionStatement = new CodeExpressionStatement(fieldRef1);
            teardownMethod.Statements.Add(as1);
            base.ComposeTestTearDownMethod(teardownMethod, testObjectMemberField, testObjectName, testObjectType);
        }
        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 CodeMemberField CreateServiceField(string serviceClassName)
 {
     CodeMemberField serviceField;
     serviceField = new CodeMemberField(serviceClassName, ResourceBaseGenerator.ServiceFieldName);
     serviceField.Attributes = MemberAttributes.Final | MemberAttributes.Private;
     return serviceField;
 }
Пример #6
0
		static void enrichWrapType(CodeTypeDeclaration wrap, TypeInfo type)
		{
			// implement IWrap<T>
			var typeRef = new CodeTypeReference(type, CodeTypeReferenceOptions.GlobalReference);
			var iwrap = new CodeTypeReference(typeof(IWrap<>).Name + "<" + "global::" + type.FullName + ">", CodeTypeReferenceOptions.GenericTypeParameter);
			wrap.BaseTypes.Add(iwrap);

			// implement interface with public members for  underlying object 
			var intf = new CodeTypeReference("I" + type.Name);
			wrap.BaseTypes.Add(intf);

			// create underlying object related stuff
			var _underlyingObject = new CodeMemberField(typeRef, "_underlyingObject") { Attributes = MemberAttributes.Private };
			wrap.Members.Add(_underlyingObject);
			var this_underlyingObject = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), _underlyingObject.Name);
			var UnderlyingObject = new CodeMemberProperty();
			UnderlyingObject.Name = "UnderlyingObject";
			UnderlyingObject.HasGet = true;
			UnderlyingObject.HasSet = false;
			var ret = new CodeMethodReturnStatement(this_underlyingObject);
			UnderlyingObject.GetStatements.Add(ret);
			UnderlyingObject.Attributes = MemberAttributes.Public;
			UnderlyingObject.ImplementationTypes.Add(iwrap);
			UnderlyingObject.PrivateImplementationType = iwrap;
			UnderlyingObject.Type = typeRef;
			wrap.Members.Add(UnderlyingObject);

			addUnderlyingCtor(typeRef, this_underlyingObject, wrap);
			addCtors(type, typeRef, this_underlyingObject, wrap);
			addMethods(type, typeRef, this_underlyingObject, wrap);



		}
        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);
        }
 internal CodeMemberField CreateNameField(IService service)
 {
     var name = new CodeMemberField(typeof(string), NameName);
     name.Attributes = MemberAttributes.Const | MemberAttributes.Private;
     name.InitExpression = new CodePrimitiveExpression(service.Name);
     return name;
 }
 internal CodeMemberField CreateUriField(IService service)
 {
     var uri = new CodeMemberField(typeof(string), BaseUriName);
     uri.Attributes = MemberAttributes.Const | MemberAttributes.Private;
     uri.InitExpression = new CodePrimitiveExpression(service.BaseUri.ToString());
     return uri;
 }
Пример #10
0
        public override void DeclareCodeType(IDLInterface idlIntf)
        {
            // Proxy class.
            typeProxy = new CodeTypeDeclaration(name + "Proxy");
            typeProxy.IsClass = true;
            typeProxy.TypeAttributes = TypeAttributes.Public;
            eventsDeclarationHolder = new CodeTypeDeferredNamespaceDeclarationHolderEvents(idlIntf);
            typeProxy.BaseTypes.Add(genInterfaceName);

            // Interface field.
            CodeMemberField memberProxy = new CodeMemberField(genInterfaceName, proxyName);
            memberProxy.Attributes = MemberAttributes.Private;
            typeProxy.Members.Add(memberProxy); // TODO: Going to need a using or a fully qualified name.

            // Constructor.
            CodeConstructor constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Public;
            // TODO - use the actual interface type rather than a string.
            paramProxy = new CodeParameterDeclarationExpression(genInterfaceName, proxyName);
            constructor.Parameters.Add(paramProxy);
            thisProxyFieldRef = new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(), proxyName
            );
            assignProxy = new CodeAssignStatement(thisProxyFieldRef,
                new CodeArgumentReferenceExpression(proxyName));
            constructor.Statements.Add(assignProxy);
            typeProxy.Members.Add(constructor);

            declarationHolder = new CodeTypeIgnoredNamespaceDeclarationHolderParams(idlIntf);
            contextDeclarationHolder = declarationHolder;

            bAddNamespace = false;
        }
 public override object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression expression;
     CodeTypeDeclaration declaration = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
     RootContext context = manager.Context[typeof(RootContext)] as RootContext;
     CodeStatementCollection statements = new CodeStatementCollection();
     if ((declaration != null) && (context != null))
     {
         CodeMemberField field = new CodeMemberField(typeof(IContainer), "components") {
             Attributes = MemberAttributes.Private
         };
         declaration.Members.Add(field);
         expression = new CodeFieldReferenceExpression(context.Expression, "components");
     }
     else
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(typeof(IContainer), "components");
         statements.Add(statement);
         expression = new CodeVariableReferenceExpression("components");
     }
     base.SetExpression(manager, value, expression);
     CodeObjectCreateExpression right = new CodeObjectCreateExpression(typeof(Container), new CodeExpression[0]);
     CodeAssignStatement statement2 = new CodeAssignStatement(expression, right);
     statement2.UserData["IContainer"] = "IContainer";
     statements.Add(statement2);
     return statements;
 }
Пример #12
0
        public ClassCreator AddProperties(string propertyName, Type propertyType)
        {
            var backingField = new CodeMemberField(propertyType, "_" + propertyName);
            _targetClass.Members.Add(backingField);

            // Declare the read-only Width property.
            var memberProperty = new CodeMemberProperty
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Name = propertyName,
                HasGet = true,
                HasSet = true,
                Type = new CodeTypeReference(propertyType)
            };

            memberProperty.GetStatements.Add(new CodeMethodReturnStatement(
                new CodeFieldReferenceExpression(
                    new CodeThisReferenceExpression(), "_" + propertyName)));

            memberProperty.SetStatements.Add(
                new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + propertyName),
                    new CodePropertySetValueReferenceExpression())
                );

            _targetClass.Members.Add(memberProperty);

            return this;
        }
		protected internal override void CreateMethods ()
		{
			CodeMemberField fld;
			CodeMemberProperty prop;

			/* override the following abstract PageTheme properties:
			   protected abstract string AppRelativeTemplateSourceDirectory { get; }
			   protected abstract IDictionary ControlSkins { get; }
			   protected abstract string[] LinkedStyleSheets { get; }
			*/

			/* ControlSkins */
			fld = new CodeMemberField (typeof (HybridDictionary), "__controlSkins");
			fld.Attributes = MemberAttributes.Private;
			fld.InitExpression = new CodeObjectCreateExpression (typeof (HybridDictionary));
			mainClass.Members.Add (fld);

			prop = new CodeMemberProperty ();
			prop.Name = "ControlSkins";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.Type = new CodeTypeReference (typeof (IDictionary));
			prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("__controlSkins")));
			mainClass.Members.Add (prop);

			/* LinkedStyleSheets */
			fld = new CodeMemberField (typeof (string[]), "__linkedStyleSheets");
			fld.Attributes = MemberAttributes.Private;
			fld.InitExpression = CreateLinkedStyleSheets ();
			mainClass.Members.Add (fld);

			prop = new CodeMemberProperty ();
			prop.Name = "LinkedStyleSheets";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.Type = new CodeTypeReference (typeof (string[]));
			prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("__linkedStyleSheets")));
			mainClass.Members.Add (prop);

			/* AppRelativeTemplateSourceDirectory */
			prop = new CodeMemberProperty ();
			prop.Name = "AppRelativeTemplateSourceDirectory";
			prop.Attributes = MemberAttributes.Family | MemberAttributes.Override;
			prop.Type = new CodeTypeReference (typeof (string));
			prop.GetStatements.Add (new CodeMethodReturnStatement (
							new CodePrimitiveExpression (
								VirtualPathUtility.ToAbsolute (parser.BaseVirtualDir))));
			mainClass.Members.Add (prop);

			ControlBuilder builder = parser.RootBuilder;
			if (builder.Children != null) {
				foreach (object o in builder.Children) {
					if (! (o is ControlBuilder))
						continue;
					if (o is CodeRenderBuilder)
						continue;
					
					ControlBuilder b = (ControlBuilder) o;
					CreateControlSkinMethod (b);
				}
			}
		}
Пример #14
0
 protected override void GenerateField(System.CodeDom.CodeMemberField e)
 {
     Output.Write(e.Name);
     Output.Write(": ");
     OutputType(e.Type);
     Output.WriteLine(";");
 }
Пример #15
0
        // Generates a codedom enumeration and attaches it to the given namespace.
        public static void Emit(CodeNamespace codeNamespace, Pie.Expressions.Enum e)
        {
            // CodeTypeDeclaration is the CodeDOM representation of a
            // class, struct, or enum.
            var codeTypeDeclaration = new CodeTypeDeclaration();
            codeNamespace.Types.Add(codeTypeDeclaration);

            // Assign the unqualified name (without namespace).
            codeTypeDeclaration.Name = e.UnqualifiedName;

            // Flag the type as an enum.
            codeTypeDeclaration.IsEnum = true;

            // Set the accessibility of the enum.
            switch (e.Accessibility)
            {
                case Accessibility.Internal:
                    codeTypeDeclaration.TypeAttributes = TypeAttributes.NestedAssembly;
                    break;
                case Accessibility.Public:
                    codeTypeDeclaration.TypeAttributes = TypeAttributes.Public;
                    break;
            }

            // Translate the list of constants in the enum
            foreach(var c in e.Constants)
            {
                var f = new CodeMemberField(e.UnqualifiedName, c.Name);
                f.InitExpression = new CodePrimitiveExpression(c.Value);
                codeTypeDeclaration.Members.Add(f);
            }
        }
        public CodeTypeDeclaration CreateClass()
        {
            CodeTypeDeclaration declaration = new CodeTypeDeclaration(_sqlDataProviderHelperClassName);

            declaration.IsClass = true;
            declaration.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            declaration.BaseTypes.Add(typeof(ISqlDataProviderHelper));

            foreach (string keyFieldName in _dataTypeDescriptor.KeyPropertyNames)
            {
                string fieldName = CreateDataIdPropertyInfoFieldName(keyFieldName);

                CodeMemberField codeField = new CodeMemberField(new CodeTypeReference(typeof(PropertyInfo)), fieldName);
                codeField.InitExpression =
                    new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(IDataExtensions)),
                            "GetDataPropertyRecursivly"
                        ),
                        new CodeExpression[] {
                                new CodeTypeOfExpression(_entityClassName),
                                new CodePrimitiveExpression(keyFieldName)
                            }
                    );

                declaration.Members.Add(codeField);
            }

            AddGetDataByIdMethod(declaration);
            AddAddDataMethod(declaration);
            AddRemoveDataMethod(declaration);

            return declaration;
        }
Пример #17
0
 public static bool ListContainsConstant(List<CodeMemberField> constants, CodeMemberField c)
 {
     foreach (CodeMemberField d in constants)
         if (d.Name == c.Name)
             return true;
     return false;
 }
Пример #18
0
        static void DumpToFile(string enumName, IEnumerable<string> names, int first)
        {
            // TODO: Необходимо задавать провайдер из параметров командной строки
            // по умолчанию брать Cpp провайдер
            var @enum = new CodeTypeDeclaration(enumName) {
                IsEnum = true,
            };

            foreach(var name in names) {
                var field = new CodeMemberField(string.Empty, name) {
                    InitExpression = new CodePrimitiveExpression(first),
                };
                @enum.Members.Add(field);
                first++;
            }

            var codeProvider = CodeDomProvider.CreateProvider("CSharp");
            var options = new CodeGeneratorOptions {
                BlankLinesBetweenMembers = false,
                BracingStyle = "C",
            };

            using(var writer = new StreamWriter(enumName + "." + codeProvider.FileExtension)) {
                codeProvider.GenerateCodeFromType(@enum, writer, options);
            }
        }
Пример #19
0
        private void AddMemberAttributeDeclaration(CodeMemberField field, string jsonName)
        {
            if (this.serializationModel == SerializationModel.DataContractJsonSerializer)
            {
                CodeAttributeDeclaration attr = new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(DataMemberAttribute)));
                if (field.Name != jsonName)
                {
                    attr.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(jsonName)));
                }

                field.CustomAttributes.Add(attr);
            }
            else if (this.serializationModel == SerializationModel.JsonNet)
            {
                CodeAttributeDeclaration attr = new CodeAttributeDeclaration(
                    new CodeTypeReference(typeof(JsonPropertyAttribute)));
                if (field.Name != jsonName)
                {
                    attr.Arguments.Add(new CodeAttributeArgument("PropertyName", new CodePrimitiveExpression(jsonName)));
                }

                field.CustomAttributes.Add(attr);
            }
            else
            {
                throw new ArgumentException("Invalid serialization model");
            }
        }
Пример #20
0
        private static void GenerateCSharpCode(Entity entity, string path)
        {
            var targetUnit = new CodeCompileUnit();
            var targetNamespace = new CodeNamespace(entity.FullName.Substring(0, entity.FullName.LastIndexOf('.')));
            targetNamespace.Imports.Add(new CodeNamespaceImport("System"));
            var targetClass = new CodeTypeDeclaration(entity.FullName.Substring(entity.FullName.LastIndexOf('.') + 1))
            {
                IsClass = true,
                IsPartial = true,
                TypeAttributes = TypeAttributes.Public
            };
            targetNamespace.Types.Add(targetClass);
            targetUnit.Namespaces.Add(targetNamespace);

            foreach (var property in entity.Properties)
            {
                CodeTypeReference propertyType;
                if (property.IsNavigable)
                {
                    propertyType = new CodeTypeReference(typeof(List<>));
                    propertyType.TypeArguments.Add((string)RemapTypeForCSharp(property.Type));
                }
                else
                {
                    propertyType = new CodeTypeReference(RemapTypeForCSharp(property.Type));
                }

                var backingField = new CodeMemberField(propertyType, "_" + property.Name) {Attributes = MemberAttributes.Private};

                if (property.IsNavigable)
                    backingField.InitExpression = new CodeObjectCreateExpression(propertyType);

                targetClass.Members.Add(backingField);

                var codeProperty = new CodeMemberProperty
                {
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    Name = property.Name,
                    HasGet = true,
                    HasSet = true,
                    Type = propertyType,
                };
                codeProperty.GetStatements.Add(new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name)));
                codeProperty.SetStatements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name),
                        new CodeVariableReferenceExpression("value")));

                targetClass.Members.Add(codeProperty);
            }

            var provider = CodeDomProvider.CreateProvider("CSharp");
            var options = new CodeGeneratorOptions {BracingStyle = "C"};
            using (var writer = new StreamWriter(Path.Combine(path, entity.FullName + '.' + provider.FileExtension)))
            {
                provider.GenerateCodeFromCompileUnit(targetUnit, writer, options);
            }
        }
 internal static void AddCallbackDeclaration(CodeTypeMemberCollection members, string callbackMember)
 {
     CodeMemberField field = new CodeMemberField {
         Type = new CodeTypeReference(typeof(SendOrPostCallback)),
         Name = callbackMember
     };
     members.Add(field);
 }
Пример #22
0
 private static CodeMemberField GenerateField(string name, Type type)
 {
     CodeMemberField field = new CodeMemberField();
     field.Attributes = MemberAttributes.Private;
     field.Name = name;
     field.Type = new CodeTypeReference(type);
     return field;
 }
 internal CodeMemberField CreateAuthenticatorField()
 {
     CodeMemberField serviceField;
     serviceField = new CodeMemberField(typeof(Google.Apis.Authentication.IAuthenticator),
         ServiceClassGenerator.AuthenticatorName);
     serviceField.Attributes = MemberAttributes.Final | MemberAttributes.Private;
     return serviceField;
 }
Пример #24
0
		public void Constructor2_Deny_Unrestricted ()
		{
			CodeMemberField cmf = new CodeMemberField ("System.Int32", "mono");
			Assert.IsNull (cmf.InitExpression, "InitExpression");
			cmf.InitExpression = new CodeExpression ();
			Assert.AreEqual ("System.Int32", cmf.Type.BaseType, "Type");
			cmf.Type = new CodeTypeReference ("System.Void");
		}
        internal CodeMemberField CreateResourceNameConst(string resourceName)
        {
            var serviceField = new CodeMemberField(typeof(string), ResourceBaseGenerator.ResourceNameConst);
            serviceField.Attributes = MemberAttributes.Const | MemberAttributes.Private;
            serviceField.InitExpression = new CodePrimitiveExpression(resourceName);

            return serviceField;
        }
 private void BuildControlSkinMember()
 {
     int count = this._controlSkinBuilderEntryList.Count;
     CodeMemberField field = new CodeMemberField(typeof(HybridDictionary).FullName, "__controlSkins");
     CodeObjectCreateExpression expression = new CodeObjectCreateExpression(typeof(HybridDictionary), new CodeExpression[0]);
     expression.Parameters.Add(new CodePrimitiveExpression(count));
     field.InitExpression = expression;
     base._sourceDataClass.Members.Add(field);
 }
Пример #27
0
        public void Visit(TableColumnArg arg)
        {
            var field = new CodeMemberField();
            field.Name = arg.Variable;
            field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            field.Type = new CodeTypeReference(TablePrimitive.FromString(arg.Type).Type);

            _codeStack.Peek().ParentMemberDefinitions.Add(field);
        }
Пример #28
0
        public static CodeTypeDeclaration GetEntityForTableDescription(DbSyncTableDescription tableDesc, bool addKeyAttributes, Dictionary<string, string> colsMapping)
        {
            CodeTypeDeclaration entityDeclaration = new CodeTypeDeclaration(SanitizeName(tableDesc.UnquotedGlobalName));
            entityDeclaration.IsPartial = true;
            entityDeclaration.IsClass = true;

            foreach (DbSyncColumnDescription column in tableDesc.Columns)
            {
                string colName = column.UnquotedName;
                if (colsMapping != null)
                {
                    colsMapping.TryGetValue(column.UnquotedName.ToLowerInvariant(), out colName);
                    colName = colName ?? column.UnquotedName;
                }
                CodeTypeReference fieldTypeReference = GetTypeFromSqlType(tableDesc, column);
                CodeMemberField colField = new CodeMemberField(fieldTypeReference, "_" + SanitizeName(colName));
                colField.Attributes = MemberAttributes.Private;

                CodeMemberProperty propertyField = new CodeMemberProperty();
                propertyField.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                propertyField.Name = SanitizeName(colName);
                propertyField.Type = fieldTypeReference;
                propertyField.GetStatements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression(colField.Name)));
                propertyField.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(colField.Name), new CodeVariableReferenceExpression("value")));

                if (addKeyAttributes)
                {
                    if (column.IsPrimaryKey)
                    {
                        //Add the Key attribute
                        propertyField.CustomAttributes.Add(new CodeAttributeDeclaration(Constants.ClientKeyAtributeType));
                    }
                }
                else
                {
                    // This is service entity. Check to see if column mappings is present i.e colName is not the same as column.UnquotedName.
                    if (!colName.Equals(column.UnquotedName, StringComparison.Ordinal))
                    {
                        propertyField.CustomAttributes.Add(new CodeAttributeDeclaration(Constants.ServiceSyncColumnMappingAttribute,
                                    new CodeAttributeArgument("LocalName", new CodeSnippetExpression("\"" + column.UnquotedName + "\""))));
                    }

                    // For a nullable data type, we add the [SyncEntityPropertyNullable] attribute to the property that is code-generated.
                    // This is required because some data types such as string are nullable by default in .NET and so there is no good way to 
                    // later determine whether the type in the underlying data store is nullable or not.
                    if (column.IsNullable)
                    {
                        propertyField.CustomAttributes.Add(new CodeAttributeDeclaration(Constants.EntityPropertyNullableAttributeType));
                    }
                }

                entityDeclaration.Members.Add(colField);
                entityDeclaration.Members.Add(propertyField);
            }

            return entityDeclaration;
        }
Пример #29
0
		public override void AddReadonlyMembers(IShaderDom shader, Action<CodeTypeMember, string> add, Platform platform)
		{
			if (platform != Platform.Both)
				return;
		
			if (vsReg.FloatRegisterCount > 0)
			{
				CodeMemberField field = CreateShaderBufferField(shader, vsReg, shader.VertexShaderRegistersRef.FieldName);

				add(field, "Vertex shader register storage");
			}

			//and the PS

			if (psReg.FloatRegisterCount > 0)
			{
				CodeMemberField field = CreateShaderBufferField(shader, psReg, shader.PixelShaderRegistersRef.FieldName);

				add(field, "Pixel shader register storage");
			}


			//now do the boolean registers
			if (vsReg.BooleanRegisterCount > 0)
			{
				//create the vertex boolean registers
				CodeMemberField field = new CodeMemberField(typeof(bool[]), shader.VertexShaderBooleanRegistersRef.FieldName);
				field.Attributes = MemberAttributes.Private | MemberAttributes.Final;

				add(field, "Vertex shader boolean register storage");
			}
			//now the PS
			if (psReg.BooleanRegisterCount > 0)
			{
				//create the vertex boolean registers
				CodeMemberField field = new CodeMemberField(typeof(bool[]), shader.PixelShaderBooleanRegistersRef.FieldName);
				field.Attributes = MemberAttributes.Private | MemberAttributes.Final;

				add(field, "Pixel shader boolean register storage");
			}

			//blending
			if (vsBlendingReg != null && vsBlendingReg.FloatRegisterCount > 0 && shader.SourceShader.ManualExtensions)
			{
				CodeMemberField field = CreateShaderBufferField(shader, vsBlendingReg, shader.BlendShaderRegistersRef.FieldName);

				add(field, "Blend shader register storage");
			}
			//instancing
			if (vsInstancingReg != null && vsInstancingReg.FloatRegisterCount > 0)
			{
				CodeMemberField field = CreateShaderBufferField(shader, vsInstancingReg, shader.InstancingShaderRegistersRef.FieldName);

				add(field, "Instancing shader register storage");
			}
		}
        private CodeCompileUnit GeneraCodigo()
        {
            //Unidad de Compilación (ensamblado)
            var cu = new CodeCompileUnit();
            cu.ReferencedAssemblies.Add("System.dll");//Ensamblados que enlaza (aunque este debería estar por defecto)
            //Espacio de nombres
            var n = new CodeNamespace("EjemploGeneracionCodigo1");
            cu.Namespaces.Add(n);
            n.Imports.Add(new CodeNamespaceImport("System"));//Espacios de nombres que utiliza este namespace para compilar
            //Clase
            var c = new CodeTypeDeclaration("ClaseGenerada");
            n.Types.Add(c);
            c.BaseTypes.Add(new CodeTypeReference(typeof(System.Timers.Timer)));//Su clase padre
            c.IsPartial = true;

            //Atributo de la clase
            CodeMemberField mf = new CodeMemberField(typeof(string),"_atributo");
            c.Members.Add(mf);
            //Propiedad de la clase
            CodeMemberProperty cp = new CodeMemberProperty();
            c.Members.Add(cp);
            cp.Attributes = MemberAttributes.Public | MemberAttributes.Final;//lo de Final para que no sea virtual (por defecto si es público es virtual)
            cp.Type = new CodeTypeReference(typeof(string));
            cp.Name = "atributo";
            CodeFieldReferenceExpression cfre = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_atributo");
            CodeMethodReturnStatement mrs = new CodeMethodReturnStatement(cfre);
            cp.GetStatements.Add(mrs);
            //Metodo de la clase
            CodeMemberMethod cmm = new CodeMemberMethod();
            c.Members.Add(cmm);
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.Name = "Metodo1";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            CodeParameterDeclarationExpression pde = new CodeParameterDeclarationExpression(typeof(int),"enteroDeEntrada");
            cmm.Parameters.Add(pde);
            pde = new CodeParameterDeclarationExpression(typeof(string),"cadenaDeEntrada");
            cmm.Parameters.Add(pde);
            //Declaración de variable
            CodeVariableDeclarationStatement vds = new CodeVariableDeclarationStatement(typeof(string),"aux",new CodePrimitiveExpression("Prueba1") );
            cmm.Statements.Add(vds);
            //Llamar a método arbitrario
            //variable a llamar y método
            CodeMethodReferenceExpression  ctr = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("Console"),"WriteLine");
            //Llamada en sí con sus parámetros
            CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression( ctr, new CodeExpression[] {new CodePrimitiveExpression("Hola mundo")} );
            cmm.Statements.Add(invoke1);

            //Código a pelo. Ojo no se puede generar, por ejemplo, un foreach.
            cmm.Statements.Add(new CodeSnippetStatement("foreach(string s in cadenas){"));
            cmm.Statements.Add(new CodeSnippetStatement("Console.WriteLine(s);"));
            cmm.Statements.Add(new CodeSnippetStatement("}"));
            mrs = new CodeMethodReturnStatement(new CodePrimitiveExpression(42));
            cmm.Statements.Add(mrs);

            return cu;
        }
        private void AddServiceFields(CodeTypeDeclaration serviceClass)
        {
            var field = new CodeMemberField(typeof(IService), ServiceClassGenerator.GenericServiceName);
            field.Attributes = MemberAttributes.Final | MemberAttributes.Private;
            serviceClass.Members.Add(field);

            field = new CodeMemberField(typeof(IAuthenticator), ServiceClassGenerator.AuthenticatorName);
            field.Attributes = MemberAttributes.Final | MemberAttributes.Private;
            serviceClass.Members.Add(field);
        }
Пример #32
0
        public void ConstructWithParametersBuildDataSetUpMethodTestObjectMemberFieldTestObjectNameTestObjectTypeTest()
        {
            this.buildData             = new NStub.CSharp.ObjectGeneration.BuildDataDictionary();
            this.setUpMethod           = new System.CodeDom.CodeMemberMethod();
            this.testObjectMemberField = new System.CodeDom.CodeMemberField();
            this.testObjectName        = "myTestObjectName";
            this.testObjectType        = typeof(object);
            this.testObject            = new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, this.testObjectName, this.testObjectType);

            Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(null, this.setUpMethod, this.testObjectMemberField, this.testObjectName, this.testObjectType));
            Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, null, this.testObjectMemberField, this.testObjectName, this.testObjectType));
            Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, null, this.testObjectName, this.testObjectType));
            Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, null, this.testObjectType));
            Assert.Throws <ArgumentException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, string.Empty, this.testObjectType));
            Assert.Throws <ArgumentNullException>(() => new TestObjectComposer(this.buildData, this.setUpMethod, this.testObjectMemberField, this.testObjectName, null));
        }
Пример #33
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);
    }
Пример #34
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);
        }