public CodeNamespace() { this.imports = new CodeNamespaceImportCollection(); this.comments = new CodeCommentStatementCollection(); this.classes = new CodeTypeDeclarationCollection(); this.namespaces = new CodeNamespaceCollection(); }
public CodeNamespace() { this.imports = new CodeNamespaceImportCollection(); this.comments = new CodeCommentStatementCollection(); this.classes = new CodeTypeDeclarationCollection(); this.namespaces = new CodeNamespaceCollection(); }
private CodeNamespace(SerializationInfo info, StreamingContext context) { this.imports = new CodeNamespaceImportCollection(); this.comments = new CodeCommentStatementCollection(); this.classes = new CodeTypeDeclarationCollection(); this.namespaces = new CodeNamespaceCollection(); }
private CodeNamespace(SerializationInfo info, StreamingContext context) { this.imports = new CodeNamespaceImportCollection(); this.comments = new CodeCommentStatementCollection(); this.classes = new CodeTypeDeclarationCollection(); this.namespaces = new CodeNamespaceCollection(); }
public override void Execute(CodeNamespace codeNamespace) { #region find the values that have the namespace CodeTypeDeclarationCollection typesToRemove = new CodeTypeDeclarationCollection(); // foreach datatype in the codeNamespace foreach (CodeTypeDeclaration type in codeNamespace.Types) { string ns = Utility.GetXmlNamespace(type); if (string.IsNullOrEmpty(ns)) continue; if (Options.Namespace.ContainsXmlName(ns)) typesToRemove.Add(type); } #endregion #region remove the values that were in the namespace foreach (CodeTypeDeclaration type in typesToRemove) codeNamespace.Types.Remove(type); #endregion #region add imports foreach (NamespaceType ns in Options.Namespace) { if (string.IsNullOrEmpty(ns.CodeNamespace)) continue; codeNamespace.Imports.Add(new CodeNamespaceImport(ns.CodeNamespace)); } #endregion }
public void Constructor1_NullItem () { CodeTypeDeclaration[] declarations = new CodeTypeDeclaration[] { new CodeTypeDeclaration (), null }; CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection ( declarations); }
public void Constructor0 () { CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection (); Assert.IsFalse (((IList) coll).IsFixedSize, "#1"); Assert.IsFalse (((IList) coll).IsReadOnly, "#2"); Assert.AreEqual (0, coll.Count, "#3"); Assert.IsFalse (((ICollection) coll).IsSynchronized, "#4"); Assert.IsNotNull (((ICollection) coll).SyncRoot, "#5"); }
/// <summary> /// Initializes a new instance of the <see cref="NamespaceDetector"/> class. /// </summary> /// <param name="typeDeclarations">The type declarations to investigate.</param> public NamespaceDetector(CodeTypeDeclarationCollection typeDeclarations) { Guard.NotNull(() => typeDeclarations, typeDeclarations); this.typeDeclarations = typeDeclarations; // storedDeclarations = typeDeclarations.OfType<CodeTypeDeclaration>().ToList(); this.storedDeclarations = typeDeclarations.OfType<CodeTypeDeclaration>().ToArray(); IEnumerable<string> distinctNamespaces; this.ShortestNamespace = DetermineShortestNamespace(this.storedDeclarations, out distinctNamespaces); this.namespaces = distinctNamespaces.ToArray(); }
public void AddRange(CodeTypeDeclarationCollection value) { if (value == null) { throw new ArgumentNullException("value"); } int count = value.Count; for (int i = 0; i < count; i++) { this.Add(value[i]); } }
public void Constructor1_Deny_Unrestricted () { CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection (array); coll.CopyTo (array, 0); Assert.AreEqual (1, coll.Add (ctd), "Add"); Assert.AreSame (ctd, coll[0], "this[int]"); coll.AddRange (array); coll.AddRange (coll); Assert.IsTrue (coll.Contains (ctd), "Contains"); Assert.AreEqual (0, coll.IndexOf (ctd), "IndexOf"); coll.Insert (0, ctd); coll.Remove (ctd); }
/// <devdoc> /// <para> /// Adds the contents of another <see cref='System.CodeDom.CodeTypeDeclarationCollection'/> to the end of the collection. /// </para> /// </devdoc> public void AddRange(CodeTypeDeclarationCollection value) { if (value == null) { throw new ArgumentNullException("value"); } int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { this.Add(value[i]); } }
public void Constructor1 () { CodeTypeDeclaration td1 = new CodeTypeDeclaration (); CodeTypeDeclaration td2 = new CodeTypeDeclaration (); CodeTypeDeclaration[] declarations = new CodeTypeDeclaration[] { td1, td2 }; CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection ( declarations); Assert.AreEqual (2, coll.Count, "#1"); Assert.AreEqual (0, coll.IndexOf (td1), "#2"); Assert.AreEqual (1, coll.IndexOf (td2), "#3"); }
private static void AddTypes(string prepend, bool nested, CodeTypeDeclarationCollection types, CodeExpressionCollection into) { foreach (CodeTypeDeclaration t in types) { into.Add(new CodeTypeOfExpression( ((prepend == null || prepend == "") ? "" : (prepend + (nested ? "+" : "."))) + t.Name)); CodeTypeDeclarationCollection ctd = new CodeTypeDeclarationCollection(); foreach (CodeTypeMember m in t.Members) { if (m is CodeTypeDeclaration) ctd.Add((CodeTypeDeclaration)m); } AddTypes( ((prepend == null || prepend == "") ? "" : (prepend + (nested ? "+" : "."))) + t.Name, true, ctd, into); } }
private static CodeTypeDeclarationCollection CollectionBuilder ( string className, string classType) { // Declare a generic class. CodeTypeDeclaration newClass = new CodeTypeDeclaration(); newClass.Name = className; newClass.BaseTypes.Add(new CodeTypeReference("System.Collections.Generic.List", new CodeTypeReference[] { new CodeTypeReference(classType) })); CodeTypeDeclarationCollection decls = new CodeTypeDeclarationCollection(); decls.Add(newClass); return decls; }
public void AddRange(CodeTypeDeclarationCollection value) { if (value == null) { throw new ArgumentNullException("value"); } int count = value.Count; for (int i = 0; i < count; i++) { Add(value[i]); } }
public override void Execute(CodeNamespace codeNamespace) { CodeTypeDeclarationCollection typesToRemove = new CodeTypeDeclarationCollection(); // foreach datatype in the codeNamespace foreach (CodeTypeDeclaration type in codeNamespace.Types) { if (Options.Type.ContainsName(codeNamespace.Name+"."+type.Name) || Options.Type.ContainsName( type.Name)) typesToRemove.Add(type); } foreach (CodeTypeDeclaration type in typesToRemove) codeNamespace.Types.Remove(type); }
/// <summary> /// /// </summary> /// <returns></returns> public override CodeTypeDeclarationCollection EmitApiClass() { Validate(); // emitter-specific validation CodeTypeReference baseType = this.GetBaseType(); // raise the TypeGenerated event TypeGeneratedEventArgs eventArgs = new TypeGeneratedEventArgs(Item, baseType); this.Generator.RaiseTypeGeneratedEvent(eventArgs); // public [abstract] partial class ClassName CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(Item.Name); typeDecl.IsPartial = true; typeDecl.TypeAttributes = System.Reflection.TypeAttributes.Class; if (Item.Abstract) { typeDecl.TypeAttributes |= System.Reflection.TypeAttributes.Abstract; } SetTypeVisibility(typeDecl); EmitTypeAttributes(Item.Name, typeDecl, eventArgs.AdditionalAttributes); // : baseclass AssignBaseType(typeDecl, baseType, eventArgs.BaseType); AddInterfaces(Item.Name, typeDecl, eventArgs.AdditionalInterfaces); CommentEmitter.EmitSummaryComments(Item, typeDecl.Comments); // Since abstract types cannot be instantiated, skip the factory method for abstract types if ((typeDecl.TypeAttributes & System.Reflection.TypeAttributes.Abstract) == 0) EmitFactoryMethod(typeDecl); EmitProperties(typeDecl); // additional members, if provided by the event subscriber this.AddMembers(Item.Name, typeDecl, eventArgs.AdditionalMembers); CodeTypeDeclarationCollection typeDecls = new CodeTypeDeclarationCollection(); typeDecls.Add(typeDecl); return typeDecls; }
public override void Execute(CodeNamespace codeNamespace) { CodeTypeDeclarationCollection typesToRemove = new CodeTypeDeclarationCollection(); // foreach datatype in the codeNamespace foreach (CodeTypeDeclaration type in codeNamespace.Types) { if (Options.Type.Find(x => x.Name == codeNamespace.Name + "." + type.Name) != null || Options.Type.Find(x => x.Name == type.Name) != null) typesToRemove.Add(type); } foreach (CodeTypeDeclaration type in typesToRemove) { List<CodeAttributeDeclaration> toRemove = new List<CodeAttributeDeclaration>(); foreach (CodeAttributeDeclaration decl in type.CustomAttributes) if (decl.Name == "System.Xml.Serialization.XmlTypeAttribute") toRemove.Add(decl); foreach (var x in toRemove) type.CustomAttributes.Remove(x); //if (type.CustomAttributes.Contains(new CodeAttributeDeclaration("System.Xml.Serialization.XmlTypeAttribute"))) // type.CustomAttributes.Remove(new CodeAttributeDeclaration("System.Xml.Serialization.XmlTypeAttribute")); } }
static CodeTypeDeclarationCollection BuildMessage(SdkMessage message, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var declarations = new CodeTypeDeclarationCollection(); foreach (var pair in message.SdkMessagePairs.Values) { if (serviceProvider.CodeMessageFilterService.GenerateSdkMessagePair(pair, serviceProvider)) { declarations.Add(BuildMessageRequest(pair, pair.Request, serviceProvider)); declarations.Add(BuildMessageResponse(pair, pair.Response, serviceProvider)); } else { Trace.TraceInformation("Skipping {0}.Message Pair from being generated.", new object[] {message.Name, pair.Request.Name}); } } Trace.TraceInformation("Exiting {0}", new object[] {MethodBase.GetCurrentMethod().Name}); return declarations; }
static CodeTypeDeclarationCollection BuildEntity(EntityMetadata entity, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var declarations = new CodeTypeDeclarationCollection(); var entityClass = Class(serviceProvider.NamingService.GetNameForEntity(entity, serviceProvider), TypeRef(EntityClassBaseType), new[] {Attribute(typeof (DataContractAttribute)), Attribute(EntityLogicalNameAttribute, new[] {AttributeArg(entity.LogicalName)})}); InitializeEntityClass(entityClass, entity); CodeTypeMember member = null; foreach (var metadata in from metadata in entity.Attributes orderby metadata.LogicalName select metadata) { if (serviceProvider.CodeFilterService.GenerateAttribute(metadata, serviceProvider)) { member = BuildAttribute(entity, metadata, serviceProvider); entityClass.Members.Add(member); if ((entity.PrimaryIdAttribute == metadata.LogicalName) && metadata.IsPrimaryId.GetValueOrDefault()) { entityClass.Members.Add(BuildIdProperty(entity, metadata, serviceProvider)); } } else { Trace.TraceInformation("Skipping {0}.Attribute {1} from being generated.", new object[] {entity.LogicalName, metadata.LogicalName}); } var declaration = BuildAttributeOptionSet(entity, metadata, member, serviceProvider); if (declaration != null) { declarations.Add(declaration); } var declaration2 = BuildAttributeOptionSetForPickList(entity, metadata, serviceProvider); if (declaration2 != null) { var codeTypeMember = entityClass.Members.Cast<CodeTypeMember>().FirstOrDefault(x => x.Name == declaration2.Name); if (codeTypeMember != null) { //dont re inject type continue; } entityClass.Members.Add(declaration2); } } entityClass.Members.AddRange(BuildOneToManyRelationships(entity, serviceProvider)); entityClass.Members.AddRange(BuildManyToManyRelationships(entity, serviceProvider)); entityClass.Members.AddRange(BuildManyToOneRelationships(entity, serviceProvider)); declarations.Add(entityClass); Trace.TraceInformation("Exiting {0}: Entity Class {1} defined", new object[] {MethodBase.GetCurrentMethod().Name, entityClass.Name}); return declarations; }
static CodeTypeDeclarationCollection BuildEntities(EntityMetadata[] entityMetadata, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var declarations = new CodeTypeDeclarationCollection(); foreach (var metadata in from metadata in entityMetadata orderby metadata.LogicalName select metadata) { if (serviceProvider.CodeFilterService.GenerateEntity(metadata, serviceProvider)) { declarations.AddRange(BuildEntity(metadata, serviceProvider)); } else { Trace.TraceInformation("Skipping Entity {0} from being generated.", new object[] {metadata.LogicalName}); } } Trace.TraceInformation("Exiting {0}", new object[] {MethodBase.GetCurrentMethod().Name}); return declarations; }
public void SetUp() { this.typeDeclarations = new System.CodeDom.CodeTypeDeclarationCollection(); typeDeclarations.Add(new CodeTypeDeclaration("Jedzia.Loves.Testing.TheClassToTest")); this.testObject = new NamespaceDetector(this.typeDeclarations); }
public void AddRange(CodeTypeDeclarationCollection value) { throw new NotImplementedException(); }
private static CodeTypeDeclarationCollection CollectionBuilder(string className, string classType, string ns) { // Declare a generic class. CodeTypeDeclaration newClass = new CodeTypeDeclaration(); newClass.Name = className; newClass.IsPartial = true; newClass.BaseTypes.Add(new CodeTypeReference("System.Collections.Generic.List", new CodeTypeReference[] { new CodeTypeReference(classType) })); // add the Serializable attribute to the class CodeAttributeDeclaration attribute = new CodeAttributeDeclaration("System.SerializableAttribute"); newClass.CustomAttributes.Add(attribute); // add the Serializable attribute to the class CodeAttributeDeclaration xmlTypeAttribute= new CodeAttributeDeclaration("System.Xml.Serialization.XmlTypeAttribute"); xmlTypeAttribute.Arguments.Add(new CodeAttributeArgument() { Name="Namespace", Value=new CodePrimitiveExpression (ns) }); newClass.CustomAttributes.Add(xmlTypeAttribute); CodeTypeDeclarationCollection decls = new CodeTypeDeclarationCollection(); decls.Add(newClass); return decls; }
static CodeTypeDeclarationCollection BuildServiceContext(EntityMetadata[] entityMetadata, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var declarations = new CodeTypeDeclarationCollection(); if (serviceProvider.CodeFilterService.GenerateServiceContext(serviceProvider)) { var declaration = Class(serviceProvider.NamingService.GetNameForServiceContext(serviceProvider), ServiceContextBaseType, new CodeAttributeDeclaration[0]); declaration.Members.Add(ServiceContextConstructor()); declaration.Comments.AddRange(CommentSummary("Represents a source of entities bound to a CRM service. It tracks and manages changes made to the retrieved entities.")); foreach (var metadata in from metadata in entityMetadata orderby metadata.LogicalName select metadata) { if (serviceProvider.CodeFilterService.GenerateEntity(metadata, serviceProvider) && !string.Equals(metadata.LogicalName, "calendarrule", StringComparison.Ordinal)) { declaration.Members.Add(BuildEntitySet(metadata, serviceProvider)); } else { Trace.TraceInformation("Skipping {0} entity set and AddTo method from being generated.", new object[] {metadata.LogicalName}); } } declarations.Add(declaration); } else { Trace.TraceInformation("Skipping data context from being generated."); } Trace.TraceInformation("Exiting {0}", new object[] {MethodBase.GetCurrentMethod().Name}); return declarations; }
static CodeTypeDeclarationCollection BuildMessages(SdkMessages sdkMessages, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var declarations = new CodeTypeDeclarationCollection(); foreach (var message in sdkMessages.MessageCollection.Values) { if (serviceProvider.CodeMessageFilterService.GenerateSdkMessage(message, serviceProvider)) { declarations.AddRange(BuildMessage(message, serviceProvider)); } else { Trace.TraceInformation("Skipping SDK Message {0} from being generated.", new object[] {message.Name}); } } Trace.TraceInformation("Exiting {0}", new object[] {MethodBase.GetCurrentMethod().Name}); return declarations; }
public CodeTypeDeclarationCollection(CodeTypeDeclarationCollection value) { return(default(CodeTypeDeclarationCollection)); }
public void AddRange(CodeTypeDeclarationCollection !value) { Contract.Requires(value != null); }
static CodeTypeDeclarationCollection BuildOptionSets(OptionSetMetadataBase[] optionSetMetadata, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var declarations = new CodeTypeDeclarationCollection(); foreach (var base2 in optionSetMetadata) { if ((serviceProvider.CodeFilterService.GenerateOptionSet(base2, serviceProvider) && base2.IsGlobal.HasValue) && base2.IsGlobal.Value) { var declaration = BuildOptionSet(null, base2, serviceProvider); if (declaration != null) { declarations.Add(declaration); } else { Trace.TraceInformation("Skipping OptionSet {0} of type {1} from being generated.", new object[] {base2.Name, base2.GetType()}); } } else { Trace.TraceInformation("Skipping OptionSet {0} from being generated.", new object[] {base2.Name}); } } Trace.TraceInformation("Exiting {0}", new object[] {MethodBase.GetCurrentMethod().Name}); return declarations; }
public void ConstructWithParametersTypeDeclarationsTest() { this.typeDeclarations = new System.CodeDom.CodeTypeDeclarationCollection(); this.testObject = new NamespaceDetector(this.typeDeclarations); Assert.Throws<ArgumentNullException>(() => new NamespaceDetector(null)); }
/// <devdoc> /// <para> /// Initializes a new instance of <see cref='System.CodeDom.CodeTypeDeclarationCollection'/> based on another <see cref='System.CodeDom.CodeTypeDeclarationCollection'/>. /// </para> /// </devdoc> public CodeTypeDeclarationCollection(CodeTypeDeclarationCollection value) { this.AddRange(value); }
/// <summary> /// Creates the CodeTypeDeclarations necessary to generate the code for the EntityContainer schema element /// </summary> /// <returns></returns> public override CodeTypeDeclarationCollection EmitApiClass() { Validate(); // emitter-specific validation // declare the new class // public partial class LOBScenario : ObjectContext CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(Item.Name); typeDecl.IsPartial = true; // raise the TypeGenerated event CodeTypeReference objectContextTypeRef = TypeReference.ObjectContext; TypeGeneratedEventArgs eventArgs = new TypeGeneratedEventArgs(Item, objectContextTypeRef); Generator.RaiseTypeGeneratedEvent(eventArgs); if (eventArgs.BaseType != null && !eventArgs.BaseType.Equals(objectContextTypeRef)) { typeDecl.BaseTypes.Add(eventArgs.BaseType); } else { typeDecl.BaseTypes.Add(TypeReference.ObjectContext); } AddInterfaces(Item.Name, typeDecl, eventArgs.AdditionalInterfaces); CommentEmitter.EmitSummaryComments(Item, typeDecl.Comments); EmitTypeAttributes(Item.Name, typeDecl, eventArgs.AdditionalAttributes); bool needTypeMapper = (0 < this.Generator.NamespaceMap.Count); var q = from a in this.Generator.EdmItemCollection.GetItems<StructuralType>() where (a.BaseType != null) && (a.BuiltInTypeKind == BuiltInTypeKind.ComplexType || a.BuiltInTypeKind == BuiltInTypeKind.EntityType) select a; bool hasInheritance = (null != q.FirstOrDefault()); CreateConstructors(typeDecl, needTypeMapper, hasInheritance); // adding partial OnContextCreated method CreateContextPartialMethods(typeDecl); if (needTypeMapper || hasInheritance) { CreateTypeMappingMethods(typeDecl, needTypeMapper, hasInheritance); } foreach (EntitySetBase entitySetBase in Item.BaseEntitySets) { if (Helper.IsEntitySet(entitySetBase)) { EntitySet set = (EntitySet)entitySetBase; CodeMemberProperty codeProperty = CreateEntitySetProperty(set); typeDecl.Members.Add(codeProperty); CodeMemberField codeField = CreateEntitySetField(set); typeDecl.Members.Add(codeField); } } foreach (EntitySetBase entitySetBase in Item.BaseEntitySets) { if (Helper.IsEntitySet(entitySetBase)) { EntitySet set = (EntitySet)entitySetBase; CodeMemberMethod codeProperty = CreateEntitySetAddObjectMethod(set); typeDecl.Members.Add(codeProperty); } } // additional members, if provided by the event subscriber AddMembers(Item.Name, typeDecl, eventArgs.AdditionalMembers); CodeTypeDeclarationCollection typeDecls = new CodeTypeDeclarationCollection(); typeDecls.Add(typeDecl); return typeDecls; }
public void ToCodeDom(CodeTypeDeclarationCollection types) { if(this.OutputType!=ClassOutputType.Interface) { CodeTypeDeclaration c = new CodeTypeDeclaration(this.Name); c.TypeAttributes = this.Attributes; types.Add(c); ToClassCodeDom(c); } if (this.OutputType==ClassOutputType.Interface || this.OutputType==ClassOutputType.ClassAndInterface) { CodeTypeDeclaration c = new CodeTypeDeclaration(InterfaceName); types.Add(c); ToInterfaceCodeDom(c); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Add comments to each class and method /// </summary> /// <param name="types">Collection of types</param> /// ------------------------------------------------------------------------------------ private void AddComments(CodeTypeDeclarationCollection types) { foreach (CodeTypeDeclaration type in types) { // we probably inherited the comments (from a base class in an external file), // so we don't want to add the same comments again! if (type.Comments.Count > 0) continue; string comment = type.Name; IdhCommentProcessor.CommentInfo ifaceComment = null; if (!s_idhProcessor.Comments.TryGetValue(type.Name, out ifaceComment) && type.Name != string.Empty) s_idhProcessor.Comments.TryGetValue(type.Name.Substring(1), out ifaceComment); // Also get comments for base class - if we derive from a class // we might need to get some comments from there if we don't have our own. List<IdhCommentProcessor.CommentInfo> baseComments = new List<IdhCommentProcessor.CommentInfo>(); if (type.BaseTypes.Count > 0) { for (int i = 0; i < type.BaseTypes.Count; i++) { IdhCommentProcessor.CommentInfo baseComment = null; if (!s_idhProcessor.Comments.TryGetValue(type.BaseTypes[i].BaseType, out baseComment)) { s_idhProcessor.Comments.TryGetValue(type.BaseTypes[i].BaseType.Substring(1), out baseComment); } if (baseComment != null) baseComments.Add(baseComment); } } if (ifaceComment != null) comment = ifaceComment.Comment; type.Comments.Add(new CodeCommentStatement( string.Format(comment.Length > 80 ? "<summary>{1}{0}{1}</summary>" : "<summary>{0} </summary>", comment, Environment.NewLine), true)); foreach (CodeTypeMember member in type.Members) { if ((!type.IsInterface && !type.IsEnum && (member.Attributes & MemberAttributes.Private) == MemberAttributes.Private) || member.Comments.Count > 0 || member.Name == string.Empty) { continue; } IdhCommentProcessor.CommentInfo methodComment = null; if (ifaceComment != null) ifaceComment.Children.TryGetValue(member.Name, out methodComment); for (int i = 0; i < baseComments.Count && methodComment == null; i++) baseComments[i].Children.TryGetValue(member.Name, out methodComment); if (member is CodeMemberMethod) { if (methodComment == null) { // Maybe it's a property with a parameter? Try and see if the IDH // file has a comment for a method without the "get_" or "set_" if (member.Name.StartsWith("get_") || member.Name.StartsWith("set_")) { string name = member.Name.Substring(4); if (ifaceComment != null) ifaceComment.Children.TryGetValue(name, out methodComment); for (int i = 0; i < baseComments.Count && methodComment == null; i++) baseComments[i].Children.TryGetValue(name, out methodComment); } } comment = "Member " + member.Name; if (methodComment != null) comment = methodComment.Comment; member.Comments.Add(new CodeCommentStatement( string.Format(comment.Length > 80 ? "<summary>{1}{0}{1}</summary>" : "<summary>{0} </summary>", comment, Environment.NewLine), true)); CodeMemberMethod method = member as CodeMemberMethod; foreach (CodeParameterDeclarationExpression param in method.Parameters) { IdhCommentProcessor.CommentInfo paramComment = null; if (methodComment != null) methodComment.Children.TryGetValue(param.Name, out paramComment); comment = string.Empty; if (paramComment != null) comment = paramComment.Comment; member.Comments.Add(new CodeCommentStatement( string.Format("<param name='{0}'>{1} </param>", param.Name, comment), true)); } if (method.ReturnType.BaseType != "System.Void") { comment = "A " + method.ReturnType.BaseType; if (methodComment != null && methodComment.Attributes.ContainsKey("retval")) { string retparamName = methodComment.Attributes["retval"]; if (methodComment.Children.ContainsKey(retparamName)) comment = methodComment.Children[retparamName].Comment; } member.Comments.Add(new CodeCommentStatement( string.Format("<returns>{0}</returns>", comment), true)); } } else if (member is CodeMemberProperty) { CodeMemberProperty property = member as CodeMemberProperty; string getset = string.Empty; if (methodComment == null) { // No comment from IDH file - generate a pseudo one if (property.HasGet) getset += "Gets"; if (property.HasSet) { if (getset.Length > 0) getset += "/"; getset += "Sets"; } getset = string.Format("{0} a {1}", getset, member.Name); } else { // Use comment provided in IDH file getset = methodComment.Comment; } member.Comments.Add(new CodeCommentStatement( string.Format(getset.Length > 80 ? "<summary>{1}{0}{1}</summary>" : "<summary>{0} </summary>", getset, Environment.NewLine), true)); member.Comments.Add(new CodeCommentStatement( string.Format("<returns>A {0} </returns>", property.Type.BaseType), true)); } else if (member is CodeMemberField) { if (methodComment == null) { // No comment from IDH file - generate a pseudo one comment = string.Empty; } else { // Use comment provided in IDH file comment = methodComment.Comment; } member.Comments.Add(new CodeCommentStatement( string.Format(comment.Length > 80 ? "<summary>{1}{0}{1}</summary>" : "<summary>{0} </summary>", comment, Environment.NewLine), true)); } else { comment = "Member " + member.Name; if (methodComment != null) comment = methodComment.Comment; member.Comments.Add(new CodeCommentStatement( string.Format(comment.Length > 80 ? "<summary>{1}{0}{1}</summary>" : "<summary>{0} </summary>", comment, Environment.NewLine), true)); member.Comments.Add(new CodeCommentStatement( string.Format("Not expecting a member of type {0}", member.GetType()))); } if (methodComment != null && methodComment.Attributes.ContainsKey("exception")) { string[] exceptions = methodComment.Attributes["exception"].Split(','); foreach (string exception in exceptions) { comment = methodComment.Attributes[exception]; member.Comments.Add(new CodeCommentStatement( string.Format(@"<exception cref=""{0}"">{1}</exception>", exception, comment), true)); } } } } }
/// <devdoc> /// <para> /// Initializes a new instance of <see cref='System.CodeDom.CodeTypeDeclarationCollection'/> based on another <see cref='System.CodeDom.CodeTypeDeclarationCollection'/>. /// </para> /// </devdoc> public CodeTypeDeclarationCollection(CodeTypeDeclarationCollection value) { this.AddRange(value); }
public void ConstructWithParametersTypeDeclarationsTest() { this.typeDeclarations = new System.CodeDom.CodeTypeDeclarationCollection(); this.testObject = new NamespaceDetector(this.typeDeclarations); Assert.Throws <ArgumentNullException>(() => new NamespaceDetector(null)); }
private static void AddEntityOptionSetEnumDeclaration(CodeTypeDeclarationCollection types) { var enumClass = new CodeTypeDeclaration("EntityOptionSetEnum") { IsClass = true, TypeAttributes = TypeAttributes.Sealed | TypeAttributes.NotPublic, }; // public static int? GetEnum(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName) var get = new CodeMemberMethod { Name = "GetEnum", ReturnType = new CodeTypeReference(typeof(int?)), // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags Attributes = System.CodeDom.MemberAttributes.Static | System.CodeDom.MemberAttributes.Public, }; get.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Microsoft.Xrm.Sdk.Entity), "entity")); get.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "attributeLogicalName")); // entity.Attributes.ContainsKey(attributeLogicalName) var entityAttributesContainsKey = new CodeMethodReferenceExpression( new CodePropertyReferenceExpression( new CodeArgumentReferenceExpression("entity"), "Attributes"), "ContainsKey"); var invokeContainsKey = new CodeMethodInvokeExpression(entityAttributesContainsKey, new CodeArgumentReferenceExpression("attributeLogicalName")); // Microsoft.Xrm.Sdk.OptionSetValue value = entity.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(attributeLogicalName).Value; var declareAndSetValue = new CodeVariableDeclarationStatement { Type = new CodeTypeReference(typeof(OptionSetValue)), Name = "value", InitExpression = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeArgumentReferenceExpression("entity"), "GetAttributeValue", new CodeTypeReference(typeof(OptionSetValue))), new CodeArgumentReferenceExpression("attributeLogicalName")) }; // value != null var valueNeNull = new CodeSnippetExpression("value != null"); // value.Value var invokeValueGetValue = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("value"), "Value"); // if(invokeContainsKey){return invokeGetAttributeValue;}else{return null} get.Statements.Add(new CodeConditionStatement(invokeContainsKey, declareAndSetValue, new CodeConditionStatement(valueNeNull, new CodeMethodReturnStatement(invokeValueGetValue)))); // return null; get.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); enumClass.Members.Add(get); types.Add(enumClass); }
/// <summary> /// Creates the CodeTypeDeclarations necessary to generate the code for the EntityContainer schema element /// </summary> /// <returns></returns> public override CodeTypeDeclarationCollection EmitApiClass() { Validate(); // emitter-specific validation // declare the new class // public partial class LOBScenario : ObjectContext CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(Item.Name); typeDecl.IsPartial = true; // raise the TypeGenerated event CodeTypeReference objectContextTypeRef = TypeReference.ObjectContext; TypeGeneratedEventArgs eventArgs = new TypeGeneratedEventArgs(Item, objectContextTypeRef); Generator.RaiseTypeGeneratedEvent(eventArgs); if (eventArgs.BaseType != null && !eventArgs.BaseType.Equals(objectContextTypeRef)) { typeDecl.BaseTypes.Add(eventArgs.BaseType); } else { typeDecl.BaseTypes.Add(TypeReference.ObjectContext); } AddInterfaces(Item.Name, typeDecl, eventArgs.AdditionalInterfaces); CommentEmitter.EmitSummaryComments(Item, typeDecl.Comments); EmitTypeAttributes(Item.Name, typeDecl, eventArgs.AdditionalAttributes); CreateConstructors(typeDecl); // adding partial OnContextCreated method CreateContextPartialMethods(typeDecl); foreach (EntitySetBase entitySetBase in Item.BaseEntitySets) { if (MetadataUtil.IsEntitySet(entitySetBase)) { EntitySet set = (EntitySet)entitySetBase; CodeMemberProperty codeProperty = CreateEntitySetProperty(set); typeDecl.Members.Add(codeProperty); CodeMemberField codeField = CreateEntitySetField(set); typeDecl.Members.Add(codeField); } } foreach (EntitySetBase entitySetBase in Item.BaseEntitySets) { if (MetadataUtil.IsEntitySet(entitySetBase)) { EntitySet set = (EntitySet)entitySetBase; CodeMemberMethod codeProperty = CreateEntitySetAddObjectProperty(set); typeDecl.Members.Add(codeProperty); } } foreach (EdmFunction functionImport in Item.FunctionImports) { if (ShouldEmitFunctionImport(functionImport)) { CodeMemberMethod functionMethod = CreateFunctionImportStructuralTypeReaderMethod(functionImport); typeDecl.Members.Add(functionMethod); } } // additional members, if provided by the event subscriber AddMembers(Item.Name, typeDecl, eventArgs.AdditionalMembers); CodeTypeDeclarationCollection typeDecls = new CodeTypeDeclarationCollection(); typeDecls.Add(typeDecl); return typeDecls; }
public void SetUp() { this.typeDeclarations = new System.CodeDom.CodeTypeDeclarationCollection(); typeDeclarations.Add(new CodeTypeDeclaration("Jedzia.Loves.Testing.TheClassToTest")); this.testObject = new NamespaceDetector(this.typeDeclarations); }
protected override byte[] GenerateCode(string fileName, string FileContents) { InitializeTool(); try { if (mOutLog != null) { mOutLog.Clear(); } string DefaultNameSpace = this.GetDefaultNameSpace(fileName); // Load FileContents into XML Doc XmlDocument inXDoc = new XmlDocument(); inXDoc.PreserveWhitespace = false; inXDoc.LoadXml(FileContents); // Get the path to the WSDL XmlNode wsdln = inXDoc.DocumentElement.SelectSingleNode("//WSDLFile/text()"); if (wsdln == null || wsdln.Value == String.Empty) { //Console.WriteLine("WSDL not found in Document <configuration><WSDLFile>http://value.wsdl</WSDLFile></configuration>\n"); if (mOutLog != null) { mOutLog.OutputString("WSDL not found in Document <configuration><WSDLFile>http://value.wsdl</WSDLFile></configuration>\n"); } else { Console.WriteLine("WSDL not found in Document <configuration><WSDLFile>http://value.wsdl</WSDLFile></configuration>\n"); } return null; } string WSDLPath = wsdln.Value; if (mOutLog != null) { mOutLog.OutputString("Generating Proxy Class File\n"); mOutLog.OutputString("NameSpace: " + DefaultNameSpace + "\n"); mOutLog.OutputString("WSDL Path: " + WSDLPath + "\n"); } else { Console.WriteLine("Generating Proxy Class File\n"); Console.WriteLine("NameSpace: " + DefaultNameSpace + "\n"); Console.WriteLine("WSDL Path: " + WSDLPath + "\n"); } // Load WSDL XmlTextReader xtr = new XmlTextReader(WSDLPath); ServiceDescription serviceDescription = ServiceDescription.Read(xtr); CodeCompileUnit codeUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(DefaultNameSpace); codeUnit.Namespaces.Add(codeNamespace); codeNamespace.Comments.Add(new CodeCommentStatement("Generator version 1.1")); codeNamespace.Comments.Add(new CodeCommentStatement("")); codeNamespace.Comments.Add(new CodeCommentStatement("Copyright: ?2000-2008 eBay Inc.")); codeNamespace.Comments.Add(new CodeCommentStatement("")); codeNamespace.Comments.Add(new CodeCommentStatement("Date: " + DateTime.Now.ToString())); codeNamespace.Comments.Add(new CodeCommentStatement("")); // // Set up the service importer that eventually generate the DOM // for client proxy. // ServiceDescriptionImporter serviceImporter = new ServiceDescriptionImporter(); // Resolve any Imports DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); dcp.DiscoverAny(WSDLPath); dcp.ResolveAll(); foreach (object osd in dcp.Documents.Values) { if (osd is ServiceDescription) serviceImporter.AddServiceDescription((ServiceDescription)osd, String.Empty, String.Empty);; if (osd is XmlSchema) serviceImporter.Schemas.Add((XmlSchema)osd); } // Configure the Importer serviceImporter.ProtocolName = "Soap"; serviceImporter.Style = ServiceDescriptionImportStyle.Client; //serviceImporter.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.EnableDataBinding // | serviceImporter.CodeGenerationOptions; ServiceDescriptionImportWarnings warnings = serviceImporter.Import(codeNamespace, codeUnit); if (mOutLog != null) { if ((warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) != 0) mOutLog.OutputString("Warning: no methods were generated.\n"); if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0) mOutLog.OutputString("Warning: one or more optional WSDL extension elements were ignored.\n"); if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0) mOutLog.OutputString("Warning: one or more optional WSDL extension elements were ignored.\n"); if ((warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) != 0) mOutLog.OutputString("Warning: one or more required WSDL extension elements were ignored.\n"); if ((warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) != 0) mOutLog.OutputString("Warning: one or more bindings were skipped.\n"); if ((warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) != 0) mOutLog.OutputString("one or more operations were skipped.\n"); if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) != 0) { mOutLog.OutputString("Warning: no classes were generated.\n"); return null; } if (warnings != 0) mOutLog.OutputString("Warnings were encountered. Review generated source comments for more details.\n"); } else { if ((warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) != 0) Console.WriteLine("Warning: no methods were generated.\n"); if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0) Console.WriteLine("Warning: one or more optional WSDL extension elements were ignored.\n"); if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) != 0) Console.WriteLine("Warning: one or more optional WSDL extension elements were ignored.\n"); if ((warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) != 0) Console.WriteLine("Warning: one or more required WSDL extension elements were ignored.\n"); if ((warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) != 0) Console.WriteLine("Warning: one or more bindings were skipped.\n"); if ((warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) != 0) Console.WriteLine("one or more operations were skipped.\n"); if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) != 0) { Console.WriteLine("Warning: no classes were generated.\n"); return null; } if (warnings != 0) Console.WriteLine("Warnings were encountered. Review generated source comments for more details.\n"); } // change the base class CodeTypeDeclaration ctDecl = codeNamespace.Types[0]; codeNamespace.Types.Remove(ctDecl); ctDecl.BaseTypes[0] = new CodeTypeReference(DefaultNameSpace + ".SoapHttpClientProtocolEx"); codeNamespace.Types.Add(ctDecl); codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections")); CodeTypeDeclarationCollection codeTypeColl = new CodeTypeDeclarationCollection(); ArrayList colList = new ArrayList(); ArrayList allMembers = new ArrayList(); //added by william, workaround to fix the code FixCode(codeNamespace); foreach (CodeTypeDeclaration codeType in codeNamespace.Types) { allMembers.Clear(); foreach (CodeTypeMember codeMember in codeType.Members) { allMembers.Add(codeMember.Name); } CodeTypeMemberCollection codeMemberColl = new CodeTypeMemberCollection(); // // Collect the public fields of the type. // foreach (CodeTypeMember codeMember in codeType.Members) { CodeMemberMethod codeMethod = codeMember as CodeMemberMethod; if (codeMethod != null) { if ((codeMethod.Attributes & MemberAttributes.Public) == MemberAttributes.Public) { foreach (CodeAttributeDeclaration cadt in codeMethod.CustomAttributes) { if (cadt.Name.EndsWith("SoapDocumentMethodAttribute")) { codeMethod.CustomAttributes.Add(new CodeAttributeDeclaration(DefaultNameSpace + ".SoapExtensionExAttribute")); break; } } } } else { CodeMemberField codeField = codeMember as CodeMemberField; if (codeField != null) { if ((codeField.Attributes & MemberAttributes.Public) == MemberAttributes.Public) { codeField.Comments.Clear(); CodeTypeReference codeFieldRef = codeField.Type.ArrayElementType as CodeTypeReference; //skip 'System.Byte' if (codeFieldRef != null && !"System.Byte".Equals(codeFieldRef.BaseType)) { string name = codeFieldRef.BaseType; //Debug.WriteLine("Array BaseType name : " + name); string[] splstr = name.Split('.'); if (splstr.Length > 1) { string ns = String.Join(".", splstr, 0, splstr.Length - 1); codeNamespace.Imports.Add(new CodeNamespaceImport(ns)); name = (string)splstr.GetValue(splstr.Length - 1); } if (!colList.Contains(name)) { codeTypeColl.Add(this.CreateCollectionType(name)); colList.Add(name); } codeField.Type = new CodeTypeReference(name + "Collection"); } int val = allMembers.IndexOf(codeField.Name + "Specified"); codeMemberColl.Add(this.CreateProperty(codeField, val != -1)); } } } } // add the newly created public properties codeType.Members.AddRange(codeMemberColl); } codeNamespace.Types.AddRange(codeTypeColl); codeNamespace.Types.Add(CreateSoapHttpClientProtocolEx()); codeNamespace.Types.Add(CreateSoapExtensionExAttribute()); codeNamespace.Types.Add(CreateSoapExtensionEx()); if (this.mProjItem != null) { MemoryStream mem = new MemoryStream(); StreamWriter outputWriter = new StreamWriter(mem); CodeProvider.GenerateCodeFromCompileUnit(codeUnit, outputWriter, new CodeGeneratorOptions()); outputWriter.Flush(); mOutLog.OutputString("Code Generation Completed Successfully\n"); return mem.ToArray(); } else { CodeDomProvider generator = null; string fileExt = null; if (mLang.Equals(VB)) { generator = new Microsoft.VisualBasic.VBCodeProvider(); fileExt = VB; } //j# is not available. //else if (mLang.Equals(JS)) //{ // generator = new Microsoft.JScript.JScriptCodeProvider().CreateGenerator(); //} else { generator = new Microsoft.CSharp.CSharpCodeProvider(); fileExt = CS; } if (mOutputOneFileOption == true) { MemoryStream mem = new MemoryStream(); StreamWriter outputWriter = new StreamWriter(mem); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; generator.GenerateCodeFromCompileUnit(codeUnit, outputWriter, options);; outputWriter.Flush(); byte [] output = mem.ToArray(); BinaryWriter writer = new BinaryWriter(File.Open(mOutputPath + fileName, FileMode.Create)); writer.Write(output); writer.Close(); } else { CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection(); coll.AddRange(codeNamespace.Types); foreach (CodeTypeDeclaration codeType in coll) { codeNamespace.Types.Clear(); CodeTypeDeclarationCollection types = new CodeTypeDeclarationCollection(); codeNamespace.Types.Add(codeType); MemoryStream mem = new MemoryStream(); StreamWriter outputWriter = new StreamWriter(mem); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; generator.GenerateCodeFromCompileUnit(codeUnit, outputWriter, options);; outputWriter.Flush(); byte [] output = mem.ToArray(); string clsName = codeType.Name + "." + fileExt; BinaryWriter writer = new BinaryWriter(File.Open(mOutputPath + clsName, FileMode.Create)); writer.Write(output); writer.Close(); } } Console.WriteLine("Code Generation Completed Successfully\n"); return null; } } catch (Exception ex) { Console.WriteLine(ex.Message + "\n"); return null; } }