Add() public méthode

public Add ( CodeTypeDeclaration value ) : int
value CodeTypeDeclaration
Résultat int
		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);
		}
Exemple #2
0
 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);
     }
 }
Exemple #3
0
        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;

        }
Exemple #4
0
        public void PrepareNamespaceImportsTest()
        {
            var imports  = new[] { "System", "System.Linq", "MbUnit.Framework" };
            var expected = ".Tests.SubNamespace";
            var actual   = testObject.PrepareNamespaceImports(imports);

            Assert.AreElementsEqual(imports, actual.Select(e => e.Namespace));

            var expectedPrepared = new[] { "System", "System.Linq", "global::MbUnit.Framework" };

            typeDeclarations.Add(new CodeTypeDeclaration("Jedzia.Loves.Testing.MbUnit.SubClass"));
            this.testObject = new NamespaceDetector(this.typeDeclarations);
            actual          = testObject.PrepareNamespaceImports(imports);
            Assert.AreElementsEqual(expectedPrepared, actual.Select(e => e.Namespace));
        }
        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 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;
 }
 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;
        }
Exemple #11
0
 public void SetUp()
 {
     this.typeDeclarations = new System.CodeDom.CodeTypeDeclarationCollection();
     typeDeclarations.Add(new CodeTypeDeclaration("Jedzia.Loves.Testing.TheClassToTest"));
     this.testObject = new NamespaceDetector(this.typeDeclarations);
 }
        /// <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 AddRange ()
		{
			CodeTypeDeclaration td1 = new CodeTypeDeclaration ();
			CodeTypeDeclaration td2 = new CodeTypeDeclaration ();
			CodeTypeDeclaration td3 = new CodeTypeDeclaration ();

			CodeTypeDeclarationCollection coll1 = new CodeTypeDeclarationCollection ();
			coll1.Add (td1);
			coll1.Add (td2);

			CodeTypeDeclarationCollection coll2 = new CodeTypeDeclarationCollection ();
			coll2.Add (td3);
			coll2.AddRange (coll1);
			Assert.AreEqual (3, coll2.Count, "#1");
			Assert.AreEqual (1, coll2.IndexOf (td1), "#2");
			Assert.AreEqual (2, coll2.IndexOf (td2), "#3");
			Assert.AreEqual (0, coll2.IndexOf (td3), "#4");

			CodeTypeDeclarationCollection coll3 = new CodeTypeDeclarationCollection ();
			coll3.Add (td3);
			coll3.AddRange (new CodeTypeDeclaration[] { td1, td2 });
			Assert.AreEqual (3, coll2.Count, "#5");
			Assert.AreEqual (1, coll2.IndexOf (td1), "#6");
			Assert.AreEqual (2, coll2.IndexOf (td2), "#7");
			Assert.AreEqual (0, coll2.IndexOf (td3), "#8");
		}
		public void AddRange_Self ()
		{
			CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection ();
			coll.Add (new CodeTypeDeclaration ());
			Assert.AreEqual (1, coll.Count, "#1");
			coll.AddRange (coll);
			Assert.AreEqual (2, coll.Count, "#2");
		}
Exemple #15
0
        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
        }
        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);
        }
 protected void Rewrite(CodeTypeDeclarationCollection target, CodeTypeDeclarationCollection source, ref bool didRewrite)
 {
     foreach (CodeTypeDeclaration item in source)
     {
         target.Add(this.Rewrite(item, ref didRewrite));
     }
 }
		public void Remove ()
		{
			CodeTypeDeclaration td1 = new CodeTypeDeclaration ();
			CodeTypeDeclaration td2 = new CodeTypeDeclaration ();

			CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection ();
			coll.Add (td1);
			coll.Add (td2);
			Assert.AreEqual (2, coll.Count, "#1");
			Assert.AreEqual (0, coll.IndexOf (td1), "#2");
			Assert.AreEqual (1, coll.IndexOf (td2), "#3");
			coll.Remove (td1);
			Assert.AreEqual (1, coll.Count, "#4");
			Assert.AreEqual (-1, coll.IndexOf (td1), "#5");
			Assert.AreEqual (0, coll.IndexOf (td2), "#6");
		}
		public void Constructor2 ()
		{
			CodeTypeDeclaration td1 = new CodeTypeDeclaration ();
			CodeTypeDeclaration td2 = new CodeTypeDeclaration ();

			CodeTypeDeclarationCollection c = new CodeTypeDeclarationCollection ();
			c.Add (td1);
			c.Add (td2);

			CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection (c);
			Assert.AreEqual (2, coll.Count, "#1");
			Assert.AreEqual (0, coll.IndexOf (td1), "#2");
			Assert.AreEqual (1, coll.IndexOf (td2), "#3");
		}
 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;
 }
        /// <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 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);
            }
        }
		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;
			}
		}
        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;

        }
 internal static void AddDelegate(CodeTypeDeclarationCollection codeClasses, string handlerType, string handlerArgs)
 {
     CodeTypeDelegate delegate2 = new CodeTypeDelegate(handlerType);
     delegate2.CustomAttributes.Add(GeneratedCodeAttribute);
     delegate2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
     delegate2.Parameters.Add(new CodeParameterDeclarationExpression(handlerArgs, "e"));
     delegate2.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     codeClasses.Add(delegate2);
 }
Exemple #26
0
 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 Add_Null () {
			CodeTypeDeclarationCollection coll = new CodeTypeDeclarationCollection ();
			coll.Add ((CodeTypeDeclaration) null);
		}