/// <summary> /// Generates the metadata class for the given object (entity or complex object) /// </summary> /// <param name="codeGenContext">The context to use to generate code.</param> /// <param name="optionalSuffix">If not null, optional suffix to class name and namespace</param> /// <param name="type">The type of the object for which to generate the metadata class.</param> /// <returns><c>true</c> means at least some code was generated.</returns> public bool GenerateMetadataClass(CodeGenContext codeGenContext, string optionalSuffix, Type type) { // If already have a buddy class, bypass all this logic // Use soft dependency (string name) to avoid static dependency on DataAnnotations. // We do this because this wizard must run from the GAC, and DataAnnotations will not necessarily be in the GAC too. Type buddyClassType = TypeUtilities.GetAssociatedMetadataType(type); if (buddyClassType != null) { return(false); } string className = type.Name; string classNamespace = type.Namespace; bool addSuffix = !string.IsNullOrEmpty(optionalSuffix); if (addSuffix) { className += optionalSuffix; classNamespace += optionalSuffix; } // Every object could have a unique namespace (odd, but true) // So we logically create a new namespace for each object. Those // sharing a namespace will reuse the CodeNamespace. // We allow the caller to specify in case it needs to override that // namespace. Unit testing is such a scenario CodeNamespace codeNamespace = codeGenContext.GetOrGenNamespace(classNamespace); // If we redirected to a different namespace than the object, import the real object's namespace if (addSuffix) { CodeGenUtilities.AddImportIfNeeded(codeNamespace, type.Namespace); } // Name of buddy class is $objectClassName$Metadata (e.g. Orders --> OrdersMetadata) string buddyClassName = className + "Metadata"; // We use the full outer.inner type naming convention for VB because they cannot resolve it otherwise. // C# can currently resolve it due to a bug in the compiler, but it is safer to use the legal syntax here. string fullBuddyClassName = className + "." + buddyClassName; CodeTypeDeclaration objectClass = null; // public class $objectType$ { } objectClass = CodeGenUtilities.CreateTypeDeclaration(className, classNamespace); objectClass.IsPartial = true; objectClass.TypeAttributes = TypeAttributes.Public; // Add explanatory comments about what the [MetadataTypeAttribute] does objectClass.Comments.Add(new CodeCommentStatement(String.Format(CultureInfo.CurrentCulture, Resources.BusinessLogicClass_Entity_Partial_Class_Remarks, buddyClassName, className), false)); // [MetadataType(typeof($objectType$.$objectType$_Metadata))] CodeAttributeDeclaration attr = CodeGenUtilities.CreateAttributeDeclaration(BusinessLogicClassConstants.MetadataTypeAttributeTypeName); CodeAttributeArgument attrArg = new CodeAttributeArgument(new CodeTypeOfExpression(fullBuddyClassName)); attr.Arguments.Add(attrArg); objectClass.CustomAttributes.Add(attr); // public sealed class $objectType$_Metadata { } // (note: cannot set 'static' modified from CodeDom.) CodeTypeDeclaration buddyClass = CodeGenUtilities.CreateTypeDeclaration(buddyClassName, classNamespace); // Both VB and C# use a friend/public buddy class. A private buddy class does not // compile in VB, and it compiles in C# only due to a bug. buddyClass.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.NestedAssembly; bool generatedProperty = false; // Generate a developer comment describing what this class does buddyClass.Comments.Add(new CodeCommentStatement(String.Format(CultureInfo.CurrentCulture, Resources.Buddy_Class_Remarks, type.Name))); // Add a language-specific example string explanation = codeGenContext.IsCSharp ? Resources.Buddy_Class_Remarks_CSharp : Resources.Buddy_Class_Remarks_VB; buddyClass.Comments.Add(new CodeCommentStatement(explanation, false)); // Generate a private ctor to make it impossible to instantiate this class CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Private; ctor.Comments.Add(new CodeCommentStatement(Resources.BusinessLogicClass_Private_Ctor_Comment)); buddyClass.Members.Add(ctor); // Sort by name order for baseline predictability foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).OrderBy(p => p.Name)) { // CodeDom does not support auto-implemented properties, so we will generate fields and then transform them into properties Type propType = propertyInfo.PropertyType; if (propType.IsVisible && propertyInfo.GetGetMethod() != null && this.CanGeneratePropertyOfType(propType)) { // Add an import for this property type's namespace if needed CodeGenUtilities.AddImportIfNeeded(codeNamespace, propertyInfo.PropertyType.Namespace); CodeSnippetTypeMember property = CodeGenUtilities.CreateAutomaticPropertyDeclaration(codeGenContext, buddyClass, propertyInfo, !string.IsNullOrEmpty(codeNamespace.Name) /* insideNamespace */); buddyClass.Members.Add(property); generatedProperty = true; } } // Don't generate anything if the buddy class is empty if (generatedProperty) { // Add the partial object class to the namespace codeNamespace.Types.Add(objectClass); // Add the metadata class as a nested class inside the partial object class objectClass.Members.Add(buddyClass); } // false if no properties were generated, indicating no code should be emitted return(generatedProperty); }
/// <summary> /// Creates the entire business logic class within the specified namespace name /// </summary> /// <param name="codeGenContext">The context into which to generate code. It cannot be null.</param> /// <param name="className">The name of the class to generate. It cannot be null or empty.</param> /// <param name="namespaceName">The namespace to use for the generated code. It cannot be empty.</param> protected void GenerateBusinessLogicClass(CodeGenContext codeGenContext, string className, string namespaceName) { if (codeGenContext == null) { throw new ArgumentNullException("codeGenContext"); } if (string.IsNullOrEmpty(className)) { throw new ArgumentNullException("className"); } if (string.IsNullOrEmpty(namespaceName)) { throw new ArgumentNullException("namespaceName"); } // namespace XXX { } CodeNamespace ns = codeGenContext.GetOrGenNamespace(namespaceName); // public class $classname$ { } CodeTypeDeclaration businessLogicClass = this.CreateBusinessLogicClass(codeGenContext, ns, className); ns.Types.Add(businessLogicClass); // Class-level Xml comments // Empty class gets its own comment because it has no ContextType to describe string remarksComment; if (this.ContextType == null) { remarksComment = Resources.BusinessLogicClass_Class_Remarks_Empty; } else { remarksComment = String.Format(CultureInfo.CurrentCulture, Resources.BusinessLogicClass_Class_Remarks, this.ContextType.Name); } // Add developer comment explaining what this class does businessLogicClass.Comments.Add(new CodeCommentStatement(remarksComment, false)); // Add [RequiresAuthentication] as a comment if (this.ContextType != null) { remarksComment = codeGenContext.IsCSharp ? Resources.BusinessLogicClass_RequiresAuthentication_CSharp : Resources.BusinessLogicClass_RequiresAuthentication_VB; businessLogicClass.Comments.Add(new CodeCommentStatement(remarksComment, false)); } if (this.IsClientAccessEnabled) { // [EnableClientAccess] CodeAttributeDeclaration attr = CodeGenUtilities.CreateAttributeDeclaration(BusinessLogicClassConstants.EnableClientAccessAttributeTypeName); businessLogicClass.CustomAttributes.Add(attr); } else { // if not enabled, add a comment explaining how to enable it businessLogicClass.Comments.Add(new CodeCommentStatement(Resources.BusinessLogicClass_EnableClientAccess_Comment)); } // Gen all domain operation entries // Sort by name for baseline predictability foreach (BusinessLogicEntity entity in this.Entities.OrderBy(e => e.Name)) { if (entity.IsIncluded) { // Add an import for this entity's namespace if needed // This is necessary only when entities exist in a different namespace from the context CodeGenUtilities.AddImportIfNeeded(ns, entity.ClrType.Namespace); this.GenerateEntityDomainOperationEntries(codeGenContext, businessLogicClass, entity); } } // If any private helper methods were generated, append them now. // We sort by their keys to give baseline predictability. Dictionary <string, CodeTypeMember> helpers = BusinessLogicContext.GetHelperMemberDictionary(businessLogicClass); foreach (string key in helpers.Keys.OrderBy(s => s)) { businessLogicClass.Members.Add(helpers[key]); } // If we exposed an OData endpoint, add a reference to the OData assembly // so it appears in the server project, allowing the user to chose // CopyLocal=true for bin deploy scenarios if (this.IsODataEndpointEnabled) { codeGenContext.AddReference(typeof(ODataEndpointFactory).Assembly.FullName); } }
/// <summary> /// Creates the entire business logic class within the specified namespace name /// </summary> /// <param name="codeGenContext">The context into which to generate code. It cannot be null.</param> /// <param name="className">The name of the class to generate. It cannot be null or empty.</param> /// <param name="namespaceName">The namespace to use for the generated code. It cannot be empty.</param> protected void GenerateBusinessLogicClass(CodeGenContext codeGenContext, string className, string namespaceName) { if (codeGenContext == null) { throw new ArgumentNullException("codeGenContext"); } if (string.IsNullOrEmpty(className)) { throw new ArgumentNullException("className"); } if (string.IsNullOrEmpty(namespaceName)) { throw new ArgumentNullException("namespaceName"); } // namespace XXX { } CodeNamespace ns = codeGenContext.GetOrGenNamespace(namespaceName); // public class $classname$ { } CodeTypeDeclaration businessLogicClass = this.CreateBusinessLogicClass(codeGenContext, ns, className); ns.Types.Add(businessLogicClass); // Class-level Xml comments // Empty class gets its own comment because it has no ContextType to describe string remarksComment; if (this.ContextType == null) { remarksComment = Resources.BusinessLogicClass_Class_Remarks_Empty; } else { remarksComment = String.Format(CultureInfo.CurrentCulture, Resources.BusinessLogicClass_Class_Remarks, this.ContextType.Name); } // Add developer comment explaining what this class does businessLogicClass.Comments.Add(new CodeCommentStatement(remarksComment, false)); // Add [RequiresAuthentication] as a comment if (this.ContextType != null) { remarksComment = codeGenContext.IsCSharp ? Resources.BusinessLogicClass_RequiresAuthentication_CSharp : Resources.BusinessLogicClass_RequiresAuthentication_VB; businessLogicClass.Comments.Add(new CodeCommentStatement(remarksComment, false)); } if (this.IsClientAccessEnabled) { // [EnableClientAccess] CodeAttributeDeclaration attr = CodeGenUtilities.CreateAttributeDeclaration(BusinessLogicClassConstants.EnableClientAccessAttributeTypeName); businessLogicClass.CustomAttributes.Add(attr); } else { // if not enabled, add a comment explaining how to enable it businessLogicClass.Comments.Add(new CodeCommentStatement(Resources.BusinessLogicClass_EnableClientAccess_Comment)); } // Gen all domain operation entries // Sort by name for baseline predictability foreach (BusinessLogicEntity entity in this.Entities.OrderBy(e => e.Name)) { if (entity.IsIncluded) { // Add an import for this entity's namespace if needed // This is necessary only when entities exist in a different namespace from the context CodeGenUtilities.AddImportIfNeeded(ns, entity.ClrType.Namespace); this.GenerateEntityDomainOperationEntries(codeGenContext, businessLogicClass, entity); } } // If any private helper methods were generated, append them now. // We sort by their keys to give baseline predictability. Dictionary<string, CodeTypeMember> helpers = BusinessLogicContext.GetHelperMemberDictionary(businessLogicClass); foreach (string key in helpers.Keys.OrderBy(s => s)) { businessLogicClass.Members.Add(helpers[key]); } // If we exposed an OData endpoint, add a reference to the OData assembly // so it appears in the server project, allowing the user to chose // CopyLocal=true for bin deploy scenarios if (this.IsODataEndpointEnabled) { codeGenContext.AddReference(typeof(ODataEndpointFactory).Assembly.FullName); } }