Ejemplo n.º 1
0
        /// <summary>
        /// In cases where we are emitting types that aren't already in the root namespace,
        /// we need to translate the generated type namespace so that it resides in the
        /// root namespace.
        /// </summary>
        /// <remarks>
        /// Here, we're interested in cases where we're generating VB code
        /// and our target project has a non-null root namespace.
        /// </remarks>
        /// <param name="type">The type who namespace should be translated</param>
        /// <param name="codeGenerator">The current proxy generator</param>
        /// <returns>A translated namespace string</returns>
        internal static string TranslateNamespace(Type type, CodeDomClientCodeGenerator codeGenerator)
        {
            // Set default namespace
            string typeNamespace;

            if (!_typeNamespaceTranslations.TryGetValue(type, out typeNamespace))
            {
                // Set the appropriate namespace
                if (NeedToPrefaceRootNamespace(type, codeGenerator))
                {
                    typeNamespace = string.IsNullOrEmpty(type.Namespace) ?
                                    _rootNamespace :
                                    (_rootNamespace + "." + type.Namespace);
                }
                else
                {
                    typeNamespace = type.Namespace;
                }

                // Cache the value for next time
                _typeNamespaceTranslations[type] = typeNamespace;
            }

            return(typeNamespace);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a <see cref="CodeAttributeDeclaration"/> for a <see cref="DisplayAttribute"/>.
        /// </summary>
        /// <param name="codeGenerator">The client proxy generator</param>
        /// <param name="referencingType">The type on whose member <see cref="DisplayAttribute"/> will be applied</param>
        /// <returns>The new attribute declaration</returns>
        internal static CodeAttributeDeclaration CreateDisplayAttributeDeclaration(CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType)
        {
            CodeAttributeDeclaration displayAttributeDeclaration = CodeGenUtilities.CreateAttributeDeclaration(
                typeof(DisplayAttribute),
                codeGenerator,
                referencingType);

            displayAttributeDeclaration.Arguments.Add(new CodeAttributeArgument("AutoGenerateField", new CodePrimitiveExpression(false)));

            return(displayAttributeDeclaration);
        }
        internal void Initialize(ICodeGenerationHost host, IEnumerable <EntityDescription> descriptions, ClientCodeGenerationOptions options)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (descriptions == null)
            {
                throw new ArgumentNullException("descriptions");
            }

            // Initialize all the instance variables
            this._host = host;
            this._clientProxyCodeGenerationOptions = options;

            this._entityDescriptions = descriptions.ToList();
            this._compileUnit        = new CodeCompileUnit();

            this._namespaces          = new Dictionary <string, CodeNamespace>();
            this._enumTypesToGenerate = new HashSet <Type>();

            CodeDomClientCodeGenerator.ValidateOptions(this._clientProxyCodeGenerationOptions);

            // Unconditionally initialize some options
            CodeGeneratorOptions cgo = new CodeGeneratorOptions();

            cgo.IndentString             = "    ";
            cgo.VerbatimOrder            = false;
            cgo.BlankLinesBetweenMembers = true;
            cgo.BracingStyle             = "C";
            this._options = cgo;

            // Choose the provider for the language.  C# is the default if unspecified.
            string language = this.ClientProxyCodeGenerationOptions.Language;
            bool   isCSharp = String.IsNullOrEmpty(language) || String.Equals(language, "C#", StringComparison.OrdinalIgnoreCase);

            this._provider = isCSharp ? (CodeDomProvider) new CSharpCodeProvider() : (CodeDomProvider) new VBCodeProvider();

            // Configure our code gen utility package
            CodeGenUtilities.Initialize(!this.IsCSharp, this.ClientProxyCodeGenerationOptions.UseFullTypeNames, this.ClientProxyCodeGenerationOptions.ClientRootNamespace);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Determines if we need to preface the root namespace to the type
        /// </summary>
        /// <param name="type">The type in question</param>
        /// <param name="codeGenerator">The current proxy generator</param>
        /// <returns><c>true</c> if if we need to preface the root namespace to the type, <c>false</c> otherwise</returns>
        private static bool NeedToPrefaceRootNamespace(Type type, CodeDomClientCodeGenerator codeGenerator)
        {
            // System assemblies never preface with the root namespace
            if (type.Assembly.IsSystemAssembly())
            {
                return(false);
            }
            bool isVbProjectWithRootNamespace = !codeGenerator.IsCSharp && !string.IsNullOrEmpty(codeGenerator.ClientProxyCodeGenerationOptions.ClientRootNamespace);

            bool typeIsGeneratedOnTheClient = (type.IsEnum && codeGenerator.NeedToGenerateEnumType(type)) ||
                                              codeGenerator.EntityDescriptions.Any(dsd => dsd.EntityTypes.Contains(type));

            bool typeNameStartsWithRootNamespace =
                string.Equals(type.Namespace, _rootNamespace, StringComparison.Ordinal) ||
                (!string.IsNullOrEmpty(type.Namespace) && type.Namespace.StartsWith(_rootNamespace + ".", StringComparison.Ordinal));

            return(isVbProjectWithRootNamespace && typeIsGeneratedOnTheClient && !typeNameStartsWithRootNamespace);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new <see cref="CodeTypeDeclaration"/> that is the generated form of
        /// the given <paramref name="enumType"/>.
        /// </summary>
        /// <param name="enumType">The enum type to generate.</param>
        /// <param name="codeGenerator">The current proxy generator context.</param>
        /// <returns>The newly generated enum type declaration.</returns>
        internal static CodeTypeDeclaration CreateEnumTypeDeclaration(Type enumType, CodeDomClientCodeGenerator codeGenerator)
        {
            System.Diagnostics.Debug.Assert(enumType.IsEnum, "Type must be an enum type");

            CodeTypeDeclaration typeDecl = CodeGenUtilities.CreateTypeDeclaration(enumType);

            typeDecl.IsEnum = true;

            // Always force generated enums to be public
            typeDecl.TypeAttributes |= TypeAttributes.Public;

            // Enums deriving from anything but int get an explicit base type
            Type underlyingType = enumType.GetEnumUnderlyingType();

            if (underlyingType != typeof(int))
            {
                typeDecl.BaseTypes.Add(new CodeTypeReference(underlyingType));
            }

            // Generate [DataContract] if it appears in the original only.  Use Reflection only because that matches
            // what WCF will do.
            DataContractAttribute dataContractAttr = (DataContractAttribute)Attribute.GetCustomAttribute(enumType, typeof(DataContractAttribute));

            if (dataContractAttr != null)
            {
                CodeAttributeDeclaration attrDecl = CodeGenUtilities.CreateDataContractAttributeDeclaration(enumType, codeGenerator, typeDecl);
                typeDecl.CustomAttributes.Add(attrDecl);
            }

            string[] memberNames   = Enum.GetNames(enumType);
            Type     enumValueType = Enum.GetUnderlyingType(enumType);

            for (int i = 0; i < memberNames.Length; ++i)
            {
                string            memberName  = memberNames[i];
                CodeTypeReference enumTypeRef = CodeGenUtilities.GetTypeReference(enumValueType, codeGenerator, typeDecl);
                CodeMemberField   enumMember  = new CodeMemberField(enumTypeRef, memberName);

                // Generate an initializer for the enum member.
                // GetRawConstantValue is the safest way to get the raw value of the enum field
                // and works for both Reflection and ReflectionOnly loaded assemblies.
                FieldInfo fieldInfo = enumType.GetField(memberName);
                if (fieldInfo != null)
                {
                    object memberValue = fieldInfo.GetRawConstantValue();

                    Debug.Assert(memberValue != null, "Enum type's GetRawConstantValue should never return null");

                    // We special-case MinValue and MaxValue for the integral types
                    // because VisualBasic will generate overflow compiler error for
                    // Int64.MinValue.   If we detect a known MinValue or MaxValue for
                    // this integral type, we generate that reference, otherwise we
                    // just generate a constant integral value of the enum's type
                    object[] minMaxValues = null;
                    CodeGenUtilities.IntegralMinMaxValues.TryGetValue(underlyingType, out minMaxValues);
                    Debug.Assert(minMaxValues == null || minMaxValues.Length == 3, "integralMinMaxValues elements must always contain 3 values");

                    // Gen xxx.MinValue if it matches, but give precedence to matching a true zero,
                    // which is the min value for the unsigned integral types
                    // minMaxValues[0]: the MinValue for this type
                    // minMaxValues[1]: the MaxValue for this type
                    // minMaxValues[2]: the zero for this type (memberValue is not boxed and cannot be cast)
                    if (minMaxValues != null && !memberValue.Equals(minMaxValues[2]) && memberValue.Equals(minMaxValues[0]))
                    {
                        enumMember.InitExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(underlyingType), "MinValue");
                    }
                    // Gen xxx.MaxValue if it matches
                    else if (minMaxValues != null && memberValue.Equals(minMaxValues[1]))
                    {
                        enumMember.InitExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(underlyingType), "MaxValue");
                    }
                    // All other cases generate an integral constant.
                    // CodeDom knows how to generate the right integral constant based on memberValue's type.
                    else
                    {
                        enumMember.InitExpression = new CodePrimitiveExpression(memberValue);
                    }
                }

                typeDecl.Members.Add(enumMember);

                // Generate an [EnumMember] if appropriate
                EnumMemberAttribute enumMemberAttr = (EnumMemberAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(EnumMemberAttribute));
                if (enumMemberAttr != null)
                {
                    CodeAttributeDeclaration enumAttrDecl = CodeGenUtilities.CreateEnumMemberAttributeDeclaration(fieldInfo, codeGenerator, typeDecl);
                    enumMember.CustomAttributes.Add(enumAttrDecl);
                }

                // Propagate any other attributes that can be seen by the client
                CustomAttributeGenerator.GenerateCustomAttributes(
                    codeGenerator,
                    typeDecl,
                    ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeTypeMember, ex.Message, fieldInfo.Name, typeDecl.Name, ex.InnerException.Message),
                    fieldInfo.GetCustomAttributes(false).Cast <Attribute>().Where(a => a.GetType() != typeof(EnumMemberAttribute)),
                    enumMember.CustomAttributes,
                    enumMember.Comments);
            }

            // Attributes marked with [Flag] propagate it
            if (enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
            {
                CodeAttributeDeclaration attrDecl = CodeGenUtilities.CreateAttributeDeclaration(typeof(FlagsAttribute), codeGenerator, typeDecl);
                typeDecl.CustomAttributes.Add(attrDecl);
            }
            return(typeDecl);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates an attribute declaration for <see cref="EnumMemberAttribute"/>
        /// </summary>
        /// <param name="memberInfo">The member that may contain an existing <see cref="EnumMemberAttribute"/></param>
        /// <param name="codeGenerator">The proxy generator</param>
        /// <param name="referencingType">The referencing type</param>
        /// <returns>A new attribute declaration</returns>
        internal static CodeAttributeDeclaration CreateEnumMemberAttributeDeclaration(MemberInfo memberInfo, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType)
        {
            CodeAttributeDeclaration enumMemberDecl = CodeGenUtilities.CreateAttributeDeclaration(typeof(System.Runtime.Serialization.EnumMemberAttribute), codeGenerator, referencingType);

            // If the user specified a DataContract, we should copy the namespace and name.
            EnumMemberAttribute enumMemberAttrib = (EnumMemberAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(EnumMemberAttribute));

            if (enumMemberAttrib != null)
            {
                string value = enumMemberAttrib.Value;
                if (!string.IsNullOrEmpty(value))
                {
                    enumMemberDecl.Arguments.Add(new CodeAttributeArgument("Value", new CodePrimitiveExpression(value)));
                }
            }
            return(enumMemberDecl);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a <see cref="CodeAttributeDeclaration"/> for a <see cref="DataContractAttribute"/>
        /// </summary>
        /// <param name="sourceType">The type to which the attribute will be applied (to use as a reference)</param>
        /// <param name="codeGenerator">The client proxy generator</param>
        /// <param name="referencingType">The type referencing this declaration</param>
        /// <returns>The new attribute declaration</returns>
        internal static CodeAttributeDeclaration CreateDataContractAttributeDeclaration(Type sourceType, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType)
        {
            CodeAttributeDeclaration dataContractAttrib = CodeGenUtilities.CreateAttributeDeclaration(typeof(System.Runtime.Serialization.DataContractAttribute), codeGenerator, referencingType);

            string dataContractNamespace = GetContractNamespace(sourceType);
            string dataContractName      = null;

            // If the user specified a DataContract, we should copy the namespace and name.
            var sourceDataContractAttrib = (DataContractAttribute)Attribute.GetCustomAttribute(sourceType, typeof(DataContractAttribute));

            if (sourceDataContractAttrib != null)
            {
                if (sourceDataContractAttrib.Namespace != null)
                {
                    dataContractNamespace = sourceDataContractAttrib.Namespace;
                }
                if (sourceDataContractAttrib.Name != null)
                {
                    dataContractName = sourceDataContractAttrib.Name;
                }
            }

            dataContractAttrib.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(dataContractNamespace)));
            if (dataContractName != null)
            {
                dataContractAttrib.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(dataContractName)));
            }
            return(dataContractAttrib);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets a <see cref="CodeTypeReference"/> for a CLR type.
        /// </summary>
        /// <param name="type">A CLR type.</param>
        /// <param name="codeGenerator">A <see cref="CodeDomClientCodeGenerator"/>.</param>
        /// <param name="referencingType">The referencing type.</param>
        /// <param name="optimizeAttributeName">Indicates whether or not to optimize <see cref="Attribute"/> names by removing the "Attribute" suffix.</param>
        /// <param name="forceUseFullyQualifiedName">Indicates whether or not to generate the type using the fully qualified name irrespective the global setting.</param>
        /// <returns>A <see cref="CodeTypeReference"/> for a CLR type.</returns>
        internal static CodeTypeReference GetTypeReference(Type type, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType, bool optimizeAttributeName, bool forceUseFullyQualifiedName)
        {
            string typeName      = type.Name;
            string typeNamespace = type.Namespace;

            // Add an import statement to the referencing type if needed
            CodeNamespace     ns = codeGenerator.GetNamespace(referencingType);
            CodeTypeReference codeTypeReference = null;

            // Attribute?  If so, we special case these and remove the 'Attribute' suffix if present.
            if (optimizeAttributeName)
            {
                typeName = OptimizeAttributeName(type);
            }

            // Determine if we should generate this type with a full type name
            bool useFullyQualifiedName = forceUseFullyQualifiedName || CodeGenUtilities._useFullTypeNames || RegisterTypeName(typeNamespace, typeName, ns.Name);

            // Make sure we take into account root namespace in VB codegen.
            typeNamespace = TranslateNamespace(type, codeGenerator);

            // Conditionally add an import statement.  Skip this step if we need to generate a full
            // type name, if we're already in the target namespace, or if the type is in the global namespace.
            if (!useFullyQualifiedName && !ns.Name.Equals(type.Namespace) && !string.IsNullOrEmpty(type.Namespace))
            {
                // If the namespace is already imported, the following line will be a no-op.
                ns.Imports.Add(new CodeNamespaceImport(typeNamespace));
            }

            // If forced using Fully Qualified names, dont look up or store the code reference in the cache. That is because,
            // we force the use of fully qualified names only in certain cases. Caching at this time will cause the fully qualified name
            // to be used every time.
            bool useCache = !forceUseFullyQualifiedName;

            // See if we already have a reference for this type
            Tuple <CodeNamespace, Type> tupleKey = new Tuple <CodeNamespace, Type>(ns, type);

            if (!useCache || !CodeGenUtilities._codeTypeReferences.TryGetValue(tupleKey, out codeTypeReference))
            {
                if (useFullyQualifiedName && !string.IsNullOrEmpty(typeNamespace))
                {
                    // While this splicing may seem awkward, we perform this task
                    // rather than rely on 'type.FullName' as we may have performed
                    // a VB root namespace translation task above.
                    typeName = typeNamespace + "." + typeName;
                }

                // If not, create a new type reference. Use the constructor for CodeTypeReference
                // that takes a type's name rather than type to generate short names.
                if (type.IsArray)
                {
                    codeTypeReference = new CodeTypeReference(
                        CodeGenUtilities.GetTypeReference(type.GetElementType(), codeGenerator, referencingType, /* optimizeAttributeName */ false, forceUseFullyQualifiedName),
                        type.GetArrayRank());
                }
                else if (type.IsGenericType)
                {
                    Type[] genericArguments           = type.GetGenericArguments();
                    CodeTypeReference[] typeArguments = new CodeTypeReference[genericArguments.Length];
                    for (int i = 0; i < genericArguments.Length; i++)
                    {
                        typeArguments[i] = GetTypeReference(genericArguments[i], codeGenerator, referencingType);
                    }
                    codeTypeReference = new CodeTypeReference(typeName, typeArguments);
                }
                else
                {
                    // Generate language-specific shorthands for core types by using CodeTypeReference constructor that takes a Type
                    if (type.IsPrimitive || type == typeof(void) || type == typeof(decimal) || type == typeof(string) || type == typeof(object))
                    {
                        codeTypeReference = new CodeTypeReference(type);
                    }
                    else
                    {
                        codeTypeReference = new CodeTypeReference(typeName);
                    }
                }

                // Keep track of the CLR type for identification purposes.
                codeTypeReference.UserData["ClrType"] = type;

                // Cache for later use.
                if (useCache)
                {
                    CodeGenUtilities._codeTypeReferences.Add(tupleKey, codeTypeReference);
                }
            }

            return(codeTypeReference);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Gets a <see cref="CodeTypeReference"/> for a CLR type.
 /// </summary>
 /// <param name="type">A CLR type.</param>
 /// <param name="codeGenerator">A <see cref="CodeDomClientCodeGenerator"/>.</param>
 /// <param name="referencingType">The referencing type.</param>
 /// <param name="optimizeAttributeName">Indicates whether or not the optimize <see cref="Attribute"/> names by removing the "Attribute" suffix.</param>
 /// <returns>A <see cref="CodeTypeReference"/> for a CLR type.</returns>
 internal static CodeTypeReference GetTypeReference(Type type, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType, bool optimizeAttributeName)
 {
     return(GetTypeReference(type, codeGenerator, referencingType, optimizeAttributeName, false));
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Gets a <see cref="CodeTypeReference"/> for a CLR type.
 /// </summary>
 /// <param name="type">A CLR type.</param>
 /// <param name="codeGenerator">A <see cref="CodeDomClientCodeGenerator"/>.</param>
 /// <param name="referencingType">The referencing type.</param>
 /// <returns>A <see cref="CodeTypeReference"/> for a CLR type.</returns>
 internal static CodeTypeReference GetTypeReference(Type type, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType)
 {
     return(GetTypeReference(type, codeGenerator, referencingType, false, false));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates an attribute declaration based on the specified attribute
        /// </summary>
        /// <param name="attributeType">type of the attribute</param>
        /// <param name="codeGenerator">A <see cref="CodeDomClientCodeGenerator"/>.</param>
        /// <param name="referencingType">The referencing type.</param>
        /// <returns>the attribute declaration</returns>
        internal static CodeAttributeDeclaration CreateAttributeDeclaration(Type attributeType, CodeDomClientCodeGenerator codeGenerator, CodeTypeDeclaration referencingType)
        {
            if (!typeof(Attribute).IsAssignableFrom(attributeType))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resource.Type_Must_Be_Attribute, attributeType.Name), "attributeType");
            }

            CodeTypeReference attribute = GetTypeReference(attributeType, codeGenerator, referencingType, true);

            return(new CodeAttributeDeclaration(attribute));
        }