示例#1
0
        private CodeTypeDeclaration CreateType(string xmlName, bool includeInSchema)
        {
            int    i       = 1;
            string clrName = CodeIdentifier.MakeValid(xmlName);

            if (CodeTypeContains(clrName))
            {
                while (CodeTypeContains(clrName + i))
                {
                    i++;
                }
                clrName = clrName + i;
            }

            CodeTypeDeclaration decl = new CodeTypeDeclaration(clrName);

            if (includeInSchema)
            {
                if (xmlName != clrName)
                {
                    decl.CustomAttributes.Add(CreateXmlAttribute(typeof(XmlTypeAttribute), xmlName));
                }
            }
            else
            {
                CodeAttributeDeclaration xt = new CodeAttributeDeclaration(typeof(XmlTypeAttribute).FullName);
                xt.Arguments.Add(new CodeAttributeArgument(
                                     "IncludeInSchema",
                                     new CodePrimitiveExpression(false)));
                decl.CustomAttributes.Add(xt);
            }
            return(decl);
        }
示例#2
0
        void ImportEnum(CodeTypeDeclaration td, XmlSchemaSet schemas, XmlSchemaSimpleTypeRestriction r, XmlSchemaType type, XmlQualifiedName qname, bool isFlag)
        {
            if (isFlag && !r.BaseTypeName.Equals(new XmlQualifiedName("string", XmlSchema.Namespace)))
            {
                throw new InvalidDataContractException(String.Format("For flags enumeration '{0}', the base type for the simple type restriction must be XML schema string", qname));
            }

            td.IsEnum = true;
            AddTypeAttributes(td, type);
            if (isFlag)
            {
                td.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(FlagsAttribute))));
            }

            foreach (var facet in r.Facets)
            {
                var e = facet as XmlSchemaEnumerationFacet;
                if (e == null)
                {
                    throw new InvalidDataContractException(String.Format("Invalid simple type restriction (type {0}). Only enumeration is allowed.", qname));
                }
                var em = new CodeMemberField()
                {
                    Name = CodeIdentifier.MakeValid(e.Value)
                };
                var ea = new CodeAttributeDeclaration(enum_member_att_ref);
                if (e.Value != em.Name)
                {
                    ea.Arguments.Add(new CodeAttributeArgument("Value", new CodePrimitiveExpression(e.Value)));
                }
                em.CustomAttributes.Add(ea);
                td.Members.Add(em);
            }
        }
示例#3
0
        void DoImport(XmlSchemaSet schemas, XmlSchemaType type, XmlQualifiedName qname)
        {
            CodeNamespace     cns = null;
            CodeTypeReference clrRef;

            cns    = GetCodeNamespace(qname);
            clrRef = new CodeTypeReference(cns.Name.Length > 0 ? cns.Name + "." + qname.Name : qname.Name);

            var td = new CodeTypeDeclaration()
            {
                Name           = GetUniqueName(CodeIdentifier.MakeValid(qname.Name), cns),
                TypeAttributes = GenerateInternal ? TypeAttributes.NotPublic : TypeAttributes.Public
            };

            cns.Types.Add(td);

            var info = new TypeImportInfo()
            {
                ClrType = clrRef, XsdType = type, XsdTypeName = qname
            };

            imported_types.Add(info);

            var st = type as XmlSchemaSimpleType;

            if (st != null)
            {
                ImportSimpleType(td, schemas, st, qname);
            }
            else
            {
                var ct = (XmlSchemaComplexType)type;
                var sc = ct.ContentModel as XmlSchemaSimpleContent;
                if (sc != null)
                {
                    if (sc.Content is XmlSchemaSimpleContentExtension)
                    {
                        throw new InvalidDataContractException(String.Format("complex type '{0}' with simple content extension is not supported", type.QualifiedName));
                    }
                }
                if (!ImportComplexType(td, schemas, ct, qname))
                {
                    cns.Types.Remove(td);
                    if (cns.Types.Count == 0)
                    {
                        CodeCompileUnit.Namespaces.Remove(cns);
                    }
                }

                foreach (var impinfo in imported_types)
                {
                    for (; impinfo.KnownTypeOutputIndex < impinfo.KnownClrTypes.Count; impinfo.KnownTypeOutputIndex++)
                    {
                        td.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                    new CodeTypeReference(typeof(KnownTypeAttribute)),
                                                    new CodeAttributeArgument(new CodeTypeOfExpression(impinfo.KnownClrTypes [impinfo.KnownTypeOutputIndex]))));
                    }
                }
            }
        }
        public void ValidateWithExceptions()
        {
            if (MemSize <= 0)
            {
                throw new Exception("Invalid memSize, must be greater than 0!");
            }

            if (MemType != "byte" && MemType != "int" && MemType != "long")
            {
                throw new Exception($"Invalid memType '{MemType}'! Valid types are byte, int, long");
            }

            if (!EoFValue.Equals("same", StringComparison.OrdinalIgnoreCase) &&
                !(MemType == "byte" && byte.TryParse(EoFValue, out byte _)) &&
                !(MemType == "int" && int.TryParse(EoFValue, out int _)) &&
                !(MemType == "long" && long.TryParse(EoFValue, out long _)))
            {
                throw new Exception($"Invalid eofValue '{EoFValue}'! Does it match the memType '{MemType}'?");
            }

            if (CodeIdentifier.MakeValid(ClassName) != ClassName)
            {
                throw new Exception($"Invalid class name '{ClassName}'!");
            }
        }
示例#5
0
        internal static CodeTypeDeclaration CreateClassDeclaration(XmlSchemaType type)
        {
            string className = CodeIdentifier.MakeValid(type.QualifiedName.Name);
            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(className);

            codeClass.TypeAttributes |= TypeAttributes.Public;

            return(codeClass);
        }
        MimeParameter ImportUrlParameter(MessagePart part)
        {
            // CONSIDER, check to see that it's a primitive type
            MimeParameter parameter = new MimeParameter();

            parameter.Name     = CodeIdentifier.MakeValid(part.Name);
            parameter.TypeName = IsRepeatingParameter(part) ? typeof(string[]).FullName : typeof(string).FullName;
            return(parameter);
        }
示例#7
0
 public static string MakeValidIdentifier(string identifierName)
 {
     identifierName = CodeIdentifier.MakeValid(identifierName);
     if (isKeyword(identifierName))
     {
         return("@" + identifierName);
     }
     return(identifierName);
 }
示例#8
0
        MimeParameter ImportUrlParameter(MessagePart part)
        {
            //
            MimeParameter parameter = new MimeParameter();

            parameter.Name     = CodeIdentifier.MakeValid(XmlConvert.DecodeName(part.Name));
            parameter.TypeName = IsRepeatingParameter(part) ? typeof(string[]).FullName : typeof(string).FullName;
            return(parameter);
        }
示例#9
0
        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), "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(options.GlobalNamespace + ".SteticGenerated." + internalClassName),
                    "Build",
                    new CodeCastExpression(typeName, cobj)
                    )
                );
        }
示例#10
0
        string MakeStringNamespaceComponentsValid(string ns)
        {
            var arr = ns.Split(split_tokens, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < arr.Length; i++)
            {
                arr [i] = CodeIdentifier.MakeValid(arr [i]);
            }
            return(String.Join(".", arr));
        }
示例#11
0
        void DoImport(XmlSchemaSet schemas, XmlSchemaType type, XmlQualifiedName qname)
        {
            CodeNamespace     cns = null;
            CodeTypeReference clrRef;

            cns    = GetCodeNamespace(qname);
            clrRef = new CodeTypeReference(cns.Name.Length > 0 ? cns.Name + "." + qname.Name : qname.Name);

            var td = new CodeTypeDeclaration();

            td.Name = CodeIdentifier.MakeValid(qname.Name);
            cns.Types.Add(td);

            var info = new TypeImportInfo()
            {
                ClrType = clrRef, XsdType = type, XsdTypeName = qname
            };

            imported_types.Add(info);

            var st = type as XmlSchemaSimpleType;

            if (st != null)
            {
                ImportSimpleType(td, schemas, st, qname);
            }
            else
            {
                var ct = (XmlSchemaComplexType)type;
                var sc = ct.ContentModel as XmlSchemaSimpleContent;
                if (sc != null)
                {
                    if (sc.Content is XmlSchemaSimpleContentExtension)
                    {
                        throw new InvalidDataContractException(String.Format("complex type '{0}' with simple content extension is not supported", type.QualifiedName));
                    }
                }
                if (!ImportComplexType(td, schemas, ct, qname))
                {
                    cns.Types.Remove(td);
                    if (cns.Types.Count == 0)
                    {
                        CodeCompileUnit.Namespaces.Remove(cns);
                    }
                }
            }
        }
示例#12
0
        internal override MimeReturn ImportReturn()
        {
            MimeTextBinding binding = (MimeTextBinding)base.ImportContext.OperationBinding.Output.Extensions.Find(typeof(MimeTextBinding));

            if (binding == null)
            {
                return(null);
            }
            if (binding.Matches.Count == 0)
            {
                base.ImportContext.UnsupportedOperationBindingWarning(Res.GetString("MissingMatchElement0"));
                return(null);
            }
            this.methodName = CodeIdentifier.MakeValid(base.ImportContext.OperationBinding.Name);
            return(new MimeTextReturn {
                TypeName = base.ImportContext.ClassNames.AddUnique(this.methodName + "Matches", binding), TextBinding = binding, ReaderType = typeof(TextReturnReader)
            });
        }
示例#13
0
        public static string MakeValidIdentifier(string identifierName, bool nameMangler2)
        {
            string str;

            if (!nameMangler2)
            {
                identifierName = CodeIdentifier.MakeValid(identifierName);
            }
            else
            {
                if (char.IsDigit(identifierName[0]))
                {
                    identifierName = string.Concat("_", identifierName);
                }
                identifierName = identifierName.Replace('.', '\u005F').Replace('-', '\u005F');
            }
            str = (!NameGenerator.isKeyword(identifierName) ? identifierName : string.Concat("@", identifierName));
            return(str);
        }
示例#14
0
 public static string MakeValidIdentifier(string identifierName, bool nameMangler2)
 {
     if (nameMangler2)
     {
         if (System.Char.IsDigit(identifierName[0]))
         {
             identifierName = "_" + identifierName;
         }
         identifierName = identifierName.Replace('.', '_').Replace('-', '_');
     }
     else
     {
         identifierName = CodeIdentifier.MakeValid(identifierName);
     }
     if (isKeyword(identifierName))
     {
         return("@" + identifierName);
     }
     return(identifierName);
 }
示例#15
0
        internal override MimeReturn ImportReturn()
        {
            MimeTextBinding mimeTextBinding = (MimeTextBinding)ImportContext.OperationBinding.Output.Extensions.Find(typeof(MimeTextBinding));

            if (mimeTextBinding == null)
            {
                return(null);
            }
            if (mimeTextBinding.Matches.Count == 0)
            {
                ImportContext.UnsupportedOperationBindingWarning(Res.GetString(Res.MissingMatchElement0));
                return(null);
            }
            methodName = CodeIdentifier.MakeValid(ImportContext.OperationBinding.Name);

            MimeTextReturn importedReturn = new MimeTextReturn();

            importedReturn.TypeName    = ImportContext.ClassNames.AddUnique(methodName + "Matches", mimeTextBinding);
            importedReturn.TextBinding = mimeTextBinding;
            importedReturn.ReaderType  = typeof(TextReturnReader);
            return(importedReturn);
        }
        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(XmlSerializer).FullName);
            _writer.WriteLine(" {");
            _writer.Indent++;

            _writer.Write("protected override ");
            _writer.Write(typeof(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(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);
        }
示例#17
0
        void AddProperty(CodeTypeDeclaration td, XmlSchemaElement xe)
        {
            var att = GenerateInternal ? MemberAttributes.Assembly : MemberAttributes.Public;
            var fi  = new CodeMemberField()
            {
                Name = CodeIdentifier.MakeValid(xe.QualifiedName.Name + "Field"), Type = GetCodeTypeReference(xe.ElementSchemaType.QualifiedName, xe)
            };

            td.Members.Add(fi);
            var pi = new CodeMemberProperty()
            {
                Name = xe.QualifiedName.Name, Attributes = att, HasGet = true, HasSet = true, Type = fi.Type
            };
            // [DataMember(Name=foobar, IsRequired=!nillable)]
            var dma = new CodeAttributeDeclaration(
                new CodeTypeReference(typeof(DataMemberAttribute)));

            if (fi.Name != xe.QualifiedName.Name)
            {
                new CodeAttributeArgument("Name", new CodePrimitiveExpression(xe.QualifiedName.Name));
            }
            if (!xe.IsNillable)
            {
                new CodeAttributeArgument("IsRequired", new CodePrimitiveExpression(true));
            }
            pi.CustomAttributes.Add(dma);

            pi.GetStatements.Add(new CodeMethodReturnStatement()
            {
                Expression = new CodeFieldReferenceExpression(this_expr, fi.Name)
            });
            pi.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(this_expr, fi.Name), arg_value_expr));


            td.Members.Add(pi);
        }
示例#18
0
        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);
        }
示例#19
0
        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);

                varName = propName;
#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);
        }
示例#20
0
        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);
            }
        }
示例#21
0
        // Returns false if it should remove the imported type.
        // FIXME: also support ImportXmlType
        bool ImportComplexType(CodeTypeDeclaration td, XmlSchemaSet schemas, XmlSchemaComplexType type, XmlQualifiedName qname)
        {
            foreach (XmlSchemaAttribute att in type.AttributeUses.Values)
            {
                if (att.Use != XmlSchemaUse.Optional || att.QualifiedName.Namespace != KnownTypeCollection.MSSimpleNamespace)
                {
                    throw new InvalidDataContractException(String.Format("attribute in DataContract complex type '{0}' is limited to those in {1} namespace, and optional.", qname, KnownTypeCollection.MSSimpleNamespace));
                }
            }

            CodeTypeReference baseClrType = null;
            var particle = type.Particle;

            if (type.ContentModel != null)
            {
                var xsscr = type.ContentModel.Content as XmlSchemaSimpleContentRestriction;
                if (xsscr != null)
                {
                    if (xsscr.BaseType != null)
                    {
                        Import(schemas, xsscr.BaseType);
                    }
                    else
                    {
                        Import(schemas, xsscr.BaseTypeName);
                    }
                    // The above will result in an error, but make sure to show we don't support it.
                    throw new InvalidDataContractException(String.Format("complex type simple content restriction is not supported in DataContract (type '{0}')", qname));
                }
                var xscce = type.ContentModel.Content as XmlSchemaComplexContentExtension;
                if (xscce != null)
                {
                    Import(schemas, xscce.BaseTypeName);
                    baseClrType = GetCodeTypeReferenceInternal(xscce.BaseTypeName, false);
                    if (baseClrType != null)
                    {
                        td.BaseTypes.Add(baseClrType);
                    }

                    var baseInfo = GetTypeInfo(xscce.BaseTypeName, false);
                    if (baseInfo != null)
                    {
                        baseInfo.KnownClrTypes.Add(imported_types.First(it => it.XsdType == type).ClrType);
                    }
                    particle = xscce.Particle;
                }
                var xsccr = type.ContentModel.Content as XmlSchemaComplexContentRestriction;
                if (xsccr != null)
                {
                    throw new InvalidDataContractException(String.Format("complex content type (for type '{0}') has a restriction content model, which is not supported in DataContract.", qname));
                }
            }

            var seq = particle as XmlSchemaSequence;

            if (seq == null && particle != null)
            {
                throw new InvalidDataContractException(String.Format("Not supported particle {1}. In DataContract, only sequence particle is allowed as the top-level content of a complex type (type '{0}')", qname, particle));
            }

            if (seq != null)
            {
                foreach (var child in seq.Items)
                {
                    if (!(child is XmlSchemaElement))
                    {
                        throw new InvalidDataContractException(String.Format("Only local element is allowed as the content of the sequence of the top-level content of a complex type '{0}'. Other particles (sequence, choice, all, any, group ref) are not supported.", qname));
                    }
                }

                if (seq.Items.Count == 1)
                {
                    var xe = (XmlSchemaElement)seq.Items [0];
                    if (xe.MaxOccursString == "unbounded")
                    {
                        // import as a collection contract.
                        if (type.QualifiedName.Namespace == KnownTypeCollection.MSArraysNamespace &&
                            IsPredefinedType(xe.ElementSchemaType.QualifiedName))
                        {
                            // then this CodeTypeDeclaration is to be removed, and CodeTypeReference to this type should be an array instead.
                            var cti = imported_types.First(i => i.XsdType == type);
                            cti.ClrType = new CodeTypeReference(GetCodeTypeReference(xe.ElementSchemaType.QualifiedName), 1);

                            return(false);
                        }
                        else
                        {
                            Import(schemas, xe.ElementSchemaType);
                        }
                        td.BaseTypes.Add(new CodeTypeReference("System.Collections.Generic.List", GetCodeTypeReference(xe.ElementSchemaType.QualifiedName)));
                        AddTypeAttributes(td, type, CodeIdentifier.MakeValid(xe.QualifiedName.Name));
                        return(true);
                    }
                }

                // import as a (normal) contract.
                var elems = new List <XmlSchemaElement> ();
                foreach (XmlSchemaElement xe in seq.Items)
                {
                    if (xe.MaxOccurs != 1)
                    {
                        throw new InvalidDataContractException(String.Format("schema complex type '{0}' has a content sequence containing an element '{1}' with 'maxOccurs' value as more than 1, which is not supported in DataContract.", qname, xe.QualifiedName));
                    }

                    if (elems.Any(e => e.QualifiedName.Name == xe.QualifiedName.Name))
                    {
                        throw new InvalidDataContractException(String.Format("In schema type '{0}', there already is an element whose name is {1}, where duplicate of element names are not supported.", qname, xe.QualifiedName.Name));
                    }

                    elems.Add(xe);
                }
                foreach (var xe in elems)
                {
                    // import property type in prior.
                    Import(schemas, xe.ElementSchemaType.QualifiedName);
                    AddProperty(td, xe);
                }
            }             // if (seq != 0)

            AddTypeAttributes(td, type, null);
            AddExtensionData(td);

            return(true);
        }
        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);
        }
        void GenerateClassForBinding()
        {
            try {
                if (bindingCount == 1 && service != null && Style != ServiceDescriptionImportStyle.ServerInterface)
                {
                    // If there is only one binding, then use the name of the service
                    className = XmlConvert.DecodeName(service.Name);
                }
                else
                {
                    // If multiple bindings, then use the name of the binding
                    className = binding.Name;
                    if (Style == ServiceDescriptionImportStyle.ServerInterface)
                    {
                        // append "I" if we are generating interfaces
                        className = "I" + CodeIdentifier.MakePascal(className);
                    }
                }
                className      = XmlConvert.DecodeName(className);
                className      = ClassNames.AddUnique(CodeIdentifier.MakeValid(className), null);
                this.codeClass = BeginClass();
                int methodCount = 0;
                for (int i = 0; i < portType.Operations.Count; i++)
                {
                    MoveToOperation(portType.Operations[i]);

                    if (!IsOperationFlowSupported(operation.Messages.Flow))
                    {
                        //
                        switch (operation.Messages.Flow)
                        {
                        case OperationFlow.SolicitResponse:
                            UnsupportedOperationWarning(Res.GetString(Res.SolicitResponseIsNotSupported0));
                            continue;

                        case OperationFlow.RequestResponse:
                            UnsupportedOperationWarning(Res.GetString(Res.RequestResponseIsNotSupported0));
                            continue;

                        case OperationFlow.OneWay:
                            UnsupportedOperationWarning(Res.GetString(Res.OneWayIsNotSupported0));
                            continue;

                        case OperationFlow.Notification:
                            UnsupportedOperationWarning(Res.GetString(Res.NotificationIsNotSupported0));
                            continue;
                        }
                    }

                    CodeMemberMethod method;
                    try {
                        method = GenerateMethod();
                    }
                    catch (Exception e) {
                        if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                        {
                            throw;
                        }
                        throw new InvalidOperationException(Res.GetString(Res.UnableToImportOperation1, operation.Name), e);
                    }

                    if (method != null)
                    {
                        AddExtensionWarningComments(codeClass.Comments, operationBinding.Extensions);
                        if (operationBinding.Input != null)
                        {
                            AddExtensionWarningComments(codeClass.Comments, operationBinding.Input.Extensions);
                        }
                        if (operationBinding.Output != null)
                        {
                            AddExtensionWarningComments(codeClass.Comments, operationBinding.Output.Extensions);
                        }
                        methodCount++;
                    }
                }
                bool newAsync = (ServiceImporter.CodeGenerationOptions & CodeGenerationOptions.GenerateNewAsync) != 0 &&
                                ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareEvents) &&
                                ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareDelegates);
                if (newAsync && methodCount > 0 && Style == ServiceDescriptionImportStyle.Client)
                {
                    CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection();
                    string           cancelAsync       = "CancelAsync";
                    string           cancelMethodName  = MethodNames.AddUnique(cancelAsync, cancelAsync);
                    CodeMemberMethod asyncCancelMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, cancelMethodName,
                                                                                    new CodeFlags[1], new string[] { typeof(object).FullName }, new string[] { "userState" },
                                                                                    typeof(void).FullName,
                                                                                    metadata,
                                                                                    CodeFlags.IsPublic | (cancelAsync != cancelMethodName ? 0 : CodeFlags.IsNew));

                    asyncCancelMethod.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));
                    CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), cancelAsync);
                    invoke.Parameters.Add(new CodeArgumentReferenceExpression("userState"));
                    asyncCancelMethod.Statements.Add(invoke);
                }

                EndClass();

                if (portType.Operations.Count == 0)
                {
                    NoMethodsGeneratedWarning();
                }

                AddExtensionWarningComments(codeClass.Comments, binding.Extensions);
                if (port != null)
                {
                    AddExtensionWarningComments(codeClass.Comments, port.Extensions);
                }

                codeNamespace.Types.Add(codeClass);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                {
                    throw;
                }
                throw new InvalidOperationException(Res.GetString(Res.UnableToImportBindingFromNamespace2, binding.Name, binding.ServiceDescription.TargetNamespace), e);
            }
        }
示例#24
0
        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();
            }
        }
示例#25
0
        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 accembly 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 string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
        {
            string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));

            serializerName = classes.AddUnique(serializerName + "Serializer", mapping);

            _writer.WriteLine();
            _writer.Write("public sealed class ");
            _writer.Write(CodeIdentifier.GetCSharpName(serializerName));
            _writer.Write(" : ");
            _writer.Write(baseSerializer);
            _writer.WriteLine(" {");
            _writer.Indent++;

            _writer.WriteLine();
            _writer.Write("public override ");
            _writer.Write(typeof(bool).FullName);
            _writer.Write(" CanDeserialize(");
            _writer.Write(typeof(XmlReader).FullName);
            _writer.WriteLine(" xmlReader) {");
            _writer.Indent++;

            if (mapping.Accessor.Any)
            {
                _writer.WriteLine("return true;");
            }
            else
            {
                _writer.Write("return xmlReader.IsStartElement(");
                WriteQuotedCSharpString(mapping.Accessor.Name);
                _writer.Write(", ");
                WriteQuotedCSharpString(mapping.Accessor.Namespace);
                _writer.WriteLine(");");
            }
            _writer.Indent--;
            _writer.WriteLine("}");

            if (writeMethod != null)
            {
                _writer.WriteLine();
                _writer.Write("protected override void Serialize(object objectToSerialize, ");
                _writer.Write(typeof(XmlSerializationWriter).FullName);
                _writer.WriteLine(" writer) {");
                _writer.Indent++;
                _writer.Write("((");
                _writer.Write(writerClass);
                _writer.Write(")writer).");
                _writer.Write(writeMethod);
                _writer.Write("(");
                if (mapping is XmlMembersMapping)
                {
                    _writer.Write("(object[])");
                }
                _writer.WriteLine("objectToSerialize);");
                _writer.Indent--;
                _writer.WriteLine("}");
            }
            if (readMethod != null)
            {
                _writer.WriteLine();
                _writer.Write("protected override object Deserialize(");
                _writer.Write(typeof(XmlSerializationReader).FullName);
                _writer.WriteLine(" reader) {");
                _writer.Indent++;
                _writer.Write("return ((");
                _writer.Write(readerClass);
                _writer.Write(")reader).");
                _writer.Write(readMethod);
                _writer.WriteLine("();");
                _writer.Indent--;
                _writer.WriteLine("}");
            }
            _writer.Indent--;
            _writer.WriteLine("}");

            return(serializerName);
        }
示例#27
0
        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);
                }
            }
        }
示例#28
0
    static void BuildProxy(ServiceData fd, bool rebuild, ArrayList proxies, XmlElement errdoc)
    {
        string wsdl = GetWsdlFile(fd);

        if (!File.Exists(wsdl))
        {
            return;
        }

        if (fd.Protocols == null)
        {
            ReportError("Client test '" + fd.Name + "': no protocols declared", "");
            return;
        }

        foreach (string prot in fd.Protocols)
        {
            string ns = fd.Namespace;
            ns = CodeIdentifier.MakeValid(ns) + "." + prot;

            string pfile = GetProxyFile(fd, prot);
            if (File.Exists(pfile) && !rebuild)
            {
                proxies.Add(pfile); continue;
            }

            CreateFolderForFile(pfile);

            Console.Write(prot + " proxy for " + wsdl + "... ");
            Process proc = new Process();
            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.FileName  = "wsdl";
            proc.StartInfo.Arguments = "/out:" + pfile + " /nologo /namespace:" + ns + " /protocol:" + prot + " " + wsdl;
            proc.Start();

            if (!proc.WaitForExit(30000))
            {
                try {
                    proc.Kill();
                } catch {}

                Console.WriteLine("FAIL (timeout)");
                if (File.Exists(pfile))
                {
                    File.Delete(pfile);
                }
                WriteError(errdoc, ns, "Errors found while generating " + prot + " proxy for WSDL: " + wsdl, "wsdl.exe timeout");
            }
            else if (proc.ExitCode != 0)
            {
                Console.WriteLine("FAIL " + proc.ExitCode);

                string err = proc.StandardOutput.ReadToEnd();
                err += "\n" + proc.StandardError.ReadToEnd();

                if (File.Exists(pfile))
                {
                    if (proc.ExitCode == 1)
                    {
                        string fn = fd.Name + prot + "Proxy.cs";
                        fn = Path.Combine(GetErrorPath(), fn);
                        CreateFolderForFile(fn);
                        File.Move(pfile, fn);

                        StreamWriter sw = new StreamWriter(fn, true);
                        sw.WriteLine();
                        sw.WriteLine("// " + fd.Wsdl);
                        sw.WriteLine();
                        sw.Close();
                    }
                    else
                    {
                        File.Delete(pfile);
                    }
                }

                WriteError(errdoc, ns, "Errors found while generating " + prot + " proxy for WSDL: " + wsdl, err);
            }
            else
            {
                if (File.Exists(pfile))
                {
                    Console.WriteLine("OK");
                    proxies.Add(pfile);
                }
                else
                {
                    Console.WriteLine("FAIL");
                    string err = proc.StandardOutput.ReadToEnd();
                    err += "\n" + proc.StandardError.ReadToEnd();
                    WriteError(errdoc, ns, "Errors found while generating " + prot + " proxy for WSDL: " + wsdl, err);
                }
            }
        }
    }
示例#29
0
        void GenerateCode(string typeName, MimeTextMatchCollection matches, CodeGenerationOptions options)
        {
            CodeIdentifiers     members   = new CodeIdentifiers();
            CodeTypeDeclaration codeClass = WebCodeGenerator.AddClass(ImportContext.CodeNamespace, typeName, string.Empty, new string[0], null, CodeFlags.IsPublic,
                                                                      ImportContext.ServiceImporter.CodeGenerator.Supports(GeneratorSupport.PartialTypes));

            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 += "[]";
                }

                CodeTypeMember member = WebCodeGenerator.AddMember(codeClass, fieldTypeName, name, null, metadata, CodeFlags.IsPublic, options);

                if (match.Matches.Count == 0 && match.Type.Length > 0)
                {
                    ImportContext.Warnings |= ServiceDescriptionImportWarnings.OptionalExtensionsIgnored;
                    ProtocolImporter.AddWarningComment(member.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, options);
                }
            }
        }
示例#30
0
        void AddTypeAttributes(CodeTypeDeclaration td, XmlSchemaType type, params XmlSchemaElement [] collectionArgs)
        {
            var name = type.QualifiedName;

            // [GeneratedCode (assembly_name, assembly_version)]
            td.CustomAttributes.Add(new CodeAttributeDeclaration(
                                        new CodeTypeReference(typeof(GeneratedCodeAttribute)),
                                        new CodeAttributeArgument(new CodePrimitiveExpression(ass_name)),
                                        new CodeAttributeArgument(new CodePrimitiveExpression(ass_version))));

            var ct = type as XmlSchemaComplexType;

            // [DataContract(Name="foobar",Namespace="urn:foobar")] (optionally IsReference=true),
            // or [CollectionDataContract(ditto, ItemType/KeyType/ValueType)]
            var dca = new CodeAttributeDeclaration(
                collectionArgs != null && collectionArgs.Length > 0 ? typeref_coll_contract : typeref_data_contract,
                new CodeAttributeArgument("Name", new CodePrimitiveExpression(name.Name)),
                new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(name.Namespace)));

            if (collectionArgs != null)
            {
                if (collectionArgs.Length > 0)
                {
                    dca.Arguments.Add(new CodeAttributeArgument("ItemName", new CodePrimitiveExpression(CodeIdentifier.MakeValid(collectionArgs [0].QualifiedName.Name))));
                }
                if (collectionArgs.Length > 2)
                {
                    dca.Arguments.Add(new CodeAttributeArgument("KeyName", new CodePrimitiveExpression(CodeIdentifier.MakeValid(collectionArgs [1].QualifiedName.Name))));
                    dca.Arguments.Add(new CodeAttributeArgument("ValueName", new CodePrimitiveExpression(CodeIdentifier.MakeValid(collectionArgs [2].QualifiedName.Name))));
                }
            }
            if (ct != null && ct.AttributeUses [new XmlQualifiedName("Ref", KnownTypeCollection.MSSimpleNamespace)] != null)
            {
                dca.Arguments.Add(new CodeAttributeArgument("IsReference", new CodePrimitiveExpression(true)));
            }
            td.CustomAttributes.Add(dca);

            // optional [Serializable]
            if (Options != null && Options.GenerateSerializable)
            {
                td.CustomAttributes.Add(new CodeAttributeDeclaration("System.SerializableAttribute"));
            }
        }