Add() public method

public Add ( CodeTypeMember value ) : int
value CodeTypeMember
return int
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generatorContext, CodeTypeMemberCollection members)
		{
			string className = "AIDX_" + Guid.NewGuid().ToString("N");
			string name = table.Get("name").String;
			bool setter = table.Get("setter").Boolean;

			CodeTypeDeclaration classCode = new CodeTypeDeclaration(className);

			classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed;

			classCode.BaseTypes.Add(typeof(ArrayMemberDescriptor));

			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = MemberAttributes.Assembly;
			classCode.Members.Add(ctor);

			ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(name));
			ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(setter));
			
			DynValue vparams = table.Get("params");

			if (vparams.Type == DataType.Table)
			{
				List<HardwireParameterDescriptor> paramDescs = HardwireParameterDescriptor.LoadDescriptorsFromTable(vparams.Table);

				ctor.BaseConstructorArgs.Add(new CodeArrayCreateExpression(typeof(ParameterDescriptor), paramDescs.Select(e => e.Expression).ToArray()));
			}

			members.Add(classCode);
			return new CodeExpression[] { new CodeObjectCreateExpression(className) };
		}
 internal static void AddCallbackDeclaration(CodeTypeMemberCollection members, string callbackMember)
 {
     CodeMemberField field = new CodeMemberField {
         Type = new CodeTypeReference(typeof(SendOrPostCallback)),
         Name = callbackMember
     };
     members.Add(field);
 }
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generatorContext, CodeTypeMemberCollection members)
		{
			string className = "DVAL_" + Guid.NewGuid().ToString("N");
			DynValue kval = table.Get("value");

			DynValue vtype = table.Get("type");
			DynValue vstaticType = table.Get("staticType");

			string type = (vtype.Type == DataType.String) ? vtype.String : null;
			string staticType = (vstaticType.Type == DataType.String) ? vstaticType.String : null;


			CodeTypeDeclaration classCode = new CodeTypeDeclaration(className);

			classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed;

			classCode.BaseTypes.Add(typeof(DynValueMemberDescriptor));

			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = MemberAttributes.Assembly;
			classCode.Members.Add(ctor);


			if (type == null)
			{
				Table tbl = new Table(null);
				tbl.Set(1, kval);
				string str = tbl.Serialize();

				ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(table.Get("name").String));
				ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(str));
			}
			else if (type == "userdata")
			{
				ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(table.Get("name").String));

				CodeMemberProperty p = new CodeMemberProperty();
				p.Name = "Value";
				p.Type = new CodeTypeReference(typeof(DynValue));
				p.Attributes = MemberAttributes.Override | MemberAttributes.Public;
				p.GetStatements.Add(
					new CodeMethodReturnStatement(
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(UserData)),
							"CreateStatic", new CodeTypeOfExpression(staticType))));

				classCode.Members.Add(p);
			}


			members.Add(classCode);
			return new CodeExpression[] { new CodeObjectCreateExpression(className) };
		}
		protected override void AddPageFields (CodeTypeMemberCollection members)
		{
			base.AddPageFields (members);

			executableField = new CodeMemberField {
            Name = "_Executable",
            Type = new CodeTypeReference(typeof(XQueryExecutable)),
            Attributes = MemberAttributes.Private | MemberAttributes.Static
         };

			members.Add (executableField);
		}
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeTypeMemberCollection coll = new CodeTypeMemberCollection (array);
			coll.CopyTo (array, 0);
			Assert.AreEqual (1, coll.Add (ctm), "Add");
			Assert.AreSame (ctm, coll[0], "this[int]");
			coll.AddRange (array);
			coll.AddRange (coll);
			Assert.IsTrue (coll.Contains (ctm), "Contains");
			Assert.AreEqual (0, coll.IndexOf (ctm), "IndexOf");
			coll.Insert (0, ctm);
			coll.Remove (ctm);
		}
        /// <summary>
        /// Generates the Request-classes for all methods in a resource.
        /// </summary>
        public CodeTypeMemberCollection GenerateRequestClasses(CodeTypeDeclaration resourceClass, IResource resource)
        {
            CodeTypeMemberCollection newMembers = new CodeTypeMemberCollection();
            IList<string> usedNames = new List<string>(GeneratorUtils.GetUsedWordsFromMembers(resourceClass.Members));
            foreach (IMethod method in resource.Methods.Values)
            {
                // Generate the request class and add it to the result collection.
                CodeTypeDeclaration requestClass = GenerateRequestClass(resource, method, resourceClass, usedNames);
                newMembers.Add(requestClass);
                usedNames.Add(requestClass.Name);
            }

            return newMembers;
        }
		protected override void AddPageFields (CodeTypeMemberCollection members)
		{
         
			base.AddPageFields (members);

			executableField = new CodeMemberField { 
            Name = "_Executable",
            Type = new CodeTypeReference(typeof(XsltExecutable)),
            Attributes = MemberAttributes.Private | MemberAttributes.Static
         };
			members.Add (executableField);

			if (parser.PageType == XsltPageType.AssociatedStylesheet) {
            
				initialContextNodeField = new CodeMemberField { 
               Name = "_initialContextNode",
               Type = new CodeTypeReference(typeof(IXPathNavigable)),
               Attributes = MemberAttributes.Private | MemberAttributes.Static
            };

				members.Add (initialContextNodeField);
			}
		}
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator,
			CodeTypeMemberCollection members)
		{
			string type = (string)table["$key"];
			string className = "TYPE_" + Guid.NewGuid().ToString("N");

			CodeTypeDeclaration classCode = new CodeTypeDeclaration(className);

			classCode.Comments.Add(new CodeCommentStatement("Descriptor of " + type));


			classCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Descriptor of " + type));
			
			classCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));


			classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed;
			
			classCode.BaseTypes.Add(typeof(HardwiredUserDataDescriptor));

			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = MemberAttributes.Assembly;
			ctor.BaseConstructorArgs.Add(new CodeTypeOfExpression(type));

			classCode.Members.Add(ctor);

			generator.DispatchTablePairs(table.Get("members").Table,
				classCode.Members, (key, exp) =>
				{
					var mname = new CodePrimitiveExpression(key);

					ctor.Statements.Add(new CodeMethodInvokeExpression(
						new CodeThisReferenceExpression(), "AddMember", mname, exp));
				});

			generator.DispatchTablePairs(table.Get("metamembers").Table,
				classCode.Members, (key, exp) =>
				{
					var mname = new CodePrimitiveExpression(key);
					
					ctor.Statements.Add(new CodeMethodInvokeExpression(
						new CodeThisReferenceExpression(), "AddMetaMember", mname, exp));
				});

			members.Add(classCode);

			return new CodeExpression[] {
					new CodeObjectCreateExpression(className)
			};
		}
        //workaround to fix the code
        private void FixCode(CodeNamespace codeNamespace)
        {
			//fix base64Binary issue
			/*foreach (CodeTypeDeclaration ctd in codeNamespace.Types)
			{
				if ("Base64BinaryType".Equals(ctd.Name))
				{
					CodeTypeMemberCollection ctmc = new CodeTypeMemberCollection();
					foreach (CodeMemberField cmf in ctd.Members)
					{
						if ("Value".Equals(cmf.Name))
						{
							ctmc.Add(cmf);
						}
					}

					foreach(CodeTypeMember ctm in ctmc)
					{
						ctd.Members.Remove(ctm);
					}

				    ctd.Members.Add(new CodeSnippetTypeMember("        private byte[] mValue;" + Environment.NewLine + Environment.NewLine));
                    ctd.Members.Add(new CodeSnippetTypeMember("        ///<summary></summary>" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("        [System.Xml.Serialization.XmlTextAttribute(DataType=\"base64Binary\")]" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("        public byte[] Value {" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("            get {" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("                return this.mValue;" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("            }" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("            set {" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("                this.mValue = value;" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("            }" + Environment.NewLine));
					ctd.Members.Add(new CodeSnippetTypeMember("        }" + Environment.NewLine + Environment.NewLine));
				}
			}*/
			
			
			//UploadSiteHostedPictures related data types should be generated for
			//EPS usage
			/*
			//remove UploadSiteHostedPictures related types
            CodeTypeDeclarationCollection ctdc = new CodeTypeDeclarationCollection();
            foreach (CodeTypeDeclaration ctd in codeNamespace.Types)
            {
                if (ctd.Name.IndexOf("UploadSiteHostedPictures") != -1)
                {
                    ctdc.Add(ctd);
                }
            }
            foreach (CodeTypeDeclaration ctd in ctdc)
            {
                codeNamespace.Types.Remove(ctd);
            }

            //remove UploadSiteHostedPictures related attributes
            foreach (CodeTypeDeclaration ctd in codeNamespace.Types)
            {
                if (ctd.Name.IndexOf("Abstract") == 0)
                {
                    CodeAttributeDeclarationCollection cadc = new CodeAttributeDeclarationCollection();
                    foreach (CodeAttributeDeclaration cad in ctd.CustomAttributes)
                    {
                        foreach (CodeAttributeArgument caa in cad.Arguments)
                        {
                            CodeTypeOfExpression ctoe = (caa.Value) as CodeTypeOfExpression;
                            if (ctoe != null && ctoe.Type.BaseType.IndexOf("UploadSiteHostedPictures") != -1)
                            {
                                cadc.Add(cad);
                            }
                        }
                    }
                    foreach (CodeAttributeDeclaration cad in cadc)
                    {
                        ctd.CustomAttributes.Remove(cad);
                    }
                }
            }*/

            //add summary comments on some constructors
            foreach (CodeTypeDeclaration ctd in codeNamespace.Types)
            {
                foreach (CodeTypeMember ctm in ctd.Members)
                {
                    if ((ctm is CodeConstructor) && ctm.Comments.Count == 0)
                    {
                        ctm.Comments.AddRange(this.GetSummaryStatements());
                    }
                }
            }

            //remove UploadSiteHostedPictures related methods
            foreach (CodeTypeDeclaration ctd in codeNamespace.Types)
            {
                CodeTypeMemberCollection ctmc = new CodeTypeMemberCollection();
                foreach (CodeTypeMember ctm in ctd.Members)
                {
                    CodeMemberMethod cmm = ctm as CodeMemberMethod;
                    if (cmm != null && cmm.Name.IndexOf("UploadSiteHostedPictures") != -1)
                    {
                        ctmc.Add(ctm);
                    }
                }
                foreach (CodeTypeMember ctm in ctmc)
                {
                    ctd.Members.Remove(ctm);
                }
            }
        }
示例#10
0
	public void enumerator_list(
		string enumName, CodeTypeMemberCollection members
	) //throws RecognitionException, TokenStreamException
{

		returnAST = null;
		ASTPair currentAST = new ASTPair();
		AST enumerator_list_AST = null;

				string s1 = string.Empty;
				string s2 = string.Empty;
				string expr1 = string.Empty;
				string expr2 = string.Empty;


		try {      // for error handling
			s1=enumerator(ref expr1);
			if (0 == inputState.guessing)
			{
				astFactory.addASTChild(ref currentAST, returnAST);
			}
			{    // ( ... )*
				for (;;)
				{
					if ((LA(1)==COMMA))
					{
						AST tmp264_AST = null;
						tmp264_AST = astFactory.create(LT(1));
						astFactory.addASTChild(ref currentAST, tmp264_AST);
						match(COMMA);
						s2=enumerator(ref expr2);
						if (0 == inputState.guessing)
						{
							astFactory.addASTChild(ref currentAST, returnAST);
						}
						if (0==inputState.guessing)
						{

												members.Add(IDLConversions.CreateEnumMember(enumName, s1, expr1));
												s1 = s2;
												expr1 = expr2;

						}
					}
					else
					{
						goto _loop174_breakloop;
					}

				}
_loop174_breakloop:				;
			}    // ( ... )*
			if (0==inputState.guessing)
			{

							if (s1 != string.Empty)
								members.Add(IDLConversions.CreateEnumMember(enumName, s1, expr1));

			}
			enumerator_list_AST = currentAST.root;
		}
		catch (RecognitionException ex)
		{
			if (0 == inputState.guessing)
			{
				reportError(ex);
				recover(ex,tokenSet_9_);
			}
			else
			{
				throw ex;
			}
		}
		returnAST = enumerator_list_AST;
	}
 private void BuildMethod(CodeTypeMemberCollection members, MethodInfo method, object[] parameters)
 {
     CodeMemberMethod method1 = new CodeMemberMethod();
     method1.Name = "Invoke" + method.Name;
     mainMethod.Statements.Add(new CodeMethodInvokeExpression(null, method1.Name, new CodeExpression[0]));
     method1.Attributes = MemberAttributes.Public | MemberAttributes.Static;
     members.Add(method1);
     CodeExpression expression1 = BuildProxy(method1.Statements, method);
     CodeMethodInvokeExpression expression2 =
         new CodeMethodInvokeExpression(expression1, method.Name, new CodeExpression[0]);
     BuildParameters(method1.Statements, method, parameters, expression2.Parameters);
     if (method.ReturnType == typeof (void))
     {
         method1.Statements.Add(new CodeExpressionStatement(expression2));
     }
     else
     {
         string text1 = GetUniqueVariableName(method.Name + "Result", method1.Statements);
         method1.Statements.Add(
             new CodeVariableDeclarationStatement(method.ReturnType.FullName, text1, expression2));
         BuildDumpInvoke(method1.Statements, "result", new CodeVariableReferenceExpression(text1));
     }
     ParameterInfo[] infoArray1 = method.GetParameters();
     for (int num1 = 0; num1 < infoArray1.Length; num1++)
     {
         ParameterInfo info1 = infoArray1[num1];
         if (info1.IsOut || info1.ParameterType.IsByRef)
         {
             BuildDumpInvoke(method1.Statements, info1.Name,
                             ((CodeDirectionExpression) expression2.Parameters[num1]).Expression);
         }
     }
 }
示例#12
0
 protected void Rewrite(CodeTypeMemberCollection target, CodeTypeMemberCollection source, ref bool didRewrite)
 {
     foreach (CodeTypeMember item in source)
     {
         target.Add(this.Rewrite(item, ref didRewrite));
     }
 }
 protected override void DbusServiceTargetField(CodeTypeReference typerefDbusInterface, CodeTypeReference typerefDbusMarshal, CodeTypeMemberCollection members)
 {
     CodeMemberField memberProxy = new CodeMemberField(typerefDbusInterface, CodeBuilderCommon.targetName);
     memberProxy.Attributes = MemberAttributes.Private;
     members.Add(memberProxy);
 }
示例#14
0
 static CodeTypeMemberCollection BuildManyToOneRelationships(EntityMetadata entity, ServiceProvider serviceProvider)
 {
     var members = new CodeTypeMemberCollection();
     if (entity.ManyToOneRelationships != null)
     {
         foreach (var metadata in from metadata in entity.ManyToOneRelationships
                                                            orderby metadata.SchemaName
                                                            select metadata)
         {
             var entityMetadata = GetEntityMetadata(metadata.ReferencedEntity, serviceProvider);
             if (serviceProvider.CodeFilterService.GenerateEntity(entityMetadata, serviceProvider) && serviceProvider.CodeFilterService.GenerateRelationship(metadata, entityMetadata, serviceProvider))
             {
                 var member = BuildManyToOne(entity, entityMetadata, metadata, serviceProvider);
                 members.Add(member);
             }
             else
             {
                 Trace.TraceInformation("Skipping {0}.ManyToOne {1} from being generated.", new object[] {entity.LogicalName, metadata.SchemaName});
             }
         }
     }
     return members;
 }
示例#15
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Returns a copy of the collection of the methods of the base type
		/// </summary>
		/// <param name="typeName">The name of the base type</param>
		/// <param name="nameSpace">The namespace which defines the base types</param>
		/// <param name="interfaceType">[out] Returns the interface type of the base type</param>
		/// <returns>A copy of the collection of the methods</returns>
		/// ------------------------------------------------------------------------------------
		private CodeTypeMemberCollection GetBaseMembers(string typeName,
			CodeNamespace nameSpace, out string interfaceType)
		{
			interfaceType = null;
			if (nameSpace.UserData[typeName] == null)
			{
				System.Console.WriteLine("Error: base type {0} not found!", typeName);
				return null;
			}
			else
			{
				CodeTypeDeclaration type = (CodeTypeDeclaration)nameSpace.UserData[typeName];
				interfaceType = (string)type.UserData["InterfaceType"];
				CodeTypeMemberCollection coll = new CodeTypeMemberCollection();

				/// All base class members must be preceded by new
				foreach (CodeTypeMember member in type.Members)
				{
					CodeTypeMember newMember;
					if (member is CodeMemberMethod)
					{
						newMember = new CodeMemberMethod();
					}
					else if (member is CodeMemberProperty)
						newMember = new CodeMemberProperty();
					else
					{
						Console.WriteLine("Unhandled member type: {0}", member.GetType());
						continue;
					}

					newMember.Attributes = member.Attributes | MemberAttributes.New;
					newMember.Attributes = newMember.Attributes & ~MemberAttributes.AccessMask |
						MemberAttributes.Public;
					newMember.Comments.AddRange(member.Comments);
					newMember.CustomAttributes.AddRange(member.CustomAttributes);
					newMember.Name = member.Name;
					if (member is CodeMemberMethod)
					{
						((CodeMemberMethod)newMember).ImplementationTypes.AddRange(((CodeMemberMethod)member).ImplementationTypes);
						((CodeMemberMethod)newMember).Parameters.AddRange(((CodeMemberMethod)member).Parameters);
						((CodeMemberMethod)newMember).ReturnType = ((CodeMemberMethod)member).ReturnType;
						((CodeMemberMethod)newMember).ReturnTypeCustomAttributes.AddRange(((CodeMemberMethod)member).ReturnTypeCustomAttributes);
					}
					else if (member is CodeMemberProperty)
					{
						((CodeMemberProperty)newMember).ImplementationTypes.AddRange(((CodeMemberProperty)member).ImplementationTypes);
						((CodeMemberProperty)newMember).Type = ((CodeMemberProperty)member).Type;
						((CodeMemberProperty)newMember).HasGet = ((CodeMemberProperty)member).HasGet;
						((CodeMemberProperty)newMember).HasSet = ((CodeMemberProperty)member).HasSet;
					}
					foreach (DictionaryEntry entry in member.UserData)
						newMember.UserData.Add(entry.Key, entry.Value);

					coll.Add(newMember);
				}

				return coll;
			}
		}
示例#16
0
        public void FindTypeMemberByNameTest()
        {
            CodeTypeMemberCollection collection = null;

            Assert.Throws(typeof(ArgumentNullException), () => collection.FindTypeMemberByName(null));
            Assert.Throws(typeof(ArgumentNullException), () => collection.FindTypeMemberByName("name"));

            collection = new CodeTypeMemberCollection(new[] { new CodeTypeMember(), });

            Assert.Throws(typeof(ArgumentNullException), () => collection.FindTypeMemberByName(null));
            Assert.Throws(typeof(ArgumentException), () => collection.FindTypeMemberByName(""));

            Assert.IsNull(collection.FindTypeMemberByName("AnyString"));

            collection.Add(CreateMemberProperty("Fish"));

            CodeTypeMember member = new CodeMemberMethod();
            member.Name = "Method";
            collection.Add(member);

            member = new CodeMemberField();
            member.Name = "Field";
            collection.Add(member);

            member = new CodeMemberEvent();
            member.Name = "Event";
            collection.Add(member);

            collection.Add(new CodeTypeDeclaration() { Name = "Class" });

            Assert.IsNull(collection.FindTypeMemberByName("AnyString"));
            Assert.IsNull(collection.FindTypeMemberByName("Method"));
            Assert.IsNull(collection.FindTypeMemberByName("Field"));
            Assert.IsNull(collection.FindTypeMemberByName("Event"));
            Assert.IsNull(collection.FindTypeMemberByName("Fish"));

            Assert.IsNotNull(collection.FindTypeMemberByName("Class"));
            Assert.AreEqual("Class", collection.FindTypeMemberByName("Class").Name);
        }
示例#17
0
 private static CodeTypeMemberCollection GetMethodsWithNameLike(CodeTypeDeclaration source, string name)
 {
     var result = new CodeTypeMemberCollection();
     foreach (CodeTypeMember method in source.Members)
     {
         if ((method is CodeMemberMethod) && (method.Name.StartsWith(name)))
         {
             result.Add(method);
         }
     }
     return result;
 }
示例#18
0
        private CodeTypeMemberCollection GenerateComplexType()
        {
            var result = new CodeTypeMemberCollection();

            result.Add(GenerateSwitchComplexType(false));
            result.Add(GenerateSwitchComplexType(true));
            //XmlXml
            result.Add(GenerateTypeXmlXml());
            result.Add(GenerateTypeArrayXmlXml());
            result.Add(type.IsEnum ? GenerateEnumTypeXElement() : GenerateTypeXElement());
            //DataXml
            result.Add(GenerateTypeDataXml());
            result.Add(GenerateTypeArrayDataXml());
            //DataJson
            result.Add(GenerateTypeDataJson());
            result.Add(GenerateTypeArrayDataJson());
            if (!type.IsEnum) result.Add(GenerateTypeJSONObject());
            result.Add(GenerateTypeArrayJSONArray());

            return result;
        }
示例#19
0
        public void FindMemberByNameTest()
        {
            CodeTypeMemberCollection collection = null;

            Assert.Throws(typeof(ArgumentNullException), () => collection.FindMemberByName(null));
            Assert.Throws(typeof(ArgumentNullException), () => collection.FindMemberByName("name"));

            collection = new CodeTypeMemberCollection(new[] { new CodeTypeMember(), });

            Assert.Throws(typeof(ArgumentNullException), () => collection.FindMemberByName(null));
            Assert.Throws(typeof(ArgumentException), () => collection.FindMemberByName(""));

            Assert.IsNull(collection.FindMemberByName("AnyString"));

            collection.Add(CreateMemberProperty("Fish"));
            collection.Add(CreateMemberProperty("Cat"));
            collection.Add(CreateMemberProperty("Tree"));
            collection.Add(CreateMemberProperty("House"));

            CodeTypeMember willAlsoFind = new CodeMemberMethod();
            willAlsoFind.Name = "WillAlsoFindMethod";
            collection.Add(willAlsoFind);

            willAlsoFind = new CodeMemberField();
            willAlsoFind.Name = "WillAlsoFindField";
            collection.Add(willAlsoFind);

            willAlsoFind = new CodeMemberEvent();
            willAlsoFind.Name = "WillAlsoFindEvent";
            collection.Add(willAlsoFind);

            Assert.IsNull(collection.FindMemberByName("AnyString"));
            Assert.IsNotNull(collection.FindMemberByName("WillAlsoFindMethod"));
            Assert.IsNotNull(collection.FindMemberByName("WillAlsoFindField"));
            Assert.IsNotNull(collection.FindMemberByName("WillAlsoFindEvent"));
            Assert.IsNotNull(collection.FindMemberByName("Fish"));
            Assert.IsNotNull(collection.FindMemberByName("Cat"));
            Assert.IsNotNull(collection.FindMemberByName("Tree"));
            Assert.IsNotNull(collection.FindMemberByName("House"));

            Assert.AreEqual("Fish", collection.FindMemberByName("Fish").Name);
            Assert.AreEqual("Cat", collection.FindMemberByName("Cat").Name);
            Assert.AreEqual("Tree", collection.FindMemberByName("Tree").Name);
            Assert.AreEqual("House", collection.FindMemberByName("House").Name);
        }
		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;
			}
		}
示例#21
0
 static CodeTypeMemberCollection BuildManyToManyRelationships(EntityMetadata entity, ServiceProvider serviceProvider)
 {
     var members = new CodeTypeMemberCollection();
     if (entity.ManyToManyRelationships != null)
     {
         foreach (var metadata in from metadata in entity.ManyToManyRelationships
                                                             orderby metadata.SchemaName
                                                             select metadata)
         {
             var entityLogicalName = (entity.LogicalName != metadata.Entity1LogicalName) ? metadata.Entity1LogicalName : metadata.Entity2LogicalName;
             var entityMetadata = GetEntityMetadata(entityLogicalName, serviceProvider);
             if (serviceProvider.CodeFilterService.GenerateEntity(entityMetadata, serviceProvider) && serviceProvider.CodeFilterService.GenerateRelationship(metadata, entityMetadata, serviceProvider))
             {
                 if (entityMetadata.LogicalName != entity.LogicalName)
                 {
                     EntityRole? reflexiveRole = null;
                     var propertyName = serviceProvider.NamingService.GetNameForRelationship(entity, metadata, reflexiveRole, serviceProvider);
                     EntityRole? entityRole = null;
                     var member = BuildManyToMany(entity, entityMetadata, metadata, propertyName, entityRole, serviceProvider);
                     members.Add(member);
                 }
                 else
                 {
                     var str3 = serviceProvider.NamingService.GetNameForRelationship(entity, metadata, 0, serviceProvider);
                     var member2 = BuildManyToMany(entity, entityMetadata, metadata, str3, 0, serviceProvider);
                     members.Add(member2);
                     var str4 = serviceProvider.NamingService.GetNameForRelationship(entity, metadata, EntityRole.Referenced, serviceProvider);
                     var member3 = BuildManyToMany(entity, entityMetadata, metadata, str4, EntityRole.Referenced, serviceProvider);
                     members.Add(member3);
                 }
             }
             else
             {
                 Trace.TraceInformation("Skipping {0}.ManyToMany {1} from being generated.", new object[] {entity.LogicalName, metadata.SchemaName});
             }
         }
     }
     return members;
 }
		public CodeExpression[] Generate(Table table, HardwireCodeGenerationContext generator, CodeTypeMemberCollection members)
		{
			bool isStatic = table.Get("static").Boolean;
			string memberType = table.Get("type").String;
			string name = table.Get("name").String;
			string decltype = table.Get("decltype").String;
			bool declvtype = table.Get("declvtype").Boolean;
			bool canWrite = table.Get("write").Boolean;
			bool canRead = table.Get("read").Boolean;

			if (declvtype && canWrite)
			{
				generator.Warning("Member '{0}.{1}::Set' will be a no-op, as it's a member of a value type.", decltype, name);
			}

			MemberDescriptorAccess access = 0;

			if (canWrite)
				access = access | MemberDescriptorAccess.CanWrite;

			if (canRead)
				access = access | MemberDescriptorAccess.CanRead;


			string className = GetPrefix() + "_" + Guid.NewGuid().ToString("N");

			CodeTypeDeclaration classCode = new CodeTypeDeclaration(className);

			classCode.TypeAttributes = System.Reflection.TypeAttributes.NestedPrivate | System.Reflection.TypeAttributes.Sealed;

			classCode.BaseTypes.Add(typeof(HardwiredMemberDescriptor));

			// protected HardwiredMemberDescriptor(Type memberType, string name, bool isStatic, MemberDescriptorAccess access)

			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = MemberAttributes.Assembly;
			ctor.BaseConstructorArgs.Add(new CodeTypeOfExpression(memberType));
			ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(name));
			ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(isStatic));
			ctor.BaseConstructorArgs.Add(new CodeCastExpression(typeof(MemberDescriptorAccess), new CodePrimitiveExpression((int)access)));
			classCode.Members.Add(ctor);

			var thisExp = isStatic
				? (CodeExpression)(new CodeTypeReferenceExpression(decltype))
				: (CodeExpression)(new CodeCastExpression(decltype, new CodeVariableReferenceExpression("obj")));

			if (canRead)
			{
				var memberExp = GetMemberAccessExpression(thisExp, name);
				//	protected virtual object GetValueImpl(Script script, object obj)
				CodeMemberMethod m = new CodeMemberMethod();
				classCode.Members.Add(m);
				m.Name = "GetValueImpl";
				m.Attributes = MemberAttributes.Override | MemberAttributes.Family;
				m.ReturnType = new CodeTypeReference(typeof(object));
				m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Script), "script"));
				m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
				m.Statements.Add(new CodeMethodReturnStatement(memberExp));
			}

			if (canWrite)
			{
				//	protected virtual object GetValueImpl(Script script, object obj)
				CodeMemberMethod m = new CodeMemberMethod();
				classCode.Members.Add(m);
				m.Name = "SetValueImpl"; 
				m.Attributes = MemberAttributes.Override | MemberAttributes.Family;
				m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Script), "script"));
				m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
				m.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "value"));

				var valExp = new CodeCastExpression(memberType, new CodeVariableReferenceExpression("value"));

				if (isStatic)
				{
					var e = GetMemberAccessExpression(thisExp, name);
					m.Statements.Add(new CodeAssignStatement(e, valExp));
				}
				else
				{
					m.Statements.Add(new CodeVariableDeclarationStatement(decltype, "tmp", thisExp));

					var memberExp = GetMemberAccessExpression(new CodeVariableReferenceExpression("tmp"), name);

					m.Statements.Add(new CodeAssignStatement(memberExp, valExp));
				}
			}

			members.Add(classCode);
			return new CodeExpression[] { new CodeObjectCreateExpression(className) };
		}
示例#23
0
 static CodeTypeMemberCollection BuildOneToManyRelationships(EntityMetadata entity, ServiceProvider serviceProvider)
 {
     var members = new CodeTypeMemberCollection();
     if (entity.OneToManyRelationships != null)
     {
         foreach (var metadata in from metadata in entity.OneToManyRelationships
                                                            orderby metadata.SchemaName
                                                            select metadata)
         {
             var entityMetadata = GetEntityMetadata(metadata.ReferencingEntity, serviceProvider);
             if (string.Equals(metadata.SchemaName, "calendar_calendar_rules", StringComparison.Ordinal) || string.Equals(metadata.SchemaName, "service_calendar_rules", StringComparison.Ordinal))
             {
                 members.Add(BuildCalendarRuleAttribute(entity, entityMetadata, metadata, serviceProvider));
             }
             else if (serviceProvider.CodeFilterService.GenerateEntity(entityMetadata, serviceProvider) && serviceProvider.CodeFilterService.GenerateRelationship(metadata, entityMetadata, serviceProvider))
             {
                 members.Add(BuildOneToMany(entity, entityMetadata, metadata, serviceProvider));
             }
             else
             {
                 Trace.TraceInformation("Skipping {0}.OneToMany {1} from being generated.", new object[] {entity.LogicalName, metadata.SchemaName});
             }
         }
     }
     return members;
 }
示例#24
0
        private bool CreateItemProperty(string propertyName, TemplateFieldItem sitecoreField, CodeTypeMemberCollection members)
        {
            var type = _fieldMappingProvider.GetFieldType(sitecoreField);

            if(type == null)
            {
                Log.Warn("Synthesis: Field type resolution for " + sitecoreField.InnerItem.Parent.Parent.Name + "::" + sitecoreField.Name + " failed; no mapping found for field type " + sitecoreField.Type, this);
                return false;
            }

            var backingFieldName = "_" + propertyName[0].ToString(CultureInfo.InvariantCulture).ToLower() + propertyName.Substring(1);
            var backingField = new CodeMemberField(new CodeTypeReference(type.InternalFieldType), backingFieldName);

            backingField.Attributes = MemberAttributes.Private;

            var property = new CodeMemberProperty
                {
            // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
            // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
                    Type = new CodeTypeReference(type.PublicFieldType),
                    Name = propertyName,
                    HasGet = true
                };

            // add [IndexField] attribute
            property.CustomAttributes.Add(GetIndexFieldAttribute(sitecoreField.Name));

            // if(backingField == null)
            //	backingField = new SynthesisFieldType(new Lazy<Field>(() => InnerItem.Fields["xxx"], GetSearchFieldValue("index-field-name"));

            var initializerLambda = new CodeSnippetExpression(string.Format("new global::Synthesis.FieldTypes.LazyField(() => InnerItem.Fields[\"{0}\"], \"{1}\", \"{2}\")", sitecoreField.ID, sitecoreField.Template.InnerItem.Paths.FullPath, sitecoreField.Name));
            var initializerSearchReference = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(),
                                                                            "GetSearchFieldValue",
                                                                            new CodePrimitiveExpression(_indexFieldNameTranslator.GetIndexFieldName(sitecoreField.Name)));

            var backingFieldNullCheck = new CodeConditionStatement();
            backingFieldNullCheck.Condition = new CodeSnippetExpression(string.Format("{0} == null", backingFieldName));
            backingFieldNullCheck.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(backingFieldName), new CodeObjectCreateExpression(type.InternalFieldType, initializerLambda, initializerSearchReference)));
            property.GetStatements.Add(backingFieldNullCheck);

            // return backingField;
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(backingFieldName)));

            AddCommentsToFieldProperty(property, sitecoreField);

            members.Add(backingField);
            members.Add(property);

            return true;
        }
示例#25
0
        public CodeTypeMemberCollection ParseMembers()
        {
            CodeTypeMemberCollection mc = new CodeTypeMemberCollection();

            while (TokenType != CDILToken.EOF && !IsKeyword("end"))
            {
                CodeTypeMember member = ParseMember();
                mc.Add(member);
            }
            return mc;
        }
示例#26
0
 private void BuildMethod(CodeTypeMemberCollection members, MethodInfo method, object[] parameters)
 {
     CodeMemberMethod method2 = new CodeMemberMethod();
     method2.Name = "Invoke" + method.Name;
     this.mainMethod.Statements.Add(new CodeMethodInvokeExpression(null, method2.Name, new CodeExpression[0]));
     method2.Attributes = MemberAttributes.Public | MemberAttributes.Static;
     members.Add(method2);
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(this.BuildProxy(method2.Statements, method), method.Name, new CodeExpression[0]);
     this.BuildParameters(method2.Statements, method, parameters, expression.Parameters);
     if (method.ReturnType == typeof(void))
     {
         method2.Statements.Add(new CodeExpressionStatement(expression));
     }
     else
     {
         string uniqueVariableName = GetUniqueVariableName(method.Name + "Result", method2.Statements);
         method2.Statements.Add(new CodeVariableDeclarationStatement(method.ReturnType.FullName, uniqueVariableName, expression));
         this.BuildDumpInvoke(method2.Statements, "result", new CodeVariableReferenceExpression(uniqueVariableName));
     }
     ParameterInfo[] infoArray = method.GetParameters();
     for (int i = 0; i < infoArray.Length; i++)
     {
         ParameterInfo info = infoArray[i];
         if (info.IsOut || info.ParameterType.IsByRef)
         {
             this.BuildDumpInvoke(method2.Statements, info.Name, ((CodeDirectionExpression) expression.Parameters[i]).Expression);
         }
     }
 }
		protected override void AddPageProperties (CodeTypeMemberCollection members)
		{
			base.AddPageProperties (members);

			CodeMemberProperty executableProperty = new CodeMemberProperty {
            Name = "Executable",
            Type = executableField.Type,
            Attributes = MemberAttributes.Public | MemberAttributes.Override,
            HasSet = false,
            HasGet = true,
         };
			executableProperty.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (PageTypeReferenceExpression, executableField.Name)));

			members.Add (executableProperty);
		}
示例#28
0
 public CodeTypeMemberCollection AddMethods(TableViewTableTypeBase baseobj)
 {
     CodeTypeMemberCollection ctmc = new CodeTypeMemberCollection();
     ctmc.Add(BuildIsDirtyMethod(baseobj));
     return ctmc;
 }
		public ShaderDom(SourceShader source, string techniqueName, Platform platform, CompileDirectives directives)
		{
			this.domList = new List<DomBase>();
			this.domList.Add(this);

			//add custom dom's
			this.domList.Add(new ShaderBytes(source, techniqueName, platform));

			//needs to be passed to the registers as an interface provider
			ConstantSetup constantes = new ConstantSetup(source, techniqueName, platform);

			this.domList.Add(new ShaderRegisters(source, techniqueName, platform, constantes));
			this.domList.Add(constantes);
			this.domList.Add(new ShaderTextures(source, techniqueName, platform));

			foreach (DomBase dom in domList)
				dom.Setup(this);

			this.techniqueName = techniqueName;
			this.source = source;
			this.platform = platform;


			classDom = new CodeTypeDeclaration(techniqueName);
			classDom.IsClass = true;
			classDom.Attributes = MemberAttributes.Final | MemberAttributes.Public;
			classDom.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.Public | TypeAttributes.Class;


			//provide a useful comment to the class
			GenerateClassComment();


			if (source.GenerateInternalClass)
			{
				classDom.Attributes = MemberAttributes.Final | MemberAttributes.Assembly;
				classDom.TypeAttributes = TypeAttributes.NestedAssembly | TypeAttributes.Class | TypeAttributes.Sealed;
			}
			
			classDom.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Diagnostics.DebuggerStepThroughAttribute))));
			classDom.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute)),new CodeAttributeArgument(new CodePrimitiveExpression(GetType().Assembly.ManifestModule.Name)),new CodeAttributeArgument(new CodePrimitiveExpression(GetType().Assembly.ManifestModule.ModuleVersionId.ToString()))));

			classDom.BaseTypes.Add(new CodeTypeReference(typeof(BaseShader)));

			//add custom base types to the shader
			//these are defined in TechniqueExtraData
			AsmTechnique asmTechnique = this.source.GetAsmTechnique(this.techniqueName, this.platform);

			if (asmTechnique.TechniqueExtraData != null && asmTechnique.TechniqueExtraData.ClassBaseTypes != null)
			{
				foreach (string baseTypeName in asmTechnique.TechniqueExtraData.ClassBaseTypes)
					classDom.BaseTypes.Add(new CodeTypeReference(baseTypeName));
			}


			this.directives = directives;

			SetupMembers(techniqueName);
			foreach (DomBase dom in domList)
				dom.SetupMembers(this);

			CreateConstructor();
			CreateStaticGraphicsInitMethod();
			CreateBindMethod();

			CreateWarmShaderMethod();

			CreateChangedMethod();

			CreateVertexInputMethods();

			CodeTypeMemberCollection pcMembers = new CodeTypeMemberCollection();
			CodeTypeMemberCollection xboxMembers = new CodeTypeMemberCollection();

			foreach (DomBase dom in this.domList)
			{
				dom.AddMembers(this, delegate(CodeTypeMember s, string c) { Comment(s, c); classDom.Members.Add(s); }, Platform.Both);

				if (!source.DefinePlatform) // no need for specialization when the platform is constant
				{
					dom.AddMembers(this, delegate(CodeTypeMember s, string c) { Comment(s, c); pcMembers.Add(s); }, Platform.Windows);
					dom.AddMembers(this, delegate(CodeTypeMember s, string c) { Comment(s, c); xboxMembers.Add(s); }, Platform.Xbox);
				}
			}


			foreach (DomBase dom in this.domList)
			{
				dom.AddReadonlyMembers(this, 
					delegate(CodeTypeMember s, string c)
					{
						CodeTypeMember readonlySnip = directives.CreateReadOnlySnippet();
						Comment(readonlySnip ?? s, c);
						if (readonlySnip != null) classDom.Members.Add(readonlySnip);
						classDom.Members.Add(s); 
					}, Platform.Both);

				if (!source.DefinePlatform)
				{
					dom.AddReadonlyMembers(this,
						delegate(CodeTypeMember s, string c)
						{
							CodeTypeMember readonlySnip = directives.CreateReadOnlySnippet();
							Comment(readonlySnip ?? s, c);
							if (readonlySnip != null) pcMembers.Add(readonlySnip);
							pcMembers.Add(s);
						}, Platform.Windows);

					dom.AddReadonlyMembers(this,
						delegate(CodeTypeMember s, string c)
						{
							CodeTypeMember readonlySnip = directives.CreateReadOnlySnippet();
							Comment(readonlySnip ?? s, c);
							if (readonlySnip != null) xboxMembers.Add(readonlySnip);
							xboxMembers.Add(s);
						}, Platform.Xbox);
				}
			}

			if (pcMembers.Count > 0 || xboxMembers.Count > 0)
			{
				//add #if / else blocks

				classDom.Members.Add(directives.IfXboxStatement);

				foreach (CodeTypeMember type in xboxMembers)
					classDom.Members.Add(type);

				classDom.Members.Add(directives.ElseStatement);

				foreach (CodeTypeMember type in pcMembers)
					classDom.Members.Add(type);

				classDom.Members.Add(directives.EndifStatement);
			}

			//finally, create the attribute setters

			CreateSetAttributeMethod(typeof(float), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Vector2), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Vector3), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Vector4), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Matrix), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(bool), "SetAttributeImpl", "attribute");

			CreateSetAttributeMethod(typeof(float[]), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Vector2[]), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Vector3[]), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Vector4[]), "SetAttributeImpl", "attribute");
			CreateSetAttributeMethod(typeof(Matrix[]), "SetAttributeImpl", "attribute");

			CreateSetAttributeMethod(typeof(Xen.Graphics.TextureSamplerState), "SetSamplerStateImpl", "sampler");
			CreateSetAttributeMethod(typeof(Texture), "SetTextureImpl", "texture");
			CreateSetAttributeMethod(typeof(Texture2D), "SetTextureImpl", "texture");
			CreateSetAttributeMethod(typeof(Texture3D), "SetTextureImpl", "texture");
			CreateSetAttributeMethod(typeof(TextureCube), "SetTextureImpl", "texture");

		}
示例#30
0
	public void member(
		CodeTypeMemberCollection members
	) //throws RecognitionException, TokenStreamException
{

		returnAST = null;
		ASTPair currentAST = new ASTPair();
		AST member_AST = null;

				Hashtable attributes = new Hashtable();
				CodeTypeMember type;
				string name;


		try {      // for error handling
			{
				switch ( LA(1) )
				{
				case LBRACKET:
				{
					field_attribute_list(attributes);
					if (0 == inputState.guessing)
					{
						astFactory.addASTChild(ref currentAST, returnAST);
					}
					break;
				}
				case INT3264:
				case INT64:
				case SCOPEOP:
				case LITERAL_const:
				case LITERAL_signed:
				case LITERAL_unsigned:
				case LITERAL_octet:
				case LITERAL_any:
				case LITERAL_void:
				case LITERAL_byte:
				case LITERAL_wchar_t:
				case LITERAL_handle_t:
				case LITERAL_small:
				case LITERAL_short:
				case LITERAL_long:
				case LITERAL_int:
				case LITERAL_hyper:
				case LITERAL_char:
				case LITERAL_float:
				case LITERAL_double:
				case LITERAL_boolean:
				case LITERAL_struct:
				case LITERAL_union:
				case LITERAL_enum:
				case LITERAL_sequence:
				case LITERAL_string:
				case IDENT:
				{
					break;
				}
				default:
				{
					throw new NoViableAltException(LT(1), getFilename());
				}
				 }
			}
			type=type_spec();
			if (0 == inputState.guessing)
			{
				astFactory.addASTChild(ref currentAST, returnAST);
			}
			name=declarator_list(attributes);
			if (0 == inputState.guessing)
			{
				astFactory.addASTChild(ref currentAST, returnAST);
			}
			AST tmp248_AST = null;
			tmp248_AST = astFactory.create(LT(1));
			astFactory.addASTChild(ref currentAST, tmp248_AST);
			match(SEMI);
			if (0==inputState.guessing)
			{

							if (type != null && name != string.Empty)
							{
								if (attributes["IsArray"] != null)
								{
									List<string> arraySizes = (List<string>)attributes["IsArray"];
									if (arraySizes.Count > 1)
									{
										Console.WriteLine(string.Format("Can't handle multi dimensional arrays: {0}",
											name));
									}

									if (arraySizes.Count == 1)
									{
										// Add attribute: [MarshalAs(UnmanagedType.ByValArray, SizeConst=x)]
										int val;
										if (int.TryParse(arraySizes[0], out val))
										{
											if (type is CodeMemberField)
												((CodeMemberField)type).Type.ArrayRank = 1;
											else
												Console.WriteLine(string.Format("Unhandled type: {0}", type.GetType()));

											type.CustomAttributes.Add(new CodeAttributeDeclaration("MarshalAs",
												new CodeAttributeArgument(
													new CodeSnippetExpression("UnmanagedType.ByValArray")),
												new CodeAttributeArgument("SizeConst",
													new CodePrimitiveExpression(val))));
										}
										else
										{
											Console.WriteLine(string.Format("Can't handle array dimension spec: '{0}' for {1}",
												arraySizes[0], name));
										}
									}
									attributes.Remove("IsArray");
								}

								type.Name = name;
								members.Add(type);
							}

			}
			member_AST = currentAST.root;
		}
		catch (RecognitionException ex)
		{
			if (0 == inputState.guessing)
			{
				reportError(ex);
				recover(ex,tokenSet_40_);
			}
			else
			{
				throw ex;
			}
		}
		returnAST = member_AST;
	}