public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers, CodeGenerationOptions options) { }
void ReflectBinding(ReflectedBinding reflectedBinding) { string bindingName = XmlConvert.EncodeLocalName(reflectedBinding.bindingAttr.Name); string bindingNamespace = reflectedBinding.bindingAttr.Namespace; if (bindingName.Length == 0) { bindingName = Service.Name + ProtocolName; } if (bindingNamespace.Length == 0) { bindingNamespace = ServiceDescription.TargetNamespace; } WsiProfiles claims = WsiProfiles.None; if (reflectedBinding.bindingAttr.Location.Length > 0) { // If a URL is specified for the WSDL, file, then we just import the // binding from there instead of generating it in this WSDL file. portType = null; binding = null; } else { bindingServiceDescription = GetServiceDescription(bindingNamespace); CodeIdentifiers bindingNames = new CodeIdentifiers(); foreach (Binding b in bindingServiceDescription.Bindings) { bindingNames.AddReserved(b.Name); } bindingName = bindingNames.AddUnique(bindingName, binding); portType = new PortType(); binding = new Binding(); portType.Name = bindingName; binding.Name = bindingName; binding.Type = new XmlQualifiedName(portType.Name, bindingNamespace); claims = reflectedBinding.bindingAttr.ConformsTo & this.ConformsTo; if (reflectedBinding.bindingAttr.EmitConformanceClaims && claims != WsiProfiles.None) { ServiceDescription.AddConformanceClaims(binding.GetDocumentationElement(), claims); } bindingServiceDescription.Bindings.Add(binding); bindingServiceDescription.PortTypes.Add(portType); } if (portNames == null) { portNames = new CodeIdentifiers(); foreach (Port p in Service.Ports) { portNames.AddReserved(p.Name); } } port = new Port(); port.Binding = new XmlQualifiedName(bindingName, bindingNamespace); port.Name = portNames.AddUnique(bindingName, port); Service.Ports.Add(port); BeginClass(); if (reflectedBinding.methodList != null && reflectedBinding.methodList.Count > 0) { foreach (LogicalMethodInfo method in reflectedBinding.methodList) { MoveToMethod(method); operation = new Operation(); operation.Name = XmlConvert.EncodeLocalName(method.Name); if (methodAttr.Description != null && methodAttr.Description.Length > 0) { operation.Documentation = methodAttr.Description; } operationBinding = new OperationBinding(); operationBinding.Name = operation.Name; inputMessage = null; outputMessage = null; headerMessages = null; if (ReflectMethod()) { if (inputMessage != null) { bindingServiceDescription.Messages.Add(inputMessage); } if (outputMessage != null) { bindingServiceDescription.Messages.Add(outputMessage); } if (headerMessages != null) { foreach (Message headerMessage in headerMessages) { bindingServiceDescription.Messages.Add(headerMessage); } } binding.Operations.Add(operationBinding); portType.Operations.Add(operation); } } } if (binding != null && claims == WsiProfiles.BasicProfile1_1 && ProtocolName == "Soap") { BasicProfileViolationCollection warnings = new BasicProfileViolationCollection(); WebServicesInteroperability.AnalyzeBinding(binding, bindingServiceDescription, ServiceDescriptions, warnings); if (warnings.Count > 0) { throw new InvalidOperationException(Res.GetString(Res.WebWsiViolation, ServiceType.FullName, warnings.ToString())); } } EndClass(); }
internal static CodeTypeDeclaration CreateArgsClass(string name, string[] paramTypes, string[] paramNames, bool isPartial) { CodeTypeDeclaration codeClass = new CodeTypeDeclaration(name); codeClass.CustomAttributes.Add(GeneratedCodeAttribute); // Add [DebuggerStepThrough] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DebuggerStepThroughAttribute).FullName)); // Add [DesignerCategory("code")] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DesignerCategoryAttribute).FullName, new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression("code")) })); codeClass.IsPartial = isPartial; codeClass.BaseTypes.Add(new CodeTypeReference(typeof(AsyncCompletedEventArgs))); CodeIdentifiers identifiers = new CodeIdentifiers(); identifiers.AddUnique("Error", "Error"); identifiers.AddUnique("Cancelled", "Cancelled"); identifiers.AddUnique("UserState", "UserState"); for (int i = 0; i < paramNames.Length; i++) { if (paramNames[i] != null) { identifiers.AddUnique(paramNames[i], paramNames[i]); } } string results = identifiers.AddUnique("results", "results"); CodeMemberField data = new CodeMemberField(typeof(object[]), results); codeClass.Members.Add(data); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = (ctor.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Assembly; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(object[]), results); ctor.Parameters.Add(param); ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Exception), "exception")); ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled")); ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); ctor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("exception")); ctor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("cancelled")); ctor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("userState")); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), data.Name), new CodeArgumentReferenceExpression(results))); codeClass.Members.Add(ctor); int index = 0; for (int i = 0; i < paramNames.Length; i++) { if (paramNames[i] != null) { codeClass.Members.Add(CreatePropertyDeclaration(data, paramNames[i], paramTypes[i], index++)); } } codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true)); return(codeClass); }
private void GenerateCode(string typeName, MimeTextMatchCollection matches, CodeGenerationOptions options) { CodeIdentifiers identifiers = new CodeIdentifiers(); CodeTypeDeclaration codeClass = WebCodeGenerator.AddClass(base.ImportContext.CodeNamespace, typeName, string.Empty, new string[0], null, CodeFlags.IsPublic, base.ImportContext.ServiceImporter.CodeGenerator.Supports(GeneratorSupport.PartialTypes)); string[] strArray = new string[matches.Count]; for (int i = 0; i < matches.Count; i++) { string fullName; MimeTextMatch match = matches[i]; string memberName = identifiers.AddUnique(CodeIdentifier.MakeValid((match.Name.Length == 0) ? (this.methodName + "Match") : match.Name), match); CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection(); if (match.Pattern.Length == 0) { throw new ArgumentException(Res.GetString("WebTextMatchMissingPattern")); } CodeExpression expression = new CodePrimitiveExpression(match.Pattern); int index = 0; if (match.Group != 1) { index++; } if (match.Capture != 0) { index++; } if (match.IgnoreCase) { index++; } if ((match.Repeats != 1) && (match.Repeats != 0x7fffffff)) { index++; } CodeExpression[] propValues = new CodeExpression[index]; string[] propNames = new string[propValues.Length]; index = 0; if (match.Group != 1) { propValues[index] = new CodePrimitiveExpression(match.Group); propNames[index] = "Group"; index++; } if (match.Capture != 0) { propValues[index] = new CodePrimitiveExpression(match.Capture); propNames[index] = "Capture"; index++; } if (match.IgnoreCase) { propValues[index] = new CodePrimitiveExpression(match.IgnoreCase); propNames[index] = "IgnoreCase"; index++; } if ((match.Repeats != 1) && (match.Repeats != 0x7fffffff)) { propValues[index] = new CodePrimitiveExpression(match.Repeats); propNames[index] = "MaxRepeats"; index++; } WebCodeGenerator.AddCustomAttribute(metadata, typeof(MatchAttribute), new CodeExpression[] { expression }, propNames, propValues); if (match.Matches.Count > 0) { fullName = base.ImportContext.ClassNames.AddUnique(CodeIdentifier.MakeValid((match.Type.Length == 0) ? memberName : match.Type), match); strArray[i] = fullName; } else { fullName = typeof(string).FullName; } if (match.Repeats != 1) { fullName = fullName + "[]"; } CodeTypeMember member = WebCodeGenerator.AddMember(codeClass, fullName, memberName, null, metadata, CodeFlags.IsPublic, options); if ((match.Matches.Count == 0) && (match.Type.Length > 0)) { HttpProtocolImporter importContext = base.ImportContext; importContext.Warnings |= ServiceDescriptionImportWarnings.OptionalExtensionsIgnored; ProtocolImporter.AddWarningComment(member.Comments, Res.GetString("WebTextMatchIgnoredTypeWarning")); } } for (int j = 0; j < strArray.Length; j++) { string str3 = strArray[j]; if (str3 != null) { this.GenerateCode(str3, matches[j].Matches, options); } } }
void GenerateCode(string typeName, MimeTextMatchCollection matches) { CodeIdentifiers members = new CodeIdentifiers(); CodeTypeDeclaration codeClass = WebCodeGenerator.AddClass(ImportContext.CodeNamespace, typeName, string.Empty, new string[0], null, CodeFlags.IsPublic); string[] fieldTypeNames = new string[matches.Count]; for (int i = 0; i < matches.Count; i++) { MimeTextMatch match = matches[i]; string name = members.AddUnique(CodeIdentifier.MakeValid(match.Name.Length == 0 ? methodName + "Match" : match.Name), match); CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection(); if (match.Pattern.Length == 0) { throw new ArgumentException(Res.GetString(Res.WebTextMatchMissingPattern)); } CodeExpression pattern = new CodePrimitiveExpression(match.Pattern); int numPropValues = 0; if (match.Group != 1) { numPropValues++; } if (match.Capture != 0) { numPropValues++; } if (match.IgnoreCase) { numPropValues++; } if (match.Repeats != 1 && match.Repeats != int.MaxValue) { numPropValues++; } CodeExpression[] propertyValues = new CodeExpression[numPropValues]; string[] propertyNames = new string[propertyValues.Length]; numPropValues = 0; if (match.Group != 1) { propertyValues[numPropValues] = new CodePrimitiveExpression(match.Group); propertyNames[numPropValues] = "Group"; numPropValues++; } if (match.Capture != 0) { propertyValues[numPropValues] = new CodePrimitiveExpression(match.Capture); propertyNames[numPropValues] = "Capture"; numPropValues++; } if (match.IgnoreCase) { propertyValues[numPropValues] = new CodePrimitiveExpression(match.IgnoreCase); propertyNames[numPropValues] = "IgnoreCase"; numPropValues++; } if (match.Repeats != 1 && match.Repeats != int.MaxValue) { propertyValues[numPropValues] = new CodePrimitiveExpression(match.Repeats); propertyNames[numPropValues] = "MaxRepeats"; numPropValues++; } WebCodeGenerator.AddCustomAttribute(metadata, typeof(MatchAttribute), new CodeExpression[] { pattern }, propertyNames, propertyValues); string fieldTypeName; if (match.Matches.Count > 0) { fieldTypeName = ImportContext.ClassNames.AddUnique(CodeIdentifier.MakeValid(match.Type.Length == 0 ? name : match.Type), match); fieldTypeNames[i] = fieldTypeName; } else { fieldTypeName = typeof(string).FullName; } if (match.Repeats != 1) { fieldTypeName += "[]"; } CodeMemberField field = WebCodeGenerator.AddField(codeClass, fieldTypeName, name, null, metadata, CodeFlags.IsPublic); if (match.Matches.Count == 0 && match.Type.Length > 0) { ImportContext.Warnings |= ServiceDescriptionImportWarnings.OptionalExtensionsIgnored; ProtocolImporter.AddWarningComment(field.Comments, Res.GetString(Res.WebTextMatchIgnoredTypeWarning)); } } for (int i = 0; i < fieldTypeNames.Length; i++) { string fieldTypeName = fieldTypeNames[i]; if (fieldTypeName != null) { GenerateCode(fieldTypeName, matches[i].Matches); } } }
/// <summary> /// /// </summary> /// <param name="xsdFilename"></param> /// <param name="targetNamespace"></param> /// <returns></returns> public static CodeNamespace Process(string xsdFilename, string targetNamespace) { XmlReaderSettings settings = new XmlReaderSettings { }; XmlSchema xsd; using (var reader = XmlReader.Create(xsdFilename)) { xsd = XmlSchema.Read(reader, MyValidationEventHandler); } XmlSchemas schemas = new XmlSchemas(); // Internal class int elementCount = xsd.Elements.Count; // 0 Elements is a post-schema-compilation property int indexOf = schemas.Add(xsd); // Method will only add (to end) if it does not exists, and return the one stored internally elementCount = xsd.Elements.Count; // 1 OOOPS! Looks like Add do some magic to added XmlSchema schemas.Compile(MyValidationEventHandler, true); // What is fullCompile? //var appinfos = xsd.Items.OfType<XmlSchemaAnnotation>().SelectMany(a => a.Items.OfType<XmlSchemaAppInfo>().SelectMany(m => m.Markup)).ToList(); //foreach (var attr in xsd.UnhandledAttributes) //{ // Console.WriteLine("UnhandledAttribute: " + attr.LocalName); //} // Create the importer for these schemas. CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); // shared import & export CodeGenerationOptions options = CodeGenerationOptions.GenerateProperties; // shared import & export CodeIdentifiers typeIdentifiers = new CodeIdentifiers(); ImportContext context = new ImportContext(typeIdentifiers, true); // true=share custom types amongst schemas XmlSchemaImporter importer = new XmlSchemaImporter(schemas, options, context); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(targetNamespace); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); Hashtable mappings = new Hashtable(); XmlCodeExporter exporter = new XmlCodeExporter(ns, codeCompileUnit, options, mappings); // Test identifier uniqueness string s = "FirstName"; var ustr = typeIdentifiers.MakeUnique(s); // FirstName ustr = typeIdentifiers.MakeUnique(s); // FirstName typeIdentifiers.Add(s, s); ustr = typeIdentifiers.MakeUnique(s); // FirstName1 typeIdentifiers.Remove(s); ustr = typeIdentifiers.MakeUnique(s); // FirstName typeIdentifiers.Add(s, s); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in xsd.Elements.Values) { //var appinfos = element.Annotation.Items.OfType<XmlSchemaAppInfo>().ToArray(); // Import the mapping first. var ss = typeIdentifiers.ToArray(typeof(string)); // 1 XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); ss = typeIdentifiers.ToArray(typeof(string)); // 2 // Export the code finally. int count = mappings.Count; // 0 exporter.ExportTypeMapping(mapping); count = mappings.Count; // 5 } foreach (var schemaType in xsd.SchemaTypes.Values.Cast <XmlSchemaType>()) { var map2 = importer.ImportSchemaType(schemaType.QualifiedName); string s2 = map2.TypeFullName; } return(ns); }
protected override CodeTypeDeclaration BeginClass() { soapBinding = (SoapBinding)Binding.Extensions.Find(typeof(SoapBinding)); CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName); codeClass.IsPartial = true; string location = null; if (Port != null) { SoapAddressBinding sab = (SoapAddressBinding)Port.Extensions.Find(typeof(SoapAddressBinding)); if (sab != null) { location = sab.Location; } } string namspace = (Port != null ? Port.Binding.Namespace : Binding.ServiceDescription.TargetNamespace); string name = (Port != null ? Port.Name : Binding.Name); if (Style == ServiceDescriptionImportStyle.Client) { CodeTypeReference ctr = new CodeTypeReference("System.Web.Services.Protocols.SoapHttpClientProtocol"); codeClass.BaseTypes.Add(ctr); } else { CodeTypeReference ctr = new CodeTypeReference("System.Web.Services.WebService"); codeClass.BaseTypes.Add(ctr); CodeAttributeDeclaration attws = new CodeAttributeDeclaration("System.Web.Services.WebServiceAttribute"); attws.Arguments.Add(GetArg("Namespace", namspace)); AddCustomAttribute(codeClass, attws, true); } CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.WebServiceBinding"); att.Arguments.Add(GetArg("Name", name)); att.Arguments.Add(GetArg("Namespace", namspace)); AddCustomAttribute(codeClass, att, true); if (Style == ServiceDescriptionImportStyle.Client) { CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public; GenerateServiceUrl(location, cc.Statements); if (ProtocolName.ToUpper() == "SOAP12") { CodeExpression thisSoapVer = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "SoapVersion"); CodeFieldReferenceExpression soap12Enum = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapProtocolVersion)), "Soap12"); cc.Statements.Add(new CodeAssignStatement(thisSoapVer, soap12Enum)); } codeClass.Members.Add(cc); } memberIds = new CodeIdentifiers(); headerVariables = new Hashtable(); return(codeClass); }
public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) { }
internal static SoapReflectedMethod ReflectMethod(LogicalMethodInfo methodInfo, bool client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, string defaultNs) { try { SoapReflectedMethod soapMethod = new SoapReflectedMethod(); MethodAttribute methodAttribute = new MethodAttribute(); object serviceAttr = GetSoapServiceAttribute(methodInfo.DeclaringType); bool serviceDefaultIsEncoded = ServiceDefaultIsEncoded(serviceAttr); object methodAttr = GetSoapMethodAttribute(methodInfo); if (methodAttr == null) { if (client) { return(null); // method attribute required on the client } if (serviceAttr is SoapRpcServiceAttribute) { methodAttr = new SoapRpcMethodAttribute(); } else { methodAttr = new SoapDocumentMethodAttribute(); } } if (methodAttr is SoapRpcMethodAttribute) { SoapRpcMethodAttribute attr = (SoapRpcMethodAttribute)methodAttr; soapMethod.rpc = true; soapMethod.use = SoapBindingUse.Encoded; soapMethod.oneWay = attr.OneWay; methodAttribute.action = attr.Action; methodAttribute.binding = attr.Binding; methodAttribute.requestName = attr.RequestElementName; methodAttribute.requestNs = attr.RequestNamespace; methodAttribute.responseName = attr.ResponseElementName; methodAttribute.responseNs = attr.ResponseNamespace; } else { SoapDocumentMethodAttribute attr = (SoapDocumentMethodAttribute)methodAttr; soapMethod.rpc = false; soapMethod.use = attr.Use; soapMethod.paramStyle = attr.ParameterStyle; soapMethod.oneWay = attr.OneWay; methodAttribute.action = attr.Action; methodAttribute.binding = attr.Binding; methodAttribute.requestName = attr.RequestElementName; methodAttribute.requestNs = attr.RequestNamespace; methodAttribute.responseName = attr.ResponseElementName; methodAttribute.responseNs = attr.ResponseNamespace; if (soapMethod.use == SoapBindingUse.Default) { if (serviceAttr is SoapDocumentServiceAttribute) { soapMethod.use = ((SoapDocumentServiceAttribute)serviceAttr).Use; } if (soapMethod.use == SoapBindingUse.Default) { soapMethod.use = SoapBindingUse.Literal; } } if (soapMethod.paramStyle == SoapParameterStyle.Default) { if (serviceAttr is SoapDocumentServiceAttribute) { soapMethod.paramStyle = ((SoapDocumentServiceAttribute)serviceAttr).ParameterStyle; } if (soapMethod.paramStyle == SoapParameterStyle.Default) { soapMethod.paramStyle = SoapParameterStyle.Wrapped; } } } if (methodAttribute.binding.Length > 0) { if (client) { throw new InvalidOperationException(Res.GetString(Res.WebInvalidBindingPlacement, methodAttr.GetType().Name)); } soapMethod.binding = WebServiceBindingReflector.GetAttribute(methodInfo, methodAttribute.binding); } WebMethodAttribute webMethodAttribute = WebMethodReflector.GetAttribute(methodInfo); soapMethod.name = webMethodAttribute.MessageName; if (soapMethod.name.Length == 0) { soapMethod.name = methodInfo.Name; } string requestElementName; if (soapMethod.rpc) { requestElementName = methodInfo.Name; } else { requestElementName = methodAttribute.requestName.Length == 0 ? soapMethod.name : methodAttribute.requestName; } string requestNamespace = methodAttribute.requestNs; if (requestNamespace == null) { if (soapMethod.binding != null && soapMethod.binding.Namespace != null && soapMethod.binding.Namespace.Length != 0) { requestNamespace = soapMethod.binding.Namespace; } else { requestNamespace = defaultNs; } } string responseElementName = methodAttribute.responseName.Length == 0 ? soapMethod.name + "Response": methodAttribute.responseName; string responseNamespace = methodAttribute.responseNs; if (responseNamespace == null) { if (soapMethod.binding != null && soapMethod.binding.Namespace != null && soapMethod.binding.Namespace.Length != 0) { responseNamespace = soapMethod.binding.Namespace; } else { responseNamespace = defaultNs; } } SoapParameterInfo[] inParameters = ReflectParameters(methodInfo.InParameters, requestNamespace); SoapParameterInfo[] outParameters = ReflectParameters(methodInfo.OutParameters, responseNamespace); soapMethod.action = methodAttribute.action; if (soapMethod.action == null) { soapMethod.action = GetDefaultAction(defaultNs, methodInfo); } soapMethod.methodInfo = methodInfo; if (soapMethod.oneWay) { if (outParameters.Length > 0) { throw new ArgumentException(Res.GetString(Res.WebOneWayOutParameters), "methodInfo"); } if (methodInfo.ReturnType != typeof(void)) { throw new ArgumentException(Res.GetString(Res.WebOneWayReturnValue), "methodInfo"); } } XmlReflectionMember[] members = new XmlReflectionMember[inParameters.Length]; for (int i = 0; i < members.Length; i++) { SoapParameterInfo soapParamInfo = inParameters[i]; XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = soapParamInfo.parameterInfo.Name; member.MemberType = soapParamInfo.parameterInfo.ParameterType; if (member.MemberType.IsByRef) { member.MemberType = member.MemberType.GetElementType(); } member.XmlAttributes = soapParamInfo.xmlAttributes; member.SoapAttributes = soapParamInfo.soapAttributes; members[i] = member; } soapMethod.requestMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, soapMethod.rpc, soapMethod.use, soapMethod.paramStyle, requestElementName, requestNamespace, methodAttribute.requestNs == null, members, true); if (GetSoapServiceRoutingStyle(serviceAttr) == SoapServiceRoutingStyle.RequestElement && soapMethod.paramStyle == SoapParameterStyle.Bare && soapMethod.requestMappings.Count != 1) { throw new ArgumentException(Res.GetString(Res.WhenUsingAMessageStyleOfParametersAsDocument0), "methodInfo"); } string elementName = ""; string elementNamespace = ""; if (soapMethod.paramStyle == SoapParameterStyle.Bare) { if (soapMethod.requestMappings.Count == 1) { elementName = soapMethod.requestMappings[0].ElementName; elementNamespace = soapMethod.requestMappings[0].Namespace; } // else: can't route on request element -- we match on an empty qname, // normal rules apply for duplicates } else { elementName = soapMethod.requestMappings.ElementName; elementNamespace = soapMethod.requestMappings.Namespace; } soapMethod.requestElementName = new XmlQualifiedName(elementName, elementNamespace); if (!soapMethod.oneWay) { int numOutParams = outParameters.Length; int count = 0; CodeIdentifiers identifiers = null; if (methodInfo.ReturnType != typeof(void)) { numOutParams++; count = 1; identifiers = new CodeIdentifiers(); } members = new XmlReflectionMember[numOutParams]; for (int i = 0; i < outParameters.Length; i++) { SoapParameterInfo soapParamInfo = outParameters[i]; XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = soapParamInfo.parameterInfo.Name; member.MemberType = soapParamInfo.parameterInfo.ParameterType; if (member.MemberType.IsByRef) { member.MemberType = member.MemberType.GetElementType(); } member.XmlAttributes = soapParamInfo.xmlAttributes; member.SoapAttributes = soapParamInfo.soapAttributes; members[count++] = member; if (identifiers != null) { identifiers.Add(member.MemberName, null); } } if (methodInfo.ReturnType != typeof(void)) { XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = identifiers.MakeUnique(soapMethod.name + "Result"); member.MemberType = methodInfo.ReturnType; member.IsReturnValue = true; member.XmlAttributes = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider); member.XmlAttributes.XmlRoot = null; // Ignore XmlRoot attribute used by get/post member.SoapAttributes = new SoapAttributes(methodInfo.ReturnTypeCustomAttributeProvider); members[0] = member; } soapMethod.responseMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, soapMethod.rpc, soapMethod.use, soapMethod.paramStyle, responseElementName, responseNamespace, methodAttribute.responseNs == null, members, false); } SoapExtensionAttribute[] extensionAttributes = (SoapExtensionAttribute[])methodInfo.GetCustomAttributes(typeof(SoapExtensionAttribute)); soapMethod.extensions = new SoapReflectedExtension[extensionAttributes.Length]; for (int i = 0; i < extensionAttributes.Length; i++) { soapMethod.extensions[i] = new SoapReflectedExtension(extensionAttributes[i].ExtensionType, extensionAttributes[i]); } Array.Sort(soapMethod.extensions); SoapHeaderAttribute[] headerAttributes = (SoapHeaderAttribute[])methodInfo.GetCustomAttributes(typeof(SoapHeaderAttribute)); Array.Sort(headerAttributes, new SoapHeaderAttributeComparer()); Hashtable headerTypes = new Hashtable(); soapMethod.headers = new SoapReflectedHeader[headerAttributes.Length]; int front = 0; int back = soapMethod.headers.Length; ArrayList inHeaders = new ArrayList(); ArrayList outHeaders = new ArrayList(); for (int i = 0; i < soapMethod.headers.Length; i++) { SoapHeaderAttribute headerAttribute = headerAttributes[i]; SoapReflectedHeader soapHeader = new SoapReflectedHeader(); Type declaringType = methodInfo.DeclaringType; if ((soapHeader.memberInfo = declaringType.GetField(headerAttribute.MemberName)) != null) { soapHeader.headerType = ((FieldInfo)soapHeader.memberInfo).FieldType; } else if ((soapHeader.memberInfo = declaringType.GetProperty(headerAttribute.MemberName)) != null) { soapHeader.headerType = ((PropertyInfo)soapHeader.memberInfo).PropertyType; } else { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderMissing); } if (soapHeader.headerType.IsArray) { soapHeader.headerType = soapHeader.headerType.GetElementType(); soapHeader.repeats = true; if (soapHeader.headerType != typeof(SoapUnknownHeader) && soapHeader.headerType != typeof(SoapHeader)) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderType); } } if (MemberHelper.IsStatic(soapHeader.memberInfo)) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderStatic); } if (!MemberHelper.CanRead(soapHeader.memberInfo)) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderRead); } if (!MemberHelper.CanWrite(soapHeader.memberInfo)) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderWrite); } if (!typeof(SoapHeader).IsAssignableFrom(soapHeader.headerType)) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderType); } SoapHeaderDirection direction = headerAttribute.Direction; if (soapMethod.oneWay && (direction & (SoapHeaderDirection.Out | SoapHeaderDirection.Fault)) != 0) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderOneWayOut); } if (headerTypes.Contains(soapHeader.headerType)) { SoapHeaderDirection prevDirection = (SoapHeaderDirection)headerTypes[soapHeader.headerType]; if ((prevDirection & direction) != 0) { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebMultiplyDeclaredHeaderTypes); } headerTypes[soapHeader.headerType] = direction | prevDirection; } else { headerTypes[soapHeader.headerType] = direction; } if (soapHeader.headerType != typeof(SoapHeader) && soapHeader.headerType != typeof(SoapUnknownHeader)) { XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = soapHeader.headerType.Name; member.MemberType = soapHeader.headerType; member.OverrideIsNullable = true; if ((direction & SoapHeaderDirection.In) != 0) { inHeaders.Add(member); } if ((direction & (SoapHeaderDirection.Out | SoapHeaderDirection.Fault)) != 0) { outHeaders.Add(member); } soapHeader.custom = true; } soapHeader.direction = direction; // Put generic header mappings at the end of the list so they are found last during header processing if (!soapHeader.custom) { soapMethod.headers[--back] = soapHeader; } else { soapMethod.headers[front++] = soapHeader; } } soapMethod.inHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, soapMethod.use, SoapParameterStyle.Bare, "InHeaders", defaultNs, true, (XmlReflectionMember[])inHeaders.ToArray(typeof(XmlReflectionMember)), false); if (!soapMethod.oneWay) { soapMethod.outHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, soapMethod.use, SoapParameterStyle.Bare, "OutHeaders", defaultNs, true, (XmlReflectionMember[])outHeaders.ToArray(typeof(XmlReflectionMember)), false); } return(soapMethod); } catch (Exception e) { throw new InvalidOperationException(Res.GetString(Res.WebReflectionErrorMethod, methodInfo.DeclaringType.Name, methodInfo.Name), e); } }
// Constructors public ImportContext(CodeIdentifiers identifiers, bool shareTypes) {}
void CreateHeaderMessages(string methodName, SoapBindingUse use, XmlMembersMapping inHeaderMappings, XmlMembersMapping outHeaderMappings, SoapReflectedHeader[] headers, bool rpc) { // if (use == SoapBindingUse.Encoded) { SoapExporter.ExportMembersMapping(inHeaderMappings, false); if (outHeaderMappings != null) { SoapExporter.ExportMembersMapping(outHeaderMappings, false); } } else { SchemaExporter.ExportMembersMapping(inHeaderMappings); if (outHeaderMappings != null) { SchemaExporter.ExportMembersMapping(outHeaderMappings); } } CodeIdentifiers identifiers = new CodeIdentifiers(); int inCount = 0, outCount = 0; for (int i = 0; i < headers.Length; i++) { SoapReflectedHeader soapHeader = headers[i]; if (!soapHeader.custom) { continue; } XmlMemberMapping member; if ((soapHeader.direction & SoapHeaderDirection.In) != 0) { member = inHeaderMappings[inCount++]; if (soapHeader.direction != SoapHeaderDirection.In) { outCount++; } } else { member = outHeaderMappings[outCount++]; } MessagePart part = new MessagePart(); part.Name = member.XsdElementName; if (use == SoapBindingUse.Encoded) { part.Type = new XmlQualifiedName(member.TypeName, member.TypeNamespace); } else { part.Element = new XmlQualifiedName(member.XsdElementName, member.Namespace); } Message message = new Message(); message.Name = identifiers.AddUnique(methodName + part.Name, message); message.Parts.Add(part); HeaderMessages.Add(message); ServiceDescriptionFormatExtension soapHeaderBinding = CreateSoapHeaderBinding(new XmlQualifiedName(message.Name, Binding.ServiceDescription.TargetNamespace), part.Name, rpc ? member.Namespace : null, use); if ((soapHeader.direction & SoapHeaderDirection.In) != 0) { OperationBinding.Input.Extensions.Add(soapHeaderBinding); } if ((soapHeader.direction & SoapHeaderDirection.Out) != 0) { OperationBinding.Output.Extensions.Add(soapHeaderBinding); } if ((soapHeader.direction & SoapHeaderDirection.Fault) != 0) { if (soapMethod.IsClaimsConformance) { throw new InvalidOperationException(Res.GetString(Res.BPConformanceHeaderFault, soapMethod.methodInfo.ToString(), soapMethod.methodInfo.DeclaringType.FullName, "Direction", typeof(SoapHeaderDirection).Name, SoapHeaderDirection.Fault.ToString())); } OperationBinding.Output.Extensions.Add(soapHeaderBinding); } } }
void AddAsyncMembers(string messageName, CodeMemberMethod method) { CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodePrimitiveExpression enull = new CodePrimitiveExpression(null); CodeMemberField codeField = new CodeMemberField(typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted"); codeField.Attributes = MemberAttributes.Private; CodeTypeDeclaration.Members.Add(codeField); // Event arguments class string argsClassName = classNames.AddUnique(messageName + "CompletedEventArgs", null); CodeTypeDeclaration argsClass = new CodeTypeDeclaration(argsClassName); argsClass.Attributes |= MemberAttributes.Public; #if NET_2_0 argsClass.IsPartial = true; #endif argsClass.BaseTypes.Add(new CodeTypeReference("System.ComponentModel.AsyncCompletedEventArgs")); CodeMemberField resultsField = new CodeMemberField(typeof(object[]), "results"); resultsField.Attributes = MemberAttributes.Private; argsClass.Members.Add(resultsField); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Assembly; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "results")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Exception), "exception")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("exception")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("cancelled")); cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("userState")); CodeExpression thisResults = new CodeFieldReferenceExpression(ethis, "results"); cc.Statements.Add(new CodeAssignStatement(thisResults, new CodeVariableReferenceExpression("results"))); argsClass.Members.Add(cc); int ind = 0; if (method.ReturnType.BaseType != "System.Void") { argsClass.Members.Add(CreateArgsProperty(method.ReturnType, "Result", ind++)); } foreach (CodeParameterDeclarationExpression par in method.Parameters) { if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref) { argsClass.Members.Add(CreateArgsProperty(par.Type, par.Name, ind++)); } } bool needsArgsClass = (ind > 0); if (needsArgsClass) { asyncTypes.Add(argsClass); } else { argsClassName = "System.ComponentModel.AsyncCompletedEventArgs"; } // Event delegate type CodeTypeDelegate delegateType = new CodeTypeDelegate(messageName + "CompletedEventHandler"); delegateType.Attributes |= MemberAttributes.Public; delegateType.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); delegateType.Parameters.Add(new CodeParameterDeclarationExpression(argsClassName, "args")); // Event member CodeMemberEvent codeEvent = new CodeMemberEvent(); codeEvent.Attributes = codeEvent.Attributes & ~MemberAttributes.AccessMask | MemberAttributes.Public; codeEvent.Name = messageName + "Completed"; codeEvent.Type = new CodeTypeReference(delegateType.Name); CodeTypeDeclaration.Members.Add(codeEvent); // Async method (without user state param) CodeMemberMethod am = new CodeMemberMethod(); am.Attributes = MemberAttributes.Public | MemberAttributes.Final; am.Name = method.Name + "Async"; am.ReturnType = new CodeTypeReference(typeof(void)); CodeMethodInvokeExpression inv; inv = new CodeMethodInvokeExpression(ethis, am.Name); am.Statements.Add(inv); // On...Completed method CodeMemberMethod onCompleted = new CodeMemberMethod(); onCompleted.Name = "On" + messageName + "Completed"; onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final; onCompleted.ReturnType = new CodeTypeReference(typeof(void)); onCompleted.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "arg")); CodeConditionStatement anIf = new CodeConditionStatement(); CodeExpression eventField = new CodeEventReferenceExpression(ethis, codeEvent.Name); anIf.Condition = new CodeBinaryOperatorExpression(eventField, CodeBinaryOperatorType.IdentityInequality, enull); CodeExpression castedArg = new CodeCastExpression(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression("arg")); CodeStatement invokeArgs = new CodeVariableDeclarationStatement(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg); anIf.TrueStatements.Add(invokeArgs); CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression(); delegateInvoke.TargetObject = eventField; delegateInvoke.Parameters.Add(ethis); CodeObjectCreateExpression argsInstance = new CodeObjectCreateExpression(argsClassName); CodeExpression invokeArgsVar = new CodeVariableReferenceExpression("invokeArgs"); if (needsArgsClass) { argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Results")); } argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Error")); argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Cancelled")); argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "UserState")); delegateInvoke.Parameters.Add(argsInstance); anIf.TrueStatements.Add(delegateInvoke); onCompleted.Statements.Add(anIf); // Async method CodeMemberMethod asyncMethod = new CodeMemberMethod(); asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; asyncMethod.Name = method.Name + "Async"; asyncMethod.ReturnType = new CodeTypeReference(typeof(void)); CodeExpression delegateField = new CodeFieldReferenceExpression(ethis, codeField.Name); anIf = new CodeConditionStatement(); anIf.Condition = new CodeBinaryOperatorExpression(delegateField, CodeBinaryOperatorType.IdentityEquality, enull);; CodeExpression delegateRef = new CodeMethodReferenceExpression(ethis, onCompleted.Name); CodeExpression newDelegate = new CodeObjectCreateExpression(typeof(System.Threading.SendOrPostCallback), delegateRef); CodeAssignStatement cas = new CodeAssignStatement(delegateField, newDelegate); anIf.TrueStatements.Add(cas); asyncMethod.Statements.Add(anIf); CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression(typeof(object)); // Assign parameters CodeIdentifiers paramsIds = new CodeIdentifiers(); foreach (CodeParameterDeclarationExpression par in method.Parameters) { paramsIds.Add(par.Name, null); if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref) { CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression(par.Type, par.Name); am.Parameters.Add(inpar); asyncMethod.Parameters.Add(inpar); inv.Parameters.Add(new CodeVariableReferenceExpression(par.Name)); paramsArray.Initializers.Add(new CodeVariableReferenceExpression(par.Name)); } } inv.Parameters.Add(enull); string userStateName = paramsIds.AddUnique("userState", null); asyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userStateName)); CodeExpression userStateVar = new CodeVariableReferenceExpression(userStateName); asyncMethod.Statements.Add(BuildInvokeAsync(messageName, paramsArray, delegateField, userStateVar)); CodeTypeDeclaration.Members.Add(am); CodeTypeDeclaration.Members.Add(asyncMethod); CodeTypeDeclaration.Members.Add(onCompleted); asyncTypes.Add(delegateType); }
internal bool Import(ServiceDescriptionImporter descriptionImporter, CodeNamespace codeNamespace, ArrayList importInfo) { this.descriptionImporter = descriptionImporter; this.classNames = new CodeIdentifiers();; this.codeNamespace = codeNamespace; warnings = (ServiceDescriptionImportWarnings)0; bool found = false; ClasifySchemas(importInfo); BeginNamespace(); foreach (ImportInfo info in importInfo) { foreach (Service service in info.ServiceDescription.Services) { this.service = service; int bindingCount = 0; foreach (Port port in service.Ports) { binding = ServiceDescriptions.GetBinding(port.Binding); if (IsBindingSupported()) { bindingCount++; } } foreach (Port port in service.Ports) { this.iinfo = info; this.port = port; binding = ServiceDescriptions.GetBinding(port.Binding); if (!IsBindingSupported()) { continue; } found = true; ImportPortBinding(bindingCount > 1); } } } if (!found) { // Looks like MS.NET generates classes for all bindings if // no services are present foreach (ImportInfo info in importInfo) { this.iinfo = info; foreach (Binding b in info.ServiceDescription.Bindings) { this.binding = b; this.service = null; this.port = null; if (!IsBindingSupported()) { continue; } found = true; ImportPortBinding(true); } } } EndNamespace(); if (!found) { warnings = ServiceDescriptionImportWarnings.NoCodeGenerated; } return(found); }
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(); } }
static void Main(string[] args) { CodeCompileUnit ccu = new CodeCompileUnit(); ccu.ReferencedAssemblies.AddRange(new[] { "System", "System.Xml.Serialization" }); var schemaSet = new XmlSchemaSet(); // reprocess and compile as much as we want schemaSet.Add(null, @"xsd/mystatus.xsd"); // will add the others schemaSet.Compile(); var mybaseSchema = schemaSet.Schemas("http://tempuri.org/mybase.xsd").OfType <XmlSchema>().Single(); var myderivedSchema = schemaSet.Schemas("http://tempuri.org/myderived.xsd").OfType <XmlSchema>().Single(); var mystatusSchema = schemaSet.Schemas("http://tempuri.org/mystatus.xsd").OfType <XmlSchema>().Single(); //ReplaceBaseWithBasesBase(myderivedSchema); schemaSet.Reprocess(myderivedSchema); schemaSet.Compile(); var xmlSysImport = new CodeNamespaceImport("System"); var xmlNsImport = new CodeNamespaceImport("System.Xml.Serialization"); var mybaseNs = new CodeNamespace("MyBase"); var myDerivedNs = new CodeNamespace("MyDerived") { Imports = { xmlSysImport, xmlNsImport, new CodeNamespaceImport(mybaseNs.Name) } }; var myStatusNs = new CodeNamespace("MyStatus") { Imports = { xmlSysImport, xmlNsImport, new CodeNamespaceImport(myDerivedNs.Name) } }; ccu.Namespaces.AddRange(new[] { mybaseNs, myDerivedNs, myStatusNs }); var schemas = new XmlSchemas(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } //schemas.Compile(ValidationEventHandler, true); // can't change model after compile! XmlSchamaSet.Reprocess handle this! schemas.Compile(ValidationEventHandler, true); CodeIdentifiers typeIdentifiers = new CodeIdentifiers(true); ImportContext context = new ImportContext(typeIdentifiers, shareTypes: false); CodeGenerationOptions options = CodeGenerationOptions.GenerateOrder; var providerOptions = new Dictionary <string, string>(); var provider = new CSharpCodeProvider(providerOptions); XmlSchemaImporter importer = new XmlSchemaImporter(schemas, options, provider, context); // for xml schemas importer.Extensions.Clear(); //importer.Extensions.Add(new MyImporterExtension()); Hashtable mappings = new Hashtable(); MapTypes(mybaseSchema, importer, mybaseNs, ccu, provider, options, mappings); MapTypes(myderivedSchema, importer, myDerivedNs, ccu, provider, options, mappings); MapTypes(mystatusSchema, importer, myStatusNs, ccu, provider, options, mappings); //XmlCodeExporter exporter = new XmlCodeExporter(myStatusNs, ccu, CodeGenerationOptions.GenerateOrder); //foreach (XmlSchemaElement element in mystatusSchema.Elements.Values) //{ // XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); // exporter.ExportTypeMapping(mapping); //} using (StreamWriter writer = File.CreateText(@"..\..\..\TestGeneratedCode\status.cs")) { //globalNs.Comments.Clear(); //globalNs.Name = "MyGlobal"; provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions { BracingStyle = "C", BlankLinesBetweenMembers = false }); } Console.WriteLine("Press enter"); Console.ReadLine(); }
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); }
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 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, 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); }
internal bool GenerateCode(CodeNamespace codeNamespace) { bindingCount = 0; anyPorts = false; this.codeNamespace = codeNamespace; Hashtable supportedBindings = new Hashtable(); Hashtable unsupportedBindings = new Hashtable(); // look for ports with bindings foreach (ServiceDescription serviceDescription in ServiceDescriptions) { foreach (Service service in serviceDescription.Services) { foreach (Port port in service.Ports) { Binding binding = ServiceDescriptions.GetBinding(port.Binding); if (supportedBindings.Contains(binding)) { continue; } PortType portType = ServiceDescriptions.GetPortType(binding.Type); MoveToBinding(service, port, binding, portType); if (IsBindingSupported()) { bindingCount++; anyPorts = true; supportedBindings.Add(binding, binding); } else if (binding != null) { unsupportedBindings[binding] = binding; } } } } // no ports, look for bindings if (bindingCount == 0) { foreach (ServiceDescription serviceDescription in ServiceDescriptions) { foreach (Binding binding in serviceDescription.Bindings) { if (unsupportedBindings.Contains(binding)) { continue; } PortType portType = ServiceDescriptions.GetPortType(binding.Type); MoveToBinding(binding, portType); if (IsBindingSupported()) { bindingCount++; } } } } // give up if no bindings if (bindingCount == 0) { // if we generated comments return true so that the comments get written return(codeNamespace.Comments.Count > 0); } this.identifiers = new CodeIdentifiers(); BeginNamespace(); supportedBindings.Clear(); foreach (ServiceDescription serviceDescription in ServiceDescriptions) { if (anyPorts) { foreach (Service service in serviceDescription.Services) { foreach (Port port in service.Ports) { Binding binding = ServiceDescriptions.GetBinding(port.Binding); PortType portType = ServiceDescriptions.GetPortType(binding.Type); MoveToBinding(service, port, binding, portType); if (IsBindingSupported() && !supportedBindings.Contains(binding)) { GenerateClassForBinding(); supportedBindings.Add(binding, binding); } } } } else { foreach (Binding binding in serviceDescription.Bindings) { PortType portType = ServiceDescriptions.GetPortType(binding.Type); MoveToBinding(binding, portType); if (IsBindingSupported()) { GenerateClassForBinding(); } } } } EndNamespace(); return(true); }
// Constructors public ImportContext(CodeIdentifiers identifiers, bool shareTypes) { }
static void GenerateComponentCode(object component, SteticCompilationUnit globalUnit, CodeNamespace globalNs, CodeExpression cobj, CodeStatementCollection statements, CodeTypeDeclaration globalType, GenerationOptions options, List <SteticCompilationUnit> units, CodeIdentifiers ids, ArrayList warnings) { Gtk.Widget widget = component as Gtk.Widget; Wrapper.Widget wwidget = Stetic.Wrapper.Widget.Lookup(widget); Wrapper.ActionGroup agroup = component as Wrapper.ActionGroup; string name = widget != null ? widget.Name : agroup.Name; string internalClassName = ids.MakeUnique(CodeIdentifier.MakeValid(name)); string typeName = widget != null ? wwidget.WrappedTypeName : "Gtk.ActionGroup"; // Create the build method for the top level CodeMemberMethod met; met = GetBuildMethod(name, internalClassName, typeName, globalUnit, options, units); // Generate the build code CodeVariableDeclarationStatement varDecHash = new CodeVariableDeclarationStatement(typeof(System.Collections.Hashtable).ToGlobalTypeRef(), "bindings"); met.Statements.Add(varDecHash); varDecHash.InitExpression = new CodeObjectCreateExpression( typeof(System.Collections.Hashtable), new CodeExpression [0] ); CodeVariableReferenceExpression targetObjectVar = new CodeVariableReferenceExpression("cobj"); Stetic.WidgetMap map; if (widget != null) { map = Stetic.CodeGenerator.GenerateCreationCode(globalNs, globalType, widget, targetObjectVar, met.Statements, options, warnings); CodeGenerator.BindSignalHandlers(targetObjectVar, wwidget, map, met.Statements, options); } else { map = Stetic.CodeGenerator.GenerateCreationCode(globalNs, globalType, agroup, targetObjectVar, met.Statements, options, warnings); foreach (Wrapper.Action ac in agroup.Actions) { CodeGenerator.BindSignalHandlers(targetObjectVar, ac, map, met.Statements, options); } } GenerateBindFieldCode(met.Statements, cobj); // Add a method call to the build method statements.Add( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(new CodeTypeReference(options.GlobalNamespace + ".SteticGenerated." + internalClassName, CodeTypeReferenceOptions.GlobalReference)), "Build", new CodeCastExpression(typeName.ToGlobalTypeRef(), cobj) ) ); }
internal static SoapReflectedMethod ReflectMethod(LogicalMethodInfo methodInfo, bool client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, string defaultNs) { SoapReflectedMethod method2; try { string str2; string str4; string key = methodInfo.GetKey(); SoapReflectedMethod method = new SoapReflectedMethod(); MethodAttribute attribute = new MethodAttribute(); object soapServiceAttribute = GetSoapServiceAttribute(methodInfo.DeclaringType); bool serviceDefaultIsEncoded = ServiceDefaultIsEncoded(soapServiceAttribute); object soapMethodAttribute = GetSoapMethodAttribute(methodInfo); if (soapMethodAttribute == null) { if (client) { return(null); } if (soapServiceAttribute is SoapRpcServiceAttribute) { SoapRpcMethodAttribute attribute2 = new SoapRpcMethodAttribute { Use = ((SoapRpcServiceAttribute)soapServiceAttribute).Use }; soapMethodAttribute = attribute2; } else if (soapServiceAttribute is SoapDocumentServiceAttribute) { SoapDocumentMethodAttribute attribute3 = new SoapDocumentMethodAttribute { Use = ((SoapDocumentServiceAttribute)soapServiceAttribute).Use }; soapMethodAttribute = attribute3; } else { soapMethodAttribute = new SoapDocumentMethodAttribute(); } } if (soapMethodAttribute is SoapRpcMethodAttribute) { SoapRpcMethodAttribute attribute4 = (SoapRpcMethodAttribute)soapMethodAttribute; method.rpc = true; method.use = attribute4.Use; method.oneWay = attribute4.OneWay; attribute.action = attribute4.Action; attribute.binding = attribute4.Binding; attribute.requestName = attribute4.RequestElementName; attribute.requestNs = attribute4.RequestNamespace; attribute.responseName = attribute4.ResponseElementName; attribute.responseNs = attribute4.ResponseNamespace; } else { SoapDocumentMethodAttribute attribute5 = (SoapDocumentMethodAttribute)soapMethodAttribute; method.rpc = false; method.use = attribute5.Use; method.paramStyle = attribute5.ParameterStyle; method.oneWay = attribute5.OneWay; attribute.action = attribute5.Action; attribute.binding = attribute5.Binding; attribute.requestName = attribute5.RequestElementName; attribute.requestNs = attribute5.RequestNamespace; attribute.responseName = attribute5.ResponseElementName; attribute.responseNs = attribute5.ResponseNamespace; if (method.use == SoapBindingUse.Default) { if (soapServiceAttribute is SoapDocumentServiceAttribute) { method.use = ((SoapDocumentServiceAttribute)soapServiceAttribute).Use; } if (method.use == SoapBindingUse.Default) { method.use = SoapBindingUse.Literal; } } if (method.paramStyle == SoapParameterStyle.Default) { if (soapServiceAttribute is SoapDocumentServiceAttribute) { method.paramStyle = ((SoapDocumentServiceAttribute)soapServiceAttribute).ParameterStyle; } if (method.paramStyle == SoapParameterStyle.Default) { method.paramStyle = SoapParameterStyle.Wrapped; } } } if (attribute.binding.Length > 0) { if (client) { throw new InvalidOperationException(System.Web.Services.Res.GetString("WebInvalidBindingPlacement", new object[] { soapMethodAttribute.GetType().Name })); } method.binding = WebServiceBindingReflector.GetAttribute(methodInfo, attribute.binding); } WebMethodAttribute methodAttribute = methodInfo.MethodAttribute; method.name = methodAttribute.MessageName; if (method.name.Length == 0) { method.name = methodInfo.Name; } if (method.rpc) { str2 = ((attribute.requestName.Length == 0) || !client) ? methodInfo.Name : attribute.requestName; } else { str2 = (attribute.requestName.Length == 0) ? method.name : attribute.requestName; } string requestNs = attribute.requestNs; if (requestNs == null) { if (((method.binding != null) && (method.binding.Namespace != null)) && (method.binding.Namespace.Length != 0)) { requestNs = method.binding.Namespace; } else { requestNs = defaultNs; } } if (method.rpc && (method.use != SoapBindingUse.Encoded)) { str4 = methodInfo.Name + "Response"; } else { str4 = (attribute.responseName.Length == 0) ? (method.name + "Response") : attribute.responseName; } string responseNs = attribute.responseNs; if (responseNs == null) { if (((method.binding != null) && (method.binding.Namespace != null)) && (method.binding.Namespace.Length != 0)) { responseNs = method.binding.Namespace; } else { responseNs = defaultNs; } } SoapParameterInfo[] infoArray = ReflectParameters(methodInfo.InParameters, requestNs); SoapParameterInfo[] infoArray2 = ReflectParameters(methodInfo.OutParameters, responseNs); method.action = attribute.action; if (method.action == null) { method.action = GetDefaultAction(defaultNs, methodInfo); } method.methodInfo = methodInfo; if (method.oneWay) { if (infoArray2.Length > 0) { throw new ArgumentException(System.Web.Services.Res.GetString("WebOneWayOutParameters"), "methodInfo"); } if (methodInfo.ReturnType != typeof(void)) { throw new ArgumentException(System.Web.Services.Res.GetString("WebOneWayReturnValue"), "methodInfo"); } } XmlReflectionMember[] members = new XmlReflectionMember[infoArray.Length]; for (int i = 0; i < members.Length; i++) { SoapParameterInfo info = infoArray[i]; XmlReflectionMember member = new XmlReflectionMember { MemberName = info.parameterInfo.Name, MemberType = info.parameterInfo.ParameterType }; if (member.MemberType.IsByRef) { member.MemberType = member.MemberType.GetElementType(); } member.XmlAttributes = info.xmlAttributes; member.SoapAttributes = info.soapAttributes; members[i] = member; } method.requestMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, method.rpc, method.use, method.paramStyle, str2, requestNs, attribute.requestNs == null, members, true, false, key, client); if (((GetSoapServiceRoutingStyle(soapServiceAttribute) == SoapServiceRoutingStyle.RequestElement) && (method.paramStyle == SoapParameterStyle.Bare)) && (method.requestMappings.Count != 1)) { throw new ArgumentException(System.Web.Services.Res.GetString("WhenUsingAMessageStyleOfParametersAsDocument0"), "methodInfo"); } string name = ""; string ns = ""; if (method.paramStyle == SoapParameterStyle.Bare) { if (method.requestMappings.Count == 1) { name = method.requestMappings[0].XsdElementName; ns = method.requestMappings[0].Namespace; } } else { name = method.requestMappings.XsdElementName; ns = method.requestMappings.Namespace; } method.requestElementName = new XmlQualifiedName(name, ns); if (!method.oneWay) { int num2 = infoArray2.Length; int num3 = 0; CodeIdentifiers identifiers = null; if (methodInfo.ReturnType != typeof(void)) { num2++; num3 = 1; identifiers = new CodeIdentifiers(); } members = new XmlReflectionMember[num2]; for (int m = 0; m < infoArray2.Length; m++) { SoapParameterInfo info2 = infoArray2[m]; XmlReflectionMember member2 = new XmlReflectionMember { MemberName = info2.parameterInfo.Name, MemberType = info2.parameterInfo.ParameterType }; if (member2.MemberType.IsByRef) { member2.MemberType = member2.MemberType.GetElementType(); } member2.XmlAttributes = info2.xmlAttributes; member2.SoapAttributes = info2.soapAttributes; members[num3++] = member2; if (identifiers != null) { identifiers.Add(member2.MemberName, null); } } if (methodInfo.ReturnType != typeof(void)) { XmlReflectionMember member3 = new XmlReflectionMember { MemberName = identifiers.MakeUnique(method.name + "Result"), MemberType = methodInfo.ReturnType, IsReturnValue = true, XmlAttributes = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider) }; member3.XmlAttributes.XmlRoot = null; member3.SoapAttributes = new SoapAttributes(methodInfo.ReturnTypeCustomAttributeProvider); members[0] = member3; } method.responseMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, method.rpc, method.use, method.paramStyle, str4, responseNs, attribute.responseNs == null, members, false, false, key + ":Response", !client); } SoapExtensionAttribute[] customAttributes = (SoapExtensionAttribute[])methodInfo.GetCustomAttributes(typeof(SoapExtensionAttribute)); method.extensions = new SoapReflectedExtension[customAttributes.Length]; for (int j = 0; j < customAttributes.Length; j++) { method.extensions[j] = new SoapReflectedExtension(customAttributes[j].ExtensionType, customAttributes[j]); } Array.Sort <SoapReflectedExtension>(method.extensions); SoapHeaderAttribute[] array = (SoapHeaderAttribute[])methodInfo.GetCustomAttributes(typeof(SoapHeaderAttribute)); Array.Sort(array, new SoapHeaderAttributeComparer()); Hashtable hashtable = new Hashtable(); method.headers = new SoapReflectedHeader[array.Length]; int num6 = 0; int length = method.headers.Length; ArrayList list = new ArrayList(); ArrayList list2 = new ArrayList(); for (int k = 0; k < method.headers.Length; k++) { SoapHeaderAttribute attribute7 = array[k]; SoapReflectedHeader header = new SoapReflectedHeader(); Type declaringType = methodInfo.DeclaringType; header.memberInfo = declaringType.GetField(attribute7.MemberName); if (header.memberInfo != null) { header.headerType = ((FieldInfo)header.memberInfo).FieldType; } else { header.memberInfo = declaringType.GetProperty(attribute7.MemberName); if (header.memberInfo == null) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderMissing"); } header.headerType = ((PropertyInfo)header.memberInfo).PropertyType; } if (header.headerType.IsArray) { header.headerType = header.headerType.GetElementType(); header.repeats = true; if ((header.headerType != typeof(SoapUnknownHeader)) && (header.headerType != typeof(SoapHeader))) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderType"); } } if (MemberHelper.IsStatic(header.memberInfo)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderStatic"); } if (!MemberHelper.CanRead(header.memberInfo)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderRead"); } if (!MemberHelper.CanWrite(header.memberInfo)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderWrite"); } if (!typeof(SoapHeader).IsAssignableFrom(header.headerType)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderType"); } SoapHeaderDirection direction = attribute7.Direction; if (method.oneWay && ((direction & (SoapHeaderDirection.Fault | SoapHeaderDirection.Out)) != 0)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderOneWayOut"); } if (hashtable.Contains(header.headerType)) { SoapHeaderDirection direction2 = (SoapHeaderDirection)hashtable[header.headerType]; if ((direction2 & direction) != 0) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebMultiplyDeclaredHeaderTypes"); } hashtable[header.headerType] = direction | direction2; } else { hashtable[header.headerType] = direction; } if ((header.headerType != typeof(SoapHeader)) && (header.headerType != typeof(SoapUnknownHeader))) { XmlReflectionMember member4 = new XmlReflectionMember { MemberName = header.headerType.Name, MemberType = header.headerType }; XmlAttributes attributes = new XmlAttributes(header.headerType); if (attributes.XmlRoot != null) { member4.XmlAttributes = new XmlAttributes(); XmlElementAttribute attribute8 = new XmlElementAttribute { ElementName = attributes.XmlRoot.ElementName, Namespace = attributes.XmlRoot.Namespace }; member4.XmlAttributes.XmlElements.Add(attribute8); } member4.OverrideIsNullable = true; if ((direction & SoapHeaderDirection.In) != 0) { list.Add(member4); } if ((direction & (SoapHeaderDirection.Fault | SoapHeaderDirection.Out)) != 0) { list2.Add(member4); } header.custom = true; } header.direction = direction; if (!header.custom) { method.headers[--length] = header; } else { method.headers[num6++] = header; } } method.inHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, method.use, SoapParameterStyle.Bare, str2 + "InHeaders", defaultNs, true, (XmlReflectionMember[])list.ToArray(typeof(XmlReflectionMember)), false, true, key + ":InHeaders", client); if (!method.oneWay) { method.outHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, method.use, SoapParameterStyle.Bare, str4 + "OutHeaders", defaultNs, true, (XmlReflectionMember[])list2.ToArray(typeof(XmlReflectionMember)), false, true, key + ":OutHeaders", !client); } method2 = method; } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } throw new InvalidOperationException(System.Web.Services.Res.GetString("WebReflectionErrorMethod", new object[] { methodInfo.DeclaringType.Name, methodInfo.Name }), exception); } return(method2); }
public static void GenerateProjectGuiCode(SteticCompilationUnit globalUnit, CodeNamespace globalNs, CodeTypeDeclaration globalType, GenerationOptions options, List <SteticCompilationUnit> units, ProjectBackend[] projects, ArrayList warnings) { bool multiProject = projects.Length > 1; // Build method overload that takes a type as parameter. CodeMemberMethod met = new CodeMemberMethod(); met.Name = "Build"; globalType.Members.Add(met); met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "cobj")); met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "type")); if (multiProject) { met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "file")); } met.ReturnType = new CodeTypeReference(typeof(void)); met.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeMethodInvokeExpression call = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(new CodeTypeReference(globalNs.Name + ".Gui", CodeTypeReferenceOptions.GlobalReference)), "Build" ), new CodeArgumentReferenceExpression("cobj"), new CodePropertyReferenceExpression( new CodeArgumentReferenceExpression("type"), "FullName" ) ); if (multiProject) { call.Parameters.Add(new CodeArgumentReferenceExpression("file")); } met.Statements.Add(call); // Generate the build method met = new CodeMemberMethod(); met.Name = "Build"; globalType.Members.Add(met); met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "cobj")); met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "id")); if (multiProject) { met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "file")); } met.ReturnType = new CodeTypeReference(typeof(void)); met.Attributes = MemberAttributes.Public | MemberAttributes.Static; if (options.GenerateEmptyBuildMethod) { return; } CodeArgumentReferenceExpression cobj = new CodeArgumentReferenceExpression("cobj"); CodeArgumentReferenceExpression cfile = new CodeArgumentReferenceExpression("file"); CodeArgumentReferenceExpression cid = new CodeArgumentReferenceExpression("id"); CodeStatementCollection projectCol = met.Statements; CodeConditionStatement tcond = new CodeConditionStatement(); tcond.Condition = new CodeMethodInvokeExpression(new CodeTypeOfExpression(typeof(Gtk.Widget)), "IsAssignableFrom", cobj); tcond.TrueStatements.Add( new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(new CodeTypeReference(globalNs.Name + ".Gui", CodeTypeReferenceOptions.GlobalReference)), "Initialize", cobj ) ); // Generate code for each project foreach (ProjectBackend gp in projects) { CodeStatementCollection widgetCol; if (multiProject) { CodeConditionStatement pcond = new CodeConditionStatement(); pcond.Condition = new CodeBinaryOperatorExpression( cfile, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(gp.Id) ); projectCol.Add(pcond); widgetCol = pcond.TrueStatements; projectCol = pcond.FalseStatements; } else { widgetCol = projectCol; } // Generate top levels CodeIdentifiers ids = new CodeIdentifiers(); foreach (Gtk.Widget w in gp.Toplevels) { CodeConditionStatement cond = new CodeConditionStatement(); cond.Condition = new CodeBinaryOperatorExpression( cid, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(w.Name) ); widgetCol.Add(cond); GenerateComponentCode(w, globalUnit, globalNs, cobj, cond.TrueStatements, globalType, options, units, ids, warnings); widgetCol = cond.FalseStatements; } // Generate action groups foreach (Wrapper.ActionGroup agroup in gp.ActionGroups) { CodeConditionStatement cond = new CodeConditionStatement(); cond.Condition = new CodeBinaryOperatorExpression( cid, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(agroup.Name) ); widgetCol.Add(cond); GenerateComponentCode(agroup, globalUnit, globalNs, cobj, cond.TrueStatements, globalType, options, units, ids, warnings); widgetCol = cond.FalseStatements; } } }
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); _writer.WriteLine(); _writer.Write("public abstract class "); _writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); _writer.Write(" : "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" CreateReader() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(readerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" CreateWriter() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(writerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); return(baseSerializer); }
void ReflectBinding(ReflectedBinding reflectedBinding) { string bindingName = reflectedBinding.bindingAttr.Name; string bindingNamespace = reflectedBinding.bindingAttr.Namespace; if (bindingName.Length == 0) { bindingName = Service.Name + ProtocolName; } if (bindingNamespace.Length == 0) { bindingNamespace = ServiceDescription.TargetNamespace; } if (reflectedBinding.bindingAttr.Location.Length > 0) { // If a URL is specified for the WSDL, file, then we just import the // binding from there instead of generating it in this WSDL file. portType = null; binding = null; } else { bindingServiceDescription = GetServiceDescription(bindingNamespace); CodeIdentifiers bindingNames = new CodeIdentifiers(); foreach (Binding b in bindingServiceDescription.Bindings) { bindingNames.AddReserved(b.Name); } bindingName = bindingNames.AddUnique(bindingName, binding); portType = new PortType(); binding = new Binding(); portType.Name = bindingName; binding.Name = bindingName; binding.Type = new XmlQualifiedName(portType.Name, bindingNamespace); bindingServiceDescription.Bindings.Add(binding); bindingServiceDescription.PortTypes.Add(portType); } if (portNames == null) { portNames = new CodeIdentifiers(); foreach (Port p in Service.Ports) { portNames.AddReserved(p.Name); } } port = new Port(); port.Binding = new XmlQualifiedName(bindingName, bindingNamespace); port.Name = portNames.AddUnique(bindingName, port); Service.Ports.Add(port); BeginClass(); foreach (LogicalMethodInfo method in reflectedBinding.methodList) { MoveToMethod(method); operation = new Operation(); operation.Name = method.Name; operation.Documentation = methodAttr.Description; operationBinding = new OperationBinding(); operationBinding.Name = operation.Name; inputMessage = null; outputMessage = null; headerMessages = null; if (ReflectMethod()) { if (inputMessage != null) { bindingServiceDescription.Messages.Add(inputMessage); } if (outputMessage != null) { bindingServiceDescription.Messages.Add(outputMessage); } if (headerMessages != null) { foreach (Message headerMessage in headerMessages) { bindingServiceDescription.Messages.Add(headerMessage); } } binding.Operations.Add(operationBinding); portType.Operations.Add(operation); } } EndClass(); }