internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace) { var scopeTable = new Dictionary <TypeScope, XmlMapping>(); foreach (XmlMapping mapping in xmlMappings) { scopeTable[mapping.Scope] = mapping; } TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); string assemblyName = "Microsoft.GeneratedCode"; AssemblyBuilder assemblyBuilder = CodeGenerator.CreateAssemblyBuilder(assemblyName); // Add AssemblyVersion attribute to match parent assembly version if (types != null && types.Length > 0 && types[0] != null) { ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor( new Type[] { typeof(String) } ); string assemblyVersion = types[0].Assembly.GetName().Version.ToString(); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new Object[] { assemblyVersion })); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } ModuleBuilder moduleBuilder = CodeGenerator.CreateModuleBuilder(assemblyBuilder, assemblyName); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterILGen writerCodeGen = new XmlSerializationWriterILGen(scopes, "public", writerClass); writerCodeGen.ModuleBuilder = moduleBuilder; writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } Type writerType = writerCodeGen.GenerateEnd(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderILGen readerCodeGen = new XmlSerializationReaderILGen(scopes, "public", readerClass); readerCodeGen.ModuleBuilder = moduleBuilder; readerCodeGen.CreatedTypes.Add(writerType.Name, writerType); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary <string, string>(); for (int i = 0; i < xmlMappings.Length; i++) { if (!serializers.ContainsKey(xmlMappings[i].Key)) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return(writerType.Assembly); }
internal SoapParameters(XmlMembersMapping request, XmlMembersMapping response, string[] parameterOrder, CodeIdentifiers identifiers) { ArrayList mappingsList = new ArrayList(); ArrayList list2 = new ArrayList(); AddMappings(mappingsList, request); if (response != null) { AddMappings(list2, response); } if (parameterOrder != null) { for (int i = 0; i < parameterOrder.Length; i++) { string elementName = parameterOrder[i]; XmlMemberMapping requestMapping = FindMapping(mappingsList, elementName); SoapParameter parameter = new SoapParameter(); if (requestMapping != null) { if (RemoveByRefMapping(list2, requestMapping)) { parameter.codeFlags = CodeFlags.IsByRef; } parameter.mapping = requestMapping; mappingsList.Remove(requestMapping); this.AddParameter(parameter); } else { XmlMemberMapping mapping2 = FindMapping(list2, elementName); if (mapping2 != null) { parameter.codeFlags = CodeFlags.IsOut; parameter.mapping = mapping2; list2.Remove(mapping2); this.AddParameter(parameter); } } } } foreach (XmlMemberMapping mapping3 in mappingsList) { SoapParameter parameter2 = new SoapParameter(); if (RemoveByRefMapping(list2, mapping3)) { parameter2.codeFlags = CodeFlags.IsByRef; } parameter2.mapping = mapping3; this.AddParameter(parameter2); } if (list2.Count > 0) { if (!((XmlMemberMapping)list2[0]).CheckSpecified) { this.ret = (XmlMemberMapping)list2[0]; list2.RemoveAt(0); } foreach (XmlMemberMapping mapping4 in list2) { SoapParameter parameter3 = new SoapParameter { mapping = mapping4, codeFlags = CodeFlags.IsOut }; this.AddParameter(parameter3); } } foreach (SoapParameter parameter4 in this.parameters) { parameter4.name = identifiers.MakeUnique(CodeIdentifier.MakeValid(parameter4.mapping.MemberName)); } }
CodeMemberMethod GenerateMethod(CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember) { CodeIdentifiers pids = new CodeIdentifiers(); CodeMemberMethod method = new CodeMemberMethod(); CodeMemberMethod methodBegin = new CodeMemberMethod(); CodeMemberMethod methodEnd = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public; methodBegin.Attributes = MemberAttributes.Public; methodEnd.Attributes = MemberAttributes.Public; // Find unique names for temporary variables for (int n = 0; n < inputMembers.Count; n++) { pids.AddUnique(inputMembers[n].MemberName, inputMembers[n]); } string varAsyncResult = pids.AddUnique("asyncResult", "asyncResult"); string varCallback = pids.AddUnique("callback", "callback"); string varAsyncState = pids.AddUnique("asyncState", "asyncState"); string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name), method); method.Name = Operation.Name; methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name), method); methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.Name), method); method.ReturnType = new CodeTypeReference(typeof(void)); methodEnd.ReturnType = new CodeTypeReference(typeof(void)); methodEnd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), varAsyncResult)); CodeExpression[] paramArray = new CodeExpression [inputMembers.Count]; for (int n = 0; n < inputMembers.Count; n++) { string ptype = GetSimpleType(inputMembers[n]); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(ptype, inputMembers[n].MemberName); param.Direction = FieldDirection.In; method.Parameters.Add(param); methodBegin.Parameters.Add(param); paramArray [n] = new CodeVariableReferenceExpression(param.Name); } bool isVoid = true; if (outputMember != null) { method.ReturnType = new CodeTypeReference(outputMember.TypeFullName); methodEnd.ReturnType = new CodeTypeReference(outputMember.TypeFullName); xmlExporter.AddMappingMetadata(method.ReturnTypeCustomAttributes, outputMember, ""); isVoid = false; } methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), varCallback)); methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), varAsyncState)); methodBegin.ReturnType = new CodeTypeReference(typeof(IAsyncResult)); // Array of input parameters CodeArrayCreateExpression methodParams; if (paramArray.Length > 0) { methodParams = new CodeArrayCreateExpression(typeof(object), paramArray); } else { methodParams = new CodeArrayCreateExpression(typeof(object), 0); } // Generate method url CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodeExpression thisURlExp = new CodeFieldReferenceExpression(ethis, "Url"); CodePrimitiveExpression metUrl = new CodePrimitiveExpression(httpOper.Location); CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression(thisURlExp, CodeBinaryOperatorType.Add, metUrl); // Invoke call CodePrimitiveExpression varMsgName = new CodePrimitiveExpression(messageName); CodeMethodInvokeExpression inv; inv = new CodeMethodInvokeExpression(ethis, "Invoke", varMsgName, expMethodLocation, methodParams); if (!isVoid) { method.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, inv))); } else { method.Statements.Add(inv); } // Begin Invoke Call CodeExpression expCallb = new CodeVariableReferenceExpression(varCallback); CodeExpression expAsyncs = new CodeVariableReferenceExpression(varAsyncState); inv = new CodeMethodInvokeExpression(ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs); methodBegin.Statements.Add(new CodeMethodReturnStatement(inv)); // End Invoke call CodeExpression varAsyncr = new CodeVariableReferenceExpression(varAsyncResult); inv = new CodeMethodInvokeExpression(ethis, "EndInvoke", varAsyncr); if (!isVoid) { methodEnd.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(methodEnd.ReturnType, inv))); } else { methodEnd.Statements.Add(inv); } // Attributes CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.Protocols.HttpMethodAttribute"); att.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(GetOutMimeFormatter()))); att.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(GetInMimeFormatter()))); AddCustomAttribute(method, att, true); CodeTypeDeclaration.Members.Add(method); CodeTypeDeclaration.Members.Add(methodBegin); CodeTypeDeclaration.Members.Add(methodEnd); return(method); }
internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream) { var compiler = new Compiler(); try { var scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) { scopeTable[mapping.Scope] = mapping; } var scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); assemblies.Clear(); var importedTypes = new Hashtable(); foreach (TypeScope scope in scopes) { foreach (Type t in scope.Types) { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; string name = a.FullName; if (assemblies[name] != null) { continue; } if (!a.GlobalAssemblyCache) { assemblies[name] = a; } } } for (int i = 0; i < types.Length; i++) { compiler.AddImport(types[i], importedTypes); } compiler.AddImport(typeof(object).Assembly); compiler.AddImport(typeof(System.Xml.Serialization.XmlSerializer).Assembly); var writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); if (assembly != null && types.Length > 0) { for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) { continue; } if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName)); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } var classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {"); writer.Indent++; writer.WriteLine(); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } writerCodeGen.GenerateEnd(); writer.WriteLine(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { if (serializers[xmlMappings[i].Key] == null) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); string codecontent = compiler.Source.ToString(); Byte[] info = new UTF8Encoding(true).GetBytes(codecontent); stream.Write(info, 0, info.Length); stream.Flush(); return(true); } finally { compiler.Close(); } }
// UNDONE Nullable private void SetArrayMappingType(ArrayMapping mapping) { bool useDefaultNs = false; string itemTypeName; string itemTypeNamespace; TypeMapping itemTypeMapping; if (mapping.Elements.Length == 1) { itemTypeMapping = mapping.Elements[0].Mapping; } else { itemTypeMapping = null; } if (itemTypeMapping is EnumMapping) { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } else if (itemTypeMapping is PrimitiveMapping) { itemTypeNamespace = itemTypeMapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; itemTypeName = itemTypeMapping.TypeDesc.DataType.Name; useDefaultNs = true; } else if (itemTypeMapping is StructMapping) { if (itemTypeMapping.TypeDesc.IsRoot) { itemTypeNamespace = XmlSchema.Namespace; itemTypeName = Soap.UrType; useDefaultNs = true; } else { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } } else if (itemTypeMapping is ArrayMapping) { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } else { throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc.FullName)); } itemTypeName = CodeIdentifier.MakePascal(itemTypeName); string uniqueName = "ArrayOf" + itemTypeName; string ns = useDefaultNs ? _defaultNs : itemTypeNamespace; int i = 1; TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) { ArrayMapping arrayMapping = (ArrayMapping)existingMapping; if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements)) { break; } } // need to re-name the mapping uniqueName = itemTypeName + i.ToString(CultureInfo.InvariantCulture); existingMapping = (TypeMapping)_types[uniqueName, ns]; i++; } mapping.Namespace = ns; mapping.TypeName = uniqueName; }
private void InternalLoad(Type elementType, bool asAddress = false) { Match match = s_regex.Match(Arg); if (match.Success) { object varA = ILG.GetVariable(match.Groups["a"].Value); Type varType = ILG.GetVariableType(varA); object varIA = ILG.GetVariable(match.Groups["ia"].Value); if (varType.IsArray) { ILG.Load(varA); ILG.Load(varIA); Type eType = varType.GetElementType(); if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); ConvertNullableValue(eType, elementType); } else { if (eType.IsValueType) { ILG.Ldelema(eType); if (!asAddress) { ILG.Ldobj(eType); } } else { ILG.Ldelem(eType); } if (elementType != null) { ILG.ConvertValue(eType, elementType); } } } else { ILG.Load(varA); ILG.Load(varIA); MethodInfo get_Item = varType.GetMethod( "get_Item", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Int32) } ); if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { get_Item = s_iListGetItemMethod.Value; } Debug.Assert(get_Item != null); ILG.Call(get_Item); Type eType = get_Item.ReturnType; if (CodeGenerator.IsNullableGenericType(eType)) { LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); ConvertNullableValue(eType, elementType); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom"); } else { Convert(eType, elementType, asAddress); } } } else if (Source == "null") { ILG.Load(null); } else { object var; Type varType; if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null) { var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg); varType = ILG.GetVariableType(var); if (varType.IsValueType) { ILG.LoadAddress(var); } else { ILG.Load(var); } } else { var = ILG.GetVariable(Arg); varType = ILG.GetVariableType(var); if (CodeGenerator.IsNullableGenericType(varType) && varType.GetGenericArguments()[0] == elementType) { ILG.LoadAddress(var); ConvertNullableValue(varType, elementType); } else { if (asAddress) { ILG.LoadAddress(var); } else { ILG.Load(var); } } } if (MemberInfo != null) { Type memberType = (MemberInfo is FieldInfo) ? ((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType; if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); ConvertNullableValue(memberType, elementType); } else { ILG.LoadMember(MemberInfo); Convert(memberType, elementType, asAddress); } } else { match = s_regex2.Match(Source); if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type)); if (asAddress) { ILG.ConvertAddress(varType, Type); } else { ILG.ConvertValue(varType, Type); } varType = Type; } Convert(varType, elementType, asAddress); } } }
protected override void Visit(CodeIdentifier identifier) { }
public CodeVariable(CodeIdentifier name, CodeTypeToken type, bool rvalueTyped) : base(name, type) { RValueTyped = rvalueTyped; }
/// <summary> /// Add named parameter value. /// </summary> /// <param name="property">Attribute property name.</param> /// <param name="value">Parameter value.</param> /// <returns>Builder instance.</returns> public AttributeBuilder Parameter(CodeIdentifier property, ICodeExpression value) { Attribute.AddNamedParameter(property, value); return(this); }
void ImportPortBinding(bool multipleBindings) { if (port != null) { if (multipleBindings) { className = binding.Name; } else { className = service.Name; } } else { className = binding.Name; } className = classNames.AddUnique(CodeIdentifier.MakeValid(className), port); className = className.Replace("_x0020_", ""); // MS.NET seems to do this try { portType = ServiceDescriptions.GetPortType(binding.Type); if (portType == null) { throw new Exception("Port type not found: " + binding.Type); } CodeTypeDeclaration codeClass = BeginClass(); codeTypeDeclaration = codeClass; AddCodeType(codeClass, port != null ? port.Documentation : null); codeClass.Attributes = MemberAttributes.Public; if (service != null && service.Documentation != null && service.Documentation != "") { AddComments(codeClass, service.Documentation); } if (Style == ServiceDescriptionImportStyle.Client) { CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThroughAttribute"); AddCustomAttribute(codeClass, att, true); att = new CodeAttributeDeclaration("System.ComponentModel.DesignerCategoryAttribute"); att.Arguments.Add(GetArg("code")); AddCustomAttribute(codeClass, att, true); } else { codeClass.TypeAttributes = System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Public; } if (binding.Operations.Count == 0) { warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated; return; } foreach (OperationBinding oper in binding.Operations) { operationBinding = oper; operation = FindPortOperation(); if (operation == null) { throw new Exception("Operation " + operationBinding.Name + " not found in portType " + PortType.Name); } inputMessage = null; outputMessage = null; foreach (OperationMessage omsg in operation.Messages) { Message msg = ServiceDescriptions.GetMessage(omsg.Message); if (msg == null) { throw new Exception("Message not found: " + omsg.Message); } if (omsg is OperationInput) { inputMessage = msg; } else { outputMessage = msg; } } CodeMemberMethod method = GenerateMethod(); if (method != null) { methodName = method.Name; if (operation.Documentation != null && operation.Documentation != "") { AddComments(method, operation.Documentation); } #if NET_2_0 if (Style == ServiceDescriptionImportStyle.Client) { AddAsyncMembers(method.Name, method); } #endif } } #if NET_2_0 if (Style == ServiceDescriptionImportStyle.Client) { AddAsyncTypes(); } #endif EndClass(); } catch (InvalidOperationException ex) { warnings |= ServiceDescriptionImportWarnings.NoCodeGenerated; UnsupportedBindingWarning(ex.Message); } }
void ImportHeader(CodeMemberMethod method, SoapHeaderBinding hb, SoapHeaderDirection direction) { Message msg = ServiceDescriptions.GetMessage(hb.Message); if (msg == null) { throw new InvalidOperationException("Message " + hb.Message + " not found"); } MessagePart part = msg.Parts [hb.Part]; if (part == null) { throw new InvalidOperationException("Message part " + hb.Part + " not found in message " + hb.Message); } XmlTypeMapping map; string hname; if (hb.Use == SoapBindingUse.Literal) { map = xmlImporter.ImportDerivedTypeMapping(part.Element, typeof(SoapHeader)); hname = part.Element.Name; xmlExporter.ExportTypeMapping(map); } else { map = soapImporter.ImportDerivedTypeMapping(part.Type, typeof(SoapHeader), true); hname = part.Type.Name; soapExporter.ExportTypeMapping(map); } string varName = headerVariables [map] as string; if (varName == null) { if (hname == map.TypeName) { varName = memberIds.AddUnique(CodeIdentifier.MakeValid(hname + "Value"), hb); } else { varName = memberIds.AddUnique(CodeIdentifier.MakeValid(hname), hb); } #if NET_2_0 string propName = varName; varName = varName + "Field"; #endif headerVariables.Add(map, varName); CodeMemberField codeField = new CodeMemberField(map.TypeFullName, varName); CodeTypeDeclaration.Members.Add(codeField); #if NET_2_0 codeField.Attributes = MemberAttributes.Private; CodeMemberProperty codeProperty = new CodeMemberProperty(); codeProperty.Name = propName; codeProperty.Type = new CodeTypeReference(map.TypeFullName); codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeProperty.HasGet = codeProperty.HasSet = true; CodeExpression ce = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), varName); codeProperty.SetStatements.Add(new CodeAssignStatement(ce, new CodePropertySetValueReferenceExpression())); codeProperty.GetStatements.Add(new CodeMethodReturnStatement(ce)); CodeTypeDeclaration.Members.Add(codeProperty); #else codeField.Attributes = MemberAttributes.Public; #endif } CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapHeaderAttribute"); att.Arguments.Add(GetArg(varName)); #if ONLY_1_0 att.Arguments.Add(GetArg("Required", false)); #endif if (direction != SoapHeaderDirection.In) { att.Arguments.Add(GetEnumArg("Direction", "System.Web.Services.Protocols.SoapHeaderDirection", direction.ToString())); } AddCustomAttribute(method, att, true); }
CodeMemberMethod GenerateMethod(CodeIdentifiers memberIds, SoapOperationBinding soapOper, SoapBodyBinding bodyBinding, XmlMembersMapping inputMembers, XmlMembersMapping outputMembers) { CodeIdentifiers pids = new CodeIdentifiers(); CodeMemberMethod method = new CodeMemberMethod(); CodeMemberMethod methodBegin = new CodeMemberMethod(); CodeMemberMethod methodEnd = new CodeMemberMethod(); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; methodBegin.Attributes = MemberAttributes.Public | MemberAttributes.Final; methodEnd.Attributes = MemberAttributes.Public | MemberAttributes.Final; SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style; // Find unique names for temporary variables for (int n = 0; n < inputMembers.Count; n++) { pids.AddUnique(inputMembers[n].MemberName, inputMembers[n]); } if (outputMembers != null) { for (int n = 0; n < outputMembers.Count; n++) { pids.AddUnique(outputMembers[n].MemberName, outputMembers[n]); } } string varAsyncResult = pids.AddUnique("asyncResult", "asyncResult"); string varResults = pids.AddUnique("results", "results"); string varCallback = pids.AddUnique("callback", "callback"); string varAsyncState = pids.AddUnique("asyncState", "asyncState"); string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name), method); method.Name = CodeIdentifier.MakeValid(Operation.Name); if (method.Name == ClassName) { method.Name += "1"; } methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + method.Name), method); methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + method.Name), method); method.ReturnType = new CodeTypeReference(typeof(void)); methodEnd.ReturnType = new CodeTypeReference(typeof(void)); methodEnd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), varAsyncResult)); CodeExpression[] paramArray = new CodeExpression [inputMembers.Count]; CodeParameterDeclarationExpression[] outParams = new CodeParameterDeclarationExpression [outputMembers != null ? outputMembers.Count : 0]; for (int n = 0; n < inputMembers.Count; n++) { CodeParameterDeclarationExpression param = GenerateParameter(inputMembers[n], FieldDirection.In); method.Parameters.Add(param); GenerateMemberAttributes(inputMembers, inputMembers[n], bodyBinding.Use, param); methodBegin.Parameters.Add(GenerateParameter(inputMembers[n], FieldDirection.In)); paramArray [n] = new CodeVariableReferenceExpression(param.Name); } if (outputMembers != null) { bool hasReturn = false; for (int n = 0; n < outputMembers.Count; n++) { CodeParameterDeclarationExpression cpd = GenerateParameter(outputMembers[n], FieldDirection.Out); outParams [n] = cpd; bool found = false; foreach (CodeParameterDeclarationExpression ip in method.Parameters) { if (ip.Name == cpd.Name && ip.Type.BaseType == cpd.Type.BaseType) { ip.Direction = FieldDirection.Ref; methodEnd.Parameters.Add(GenerateParameter(outputMembers[n], FieldDirection.Out)); found = true; break; } } if (found) { continue; } if (!hasReturn) { hasReturn = true; method.ReturnType = cpd.Type; methodEnd.ReturnType = cpd.Type; GenerateReturnAttributes(outputMembers, outputMembers[n], bodyBinding.Use, method); outParams [n] = null; continue; } method.Parameters.Add(cpd); GenerateMemberAttributes(outputMembers, outputMembers[n], bodyBinding.Use, cpd); methodEnd.Parameters.Add(GenerateParameter(outputMembers[n], FieldDirection.Out)); } } methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), varCallback)); methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), varAsyncState)); methodBegin.ReturnType = new CodeTypeReference(typeof(IAsyncResult)); // Array of input parameters CodeArrayCreateExpression methodParams; if (paramArray.Length > 0) { methodParams = new CodeArrayCreateExpression(typeof(object), paramArray); } else { methodParams = new CodeArrayCreateExpression(typeof(object), 0); } // Assignment of output parameters CodeStatementCollection outAssign = new CodeStatementCollection(); CodeVariableReferenceExpression arrVar = new CodeVariableReferenceExpression(varResults); for (int n = 0; n < outParams.Length; n++) { CodeExpression index = new CodePrimitiveExpression(n); if (outParams[n] == null) { CodeExpression res = new CodeCastExpression(method.ReturnType, new CodeArrayIndexerExpression(arrVar, index)); outAssign.Add(new CodeMethodReturnStatement(res)); } else { CodeExpression res = new CodeCastExpression(outParams[n].Type, new CodeArrayIndexerExpression(arrVar, index)); CodeExpression var = new CodeVariableReferenceExpression(outParams[n].Name); outAssign.Insert(0, new CodeAssignStatement(var, res)); } } if (Style == ServiceDescriptionImportStyle.Client) { // Invoke call CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodePrimitiveExpression varMsgName = new CodePrimitiveExpression(messageName); CodeMethodInvokeExpression inv; CodeVariableDeclarationStatement dec; inv = new CodeMethodInvokeExpression(ethis, "Invoke", varMsgName, methodParams); if (outputMembers != null && outputMembers.Count > 0) { dec = new CodeVariableDeclarationStatement(typeof(object[]), varResults, inv); method.Statements.Add(dec); method.Statements.AddRange(outAssign); } else { method.Statements.Add(inv); } // Begin Invoke Call CodeExpression expCallb = new CodeVariableReferenceExpression(varCallback); CodeExpression expAsyncs = new CodeVariableReferenceExpression(varAsyncState); inv = new CodeMethodInvokeExpression(ethis, "BeginInvoke", varMsgName, methodParams, expCallb, expAsyncs); methodBegin.Statements.Add(new CodeMethodReturnStatement(inv)); // End Invoke call CodeExpression varAsyncr = new CodeVariableReferenceExpression(varAsyncResult); inv = new CodeMethodInvokeExpression(ethis, "EndInvoke", varAsyncr); if (outputMembers != null && outputMembers.Count > 0) { dec = new CodeVariableDeclarationStatement(typeof(object[]), varResults, inv); methodEnd.Statements.Add(dec); methodEnd.Statements.AddRange(outAssign); } else { methodEnd.Statements.Add(inv); } } else { method.Attributes = MemberAttributes.Public | MemberAttributes.Abstract; } // Attributes ImportHeaders(method); CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.WebMethodAttribute"); if (messageName != method.Name) { att.Arguments.Add(GetArg("MessageName", messageName)); } AddCustomAttribute(method, att, (Style == ServiceDescriptionImportStyle.Server)); if (style == SoapBindingStyle.Rpc) { att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapRpcMethodAttribute"); att.Arguments.Add(GetArg(soapOper.SoapAction)); if (inputMembers.ElementName != method.Name) { att.Arguments.Add(GetArg("RequestElementName", inputMembers.ElementName)); } if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) { att.Arguments.Add(GetArg("ResponseElementName", outputMembers.ElementName)); } att.Arguments.Add(GetArg("RequestNamespace", inputMembers.Namespace)); if (outputMembers != null) { att.Arguments.Add(GetArg("ResponseNamespace", outputMembers.Namespace)); } if (outputMembers == null) { att.Arguments.Add(GetArg("OneWay", true)); } } else { if (outputMembers != null && (inputMembers.ElementName == "" && outputMembers.ElementName != "" || inputMembers.ElementName != "" && outputMembers.ElementName == "")) { throw new InvalidOperationException("Parameter style is not the same for the input message and output message"); } att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapDocumentMethodAttribute"); att.Arguments.Add(GetArg(soapOper.SoapAction)); if (inputMembers.ElementName != "") { if (inputMembers.ElementName != method.Name) { att.Arguments.Add(GetArg("RequestElementName", inputMembers.ElementName)); } if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) { att.Arguments.Add(GetArg("ResponseElementName", outputMembers.ElementName)); } att.Arguments.Add(GetArg("RequestNamespace", inputMembers.Namespace)); if (outputMembers != null) { att.Arguments.Add(GetArg("ResponseNamespace", outputMembers.Namespace)); } att.Arguments.Add(GetEnumArg("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Wrapped")); } else { att.Arguments.Add(GetEnumArg("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Bare")); } if (outputMembers == null) { att.Arguments.Add(GetArg("OneWay", true)); } att.Arguments.Add(GetEnumArg("Use", "System.Web.Services.Description.SoapBindingUse", bodyBinding.Use.ToString())); } AddCustomAttribute(method, att, true); CodeTypeDeclaration.Members.Add(method); if (Style == ServiceDescriptionImportStyle.Client) { CodeTypeDeclaration.Members.Add(methodBegin); CodeTypeDeclaration.Members.Add(methodEnd); } return(method); }
/// <summary> /// Add parameter section to xml-doc. /// </summary> /// <param name="parameter">Parameter name.</param> /// <param name="text">Help text.</param> /// <returns>Builder instance.</returns> public XmlDocBuilder Parameter(CodeIdentifier parameter, string text) { _comment.AddParameter(parameter, text); return(this); }
private MimeParameter ImportUrlParameter(MessagePart part) { return(new MimeParameter { Name = CodeIdentifier.MakeValid(XmlConvert.DecodeName(part.Name)), TypeName = this.IsRepeatingParameter(part) ? typeof(string[]).FullName : typeof(string).FullName }); }
private void GenerateClassForBinding() { try { if (((this.bindingCount == 1) && (this.service != null)) && (this.Style != ServiceDescriptionImportStyle.ServerInterface)) { this.className = XmlConvert.DecodeName(this.service.Name); } else { this.className = this.binding.Name; if (this.Style == ServiceDescriptionImportStyle.ServerInterface) { this.className = "I" + CodeIdentifier.MakePascal(this.className); } } this.className = XmlConvert.DecodeName(this.className); this.className = this.ClassNames.AddUnique(CodeIdentifier.MakeValid(this.className), null); this.codeClass = this.BeginClass(); int num = 0; for (int i = 0; i < this.portType.Operations.Count; i++) { CodeMemberMethod method; this.MoveToOperation(this.portType.Operations[i]); if (!this.IsOperationFlowSupported(this.operation.Messages.Flow)) { switch (this.operation.Messages.Flow) { case OperationFlow.OneWay: { this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("OneWayIsNotSupported0")); continue; } case OperationFlow.Notification: { this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("NotificationIsNotSupported0")); continue; } case OperationFlow.RequestResponse: { this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("RequestResponseIsNotSupported0")); continue; } case OperationFlow.SolicitResponse: { this.UnsupportedOperationWarning(System.Web.Services.Res.GetString("SolicitResponseIsNotSupported0")); continue; } } } try { method = this.GenerateMethod(); } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } throw new InvalidOperationException(System.Web.Services.Res.GetString("UnableToImportOperation1", new object[] { this.operation.Name }), exception); } if (method != null) { this.AddExtensionWarningComments(this.codeClass.Comments, this.operationBinding.Extensions); if (this.operationBinding.Input != null) { this.AddExtensionWarningComments(this.codeClass.Comments, this.operationBinding.Input.Extensions); } if (this.operationBinding.Output != null) { this.AddExtensionWarningComments(this.codeClass.Comments, this.operationBinding.Output.Extensions); } num++; } } if ((((((this.ServiceImporter.CodeGenerationOptions & CodeGenerationOptions.GenerateNewAsync) != CodeGenerationOptions.None) && this.ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareEvents)) && this.ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareDelegates)) && (num > 0)) && (this.Style == ServiceDescriptionImportStyle.Client)) { CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection(); string identifier = "CancelAsync"; string methodName = this.MethodNames.AddUnique(identifier, identifier); CodeMemberMethod method2 = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, methodName, new CodeFlags[1], new string[] { typeof(object).FullName }, new string[] { "userState" }, typeof(void).FullName, metadata, CodeFlags.IsPublic | ((identifier != methodName) ? ((CodeFlags)0) : CodeFlags.IsNew)); method2.Comments.Add(new CodeCommentStatement(System.Web.Services.Res.GetString("CodeRemarks"), true)); CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), identifier, new CodeExpression[0]); expression.Parameters.Add(new CodeArgumentReferenceExpression("userState")); method2.Statements.Add(expression); } this.EndClass(); if (this.portType.Operations.Count == 0) { this.NoMethodsGeneratedWarning(); } this.AddExtensionWarningComments(this.codeClass.Comments, this.binding.Extensions); if (this.port != null) { this.AddExtensionWarningComments(this.codeClass.Comments, this.port.Extensions); } this.codeNamespace.Types.Add(this.codeClass); } catch (Exception exception2) { if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException)) { throw; } throw new InvalidOperationException(System.Web.Services.Res.GetString("UnableToImportBindingFromNamespace2", new object[] { this.binding.Name, this.binding.ServiceDescription.TargetNamespace }), exception2); } }
private static string MakeFieldName(string name) { return(CodeIdentifier.MakeCamel(name) + "Field"); }
public CodeVariable(CodeIdentifier name, IType type, bool rvalueTyped) : this(name, new CodeTypeToken(type), rvalueTyped) { }