示例#1
0
        public static CodeTypeDeclaration CreateUnmarshalHelperType(CodeNamespace ns, string name, bool type_decode)
        {
            var type = ns.AddType(name);

            type.TypeAttributes = TypeAttributes.NestedAssembly;
            type.BaseTypes.Add(typeof(NdrUnmarshalBuffer).ToRef());
            var con = type.AddConstructor(MemberAttributes.Public);

            con.AddParam(typeof(RpcClientResponse).ToRef(), "r");
            var param_var = CodeGenUtils.GetVariable("r");

            con.BaseConstructorArgs.Add(new CodePropertyReferenceExpression(param_var, "NdrBuffer"));
            con.BaseConstructorArgs.Add(new CodePropertyReferenceExpression(param_var, "Handles"));
            con.BaseConstructorArgs.Add(new CodePropertyReferenceExpression(param_var, "DataRepresentation"));

            con = type.AddConstructor(MemberAttributes.Public);
            con.AddParam(typeof(byte[]).ToRef(), "ba");
            con.BaseConstructorArgs.Add(CodeGenUtils.GetVariable("ba"));

            if (type_decode)
            {
                con = type.AddConstructor(MemberAttributes.Public);
                con.AddParam(typeof(NdrPickledType).ToRef(), "pickled_type");
                con.BaseConstructorArgs.Add(CodeGenUtils.GetVariable("pickled_type"));
            }

            return(type);
        }
示例#2
0
        public string GetOutputParameterTypeWithModuleNamePrefix(bool isTS)
        {
            var item = CodeGenUtils.ModelPrefixedClassName(isTS, OutputParameterType) ?? "";

            if (isTS)
            {
                if (item.Trim() == "")
                {
                    return("Promise");
                }
                else
                {
                    return("Promise<" + item + ">");
                }
            }
            else
            {
                if (item.Trim() == "")
                {
                    return("void");
                }
                else
                {
                    return(item);
                }
            }
        }
示例#3
0
        private static CodeExpression AddParam(CodeTypeReference type, int arg_count, CodeMemberMethod method)
        {
            string p_name = $"p{arg_count}";

            method.AddParam(type, p_name);
            return(CodeGenUtils.GetVariable(p_name));
        }
示例#4
0
        /// <summary>
        /// Generate a DPWSHostedService source file from a Wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateHostedService(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string hostedServiceClassName = serviceDesc.Name;
            string hostedServiceNs        = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "HostedService.cs";

            HostedServices hostedServices = new HostedServices(hostedServiceNs);

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                HostedService hostedService = new HostedService(portType.Name, hostedServiceNs, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction  = serviceDesc.TargetNamespace + "/" + operation.Name + "Request";
                    string outAction = serviceDesc.TargetNamespace + "/" + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    hostedService.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    hostedService.Messages.Add(message);
                }
            }

            HostedServiceGenerator hostedServiceGen = new HostedServiceGenerator();

            hostedServiceGen.GenerateCode(filename, hostedServices);
        }
示例#5
0
        void Compile(RPContext ctx, out Func <int, int> expCompiled, out MethodDef native)
        {
            var var    = new Variable("{VAR}");
            var result = new Variable("{RESULT}");

            var int32 = ctx.Module.CorLibTypes.Int32;

            native = new MethodDefUser(ctx.Context.Registry.GetService <INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static)
            {
                ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig
            };
            ctx.Module.GlobalType.Methods.Add(native);

            ctx.Context.Registry.GetService <IMarkerService>().Mark(native, ctx.Protection);
            ctx.Context.Registry.GetService <INameService>().SetCanRename(native, false);

            x86Register?reg;
            var         codeGen = new x86CodeGen();
            Expression  expression;

            do
            {
                ctx.DynCipher.GenerateExpressionPair(
                    ctx.Random,
                    new VariableExpression {
                    Variable = var
                }, new VariableExpression {
                    Variable = result
                },
                    ctx.Depth, out expression, out var inverse);

                reg = codeGen.GenerateX86(inverse, (v, r) => { return(new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }); });
            } while (reg == null);

            var code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

            expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                          .GenerateCIL(expression)
                          .Compile <Func <int, int> >();

            nativeCodes.Add(Tuple.Create(native, code, (MethodBody)null));
            if (!addedHandler)
            {
                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
                addedHandler = true;
            }
        }
示例#6
0
            public void Compile(CFContext ctx)
            {
                var var    = new Variable("{VAR}");
                var result = new Variable("{RESULT}");

                var int32 = ctx.Method.Module.CorLibTypes.Int32;

                native = new MethodDefUser(ctx.Context.Registry.GetService <INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static)
                {
                    ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig
                };
                // Attempt to improve performance --- failed with StackOverflowException... :/
                //var suppressAttr = ctx.Method.Module.CorLibTypes.GetTypeRef("System.Security", "SuppressUnmanagedCodeSecurityAttribute").ResolveThrow();
                //native.CustomAttributes.Add(new CustomAttribute((MemberRef)ctx.Method.Module.Import(suppressAttr.FindDefaultConstructor())));
                //native.HasSecurity = true;
                ctx.Method.Module.GlobalType.Methods.Add(native);

                ctx.Context.Registry.GetService <IMarkerService>().Mark(native, ctx.Protection);
                ctx.Context.Registry.GetService <INameService>().SetCanRename(native, false);

                x86Register?reg;
                var         codeGen = new x86CodeGen();

                do
                {
                    ctx.DynCipher.GenerateExpressionPair(
                        ctx.Random,
                        new VariableExpression {
                        Variable = var
                    }, new VariableExpression {
                        Variable = result
                    },
                        ctx.Depth, out expression, out inverse);

                    reg = codeGen.GenerateX86(inverse, (v, r) => { return(new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }); });
                } while (reg == null);

                code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

                expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                              .GenerateCIL(expression)
                              .Compile <Func <int, int> >();


                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
            }
示例#7
0
        public string GenerateCode()
        {
            switch (ItemType)
            {
            case CsharpItemType.PublicProperty:
                return($"public {Type} {Name} {{ get; set; }}");

            case CsharpItemType.PublicMethod:
                return($@"public {Type} {Name}() 
{{
{CodeGenUtils.Indent(1, string.Join("\r\n", Body))}
}}");

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        /// <summary>
        /// Generate a DPWSClientProxy source file from a wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateClientProxy(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string clientProxyClassName = serviceDesc.Name;
            string clientProxyNs        = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename             = serviceDesc.Name + "ClientProxy.cs";

            ClientProxies clientProxies = new ClientProxies(clientProxyNs);

            string ns = serviceDesc.TargetNamespace.Trim();

            if (!ns.EndsWith("/"))
            {
                ns += "/";
            }

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                ClientProxy clientProxy = new ClientProxy(portType.Name, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction  = ns + operation.Name + "Request";
                    string outAction = ns + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    clientProxy.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    clientProxy.Messages.Add(message);
                }

                if (clientProxy.ServiceOperations.Count > 0)
                {
                    clientProxies.Add(clientProxy);
                }
            }

            ClientProxyGenerator clientProxyGen = new ClientProxyGenerator();

            clientProxyGen.GenerateCode(filename, clientProxies);
        }
示例#9
0
            public void Compile(CEContext ctx)
            {
                var var    = new Variable("{VAR}");
                var result = new Variable("{RESULT}");

                CorLibTypeSig int32 = ctx.Module.CorLibTypes.Int32;

                native = new MethodDefUser("", MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
                native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                ctx.Module.GlobalType.Methods.Add(native);

                ctx.Name.MarkHelper(native, ctx.Marker, ctx.Protection);

                x86Register?reg;
                var         codeGen = new x86CodeGen();

                do
                {
                    ctx.DynCipher.GenerateExpressionPair(
                        ctx.Random,
                        new VariableExpression {
                        Variable = var
                    }, new VariableExpression {
                        Variable = result
                    },
                        4, out expression, out inverse);

                    reg = codeGen.GenerateX86(inverse, (v, r) => { return(new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }); });
                } while (reg == null);

                code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

                expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                              .GenerateCIL(expression)
                              .Compile <Func <int, int> >();


                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
            }
        private void Compile(RPContext ctx, out Func <int, int> expCompiled, out MethodDef native)
        {
            x86Register?  nullable;
            Expression    expression;
            Variable      variable  = new Variable("{VAR}");
            Variable      variable2 = new Variable("{RESULT}");
            CorLibTypeSig retType   = ctx.Module.CorLibTypes.Int32;

            native = new MethodDefUser(ctx.Context.Registry.GetService <INameService>().RandomName(), MethodSig.CreateStatic(retType, retType), MethodAttributes.CompilerControlled | MethodAttributes.PinvokeImpl | MethodAttributes.Static);
            native.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.ManagedMask | MethodImplAttributes.Native | MethodImplAttributes.PreserveSig;
            ctx.Module.GlobalType.Methods.Add(native);
            ctx.Context.Registry.GetService <IMarkerService>().Mark(native, ctx.Protection);
            ctx.Context.Registry.GetService <INameService>().SetCanRename(native, false);
            x86CodeGen codeGen = new x86CodeGen();

            do
            {
                Expression         expression2;
                VariableExpression var = new VariableExpression {
                    Variable = variable
                };
                VariableExpression result = new VariableExpression {
                    Variable = variable2
                };
                ctx.DynCipher.GenerateExpressionPair(ctx.Random, var, result, ctx.Depth, out expression, out expression2);
                nullable = codeGen.GenerateX86(expression2, (v, r) => new x86Instruction[] { x86Instruction.Create(x86OpCode.POP, new Ix86Operand[] { new x86RegisterOperand(r) }) });
            }while (!nullable.HasValue);
            byte[] buffer = CodeGenUtils.AssembleCode(codeGen, nullable.Value);
            expCompiled = new DMCodeGen(typeof(int), new Tuple <string, Type>[] { Tuple.Create <string, Type>("{VAR}", typeof(int)) }).GenerateCIL(expression).Compile <Func <int, int> >();
            this.nativeCodes.Add(Tuple.Create <MethodDef, byte[], dnlib.DotNet.Writer.MethodBody>(native, buffer, null));
            if (!this.addedHandler)
            {
                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += new EventHandler <ModuleWriterListenerEventArgs>(this.InjectNativeCode);
                this.addedHandler = true;
            }
        }
        private static void FixupComplexType(HashSet <NdrComplexTypeReference> fixup_set, NdrComplexTypeReference complex_type, UserDefinedTypeInformation udt)
        {
            if (!fixup_set.Add(complex_type))
            {
                return;
            }

            // Fixup the name to remove compiler generated characters.
            complex_type.Name = CodeGenUtils.MakeIdentifier(udt.Name);
            if (udt.Union)
            {
                if (complex_type is NdrUnionTypeReference union)
                {
                    FixupUnionType(fixup_set, union, udt);
                }
            }
            else
            {
                if (complex_type is NdrBaseStructureTypeReference str)
                {
                    FixupStructureType(fixup_set, str, udt);
                }
            }
        }
示例#12
0
 public string AddGenericMarshal(NdrBaseTypeReference ndr_type, string type_name, string name, AdditionalArguments additional_args)
 {
     return(AddGenericMarshal(ndr_type, new CodeTypeReference(CodeGenUtils.MakeIdentifier(type_name)), name, additional_args));
 }
示例#13
0
        /// <summary>
        /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types,
        /// HostedServices and Client Proxies.
        /// </summary>
        /// <remarks>Currently only generates C# source files.</remarks>
        /// <param name="contractFilename">The name of a contract source code (.cs) file.</param>
        /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param>
        /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param>
        /// <param name="targetPlatform">Specifies the target runtime platform.</param>
        public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform)
        {
            m_platform = targetPlatform;

            Logger.WriteLine("", LogLevel.Normal);
            Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal);

            if (contractFilename == null)
            {
                throw new ArgumentNullException("codeFilename", "You must pass a valid code filename.");
            }

            if (m_svcDesc.Types == null)
            {
                throw new Exception("No wsdl types found.");
            }

            string path = Path.GetDirectoryName(contractFilename).Trim();

            if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // Create code file stream
            FileStream   dcStream       = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter dcStreamWriter = new StreamWriter(dcStream);

            // Write the auto generated header
            dcStreamWriter.Write(AutoGenTextHeader.Message);

            try
            {
                // Set up data contract code generator
                CSharpCodeProvider   cSharpCP       = new CSharpCodeProvider();
                ICodeGenerator       codeGen        = cSharpCP.CreateGenerator(dcStreamWriter);
                CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
                codeGenOptions.BracingStyle = "C";

                // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.'
                string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace);

                // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh!
                foreach (XmlSchema schema in m_svcDesc.Types.Schemas)
                {
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema);
                    schemaSet.Compile();
                }

                // Create new code namespace
                CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName);

                // Add data contract using directives
                CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;");
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using System.Xml;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                if (m_platform == TargetPlatform.MicroFramework)
                {
                    compileUnit.Value = "using System.Ext;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                    compileUnit.Value = "using System.Ext.Xml;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                }
                compileUnit.Value = "using Ws.ServiceModel;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Mtom;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Serialization;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Namespaces.Add(targetNamespace);
                m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces;

                Logger.WriteLine("", LogLevel.Normal);

                // Create HostedServices and ClientProxies collections
                HostedServices hostedServices = new HostedServices(targetNamespaceName);
                ClientProxies  clientProxies  = new ClientProxies(targetNamespaceName);

                // For each PortType process
                foreach (PortType portType in m_svcDesc.PortTypes)
                {
                    // For each operation in the port type:
                    // Get input and output message parts.
                    // If the message part is a simple type:
                    //   Build HostedService operation.
                    // Else if the message part is an element:
                    //   Find elements in Schema
                    //   If element type is native xml type:
                    //     Build HostedService operation.
                    //   Else if element references a simple or complex type:
                    //     If simpleType is base xml type with restrictions:
                    //       Build HostedService operation.
                    //     Else
                    //       Build DataContract and DataContractSerializer.
                    //       Build HostedService Operation.
                    //

                    // Create instance of a HostedService to hold the port type details
                    HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform);

                    // Create instance of ClientProxyGenerator
                    ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform);

                    // Create service contract interface
                    CodeTypeDeclaration      serviceCodeType = new CodeTypeDeclaration("I" + portType.Name);
                    CodeAttributeArgument    codeAttr        = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace));
                    CodeAttributeDeclaration codeAttrDecl    = new CodeAttributeDeclaration("ServiceContract", codeAttr);
                    serviceCodeType.CustomAttributes.Add(codeAttrDecl);

                    // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes
                    // are required to regenerate policy assertions when converting a service to Wsdl.
                    List <PolicyAssertion> policyAssertions = GetPolicyAssertions();
                    bool OptimizedMimeEncoded = false;
                    foreach (PolicyAssertion assert in policyAssertions)
                    {
                        serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID));

                        // if Optimized Mime assertion id found set a processing flag
                        if (assert.Name == "OptimizedMimeSerialization")
                        {
                            OptimizedMimeEncoded = true;
                        }
                    }

                    // Add type declaration
                    serviceCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCodeType.IsInterface    = true;

                    // Create service contract callback client interface
                    CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback");

                    // Add type declaration
                    serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCallbackCodeType.IsInterface    = true;

                    // If the binding contains a ref to Mtom encoding type set the Mtom flag
                    if (OptimizedMimeEncoded)
                    {
                        m_dcCodeGen.EncodingType   = MessageEncodingType.Mtom;
                        hostedService.EncodingType = MessageEncodingType.Mtom;
                        clientProxy.EncodingType   = MessageEncodingType.Mtom;
                    }

                    // Step through port operations, get method names and parse elements.
                    for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index)
                    {
                        Operation operation     = portType.Operations[pt_index];
                        string    operationName = operation.Name;

                        string inputMessageName  = null;
                        string outputMessageName = null;
                        MessagePartCollection inputMessageParts  = null;
                        MessagePartCollection outputMessageParts = null;
                        string inAction  = null;
                        string outAction = null;
                        GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction);

                        // Oneway request port type
                        if (operation.Messages.Flow == OperationFlow.OneWay)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Twoway request/response pattern
                        else if (operation.Messages.Flow == OperationFlow.RequestResponse)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Event pattern
                        else if (operation.Messages.Flow == OperationFlow.Notification)
                        {
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }

                        // Find input and output message parts collection in messages collection
                        // and store for later.
                        foreach (Message message in m_svcDesc.Messages)
                        {
                            if (inputMessageName != null)
                            {
                                if (message.Name == inputMessageName)
                                {
                                    inputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                            }

                            if (outputMessageName != null)
                            {
                                if (message.Name == outputMessageName)
                                {
                                    outputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                            }
                        }

                        try
                        {
                            // Try to generate Data Contracts and DataContractSerializers
                            GenerateTypeContracts(operation, inputMessageParts, outputMessageParts);

                            // If operation flow is notification (event) add OperationContract to ServiceContractCallback
                            // else add OperationContract to ServiceContract
                            if (operation.Messages.Flow == OperationFlow.Notification)
                            {
                                AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType);
                            }
                            else
                            {
                                AddServiceOperationToInterface(operation, inAction, serviceCodeType);
                            }
                        }
                        catch (Exception e)
                        {
                            dcStreamWriter.Close();
                            File.Delete(contractFilename);
                            Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                            return;
                        }
                    }

                    // Add serviceCodeType Service Contract interface to namespace
                    // A serviceCodeType is added even if the wsdl only contains notifications. In that case
                    // the contract will be empty but the ServiceContract attribute and CallbackContract argument
                    // will be used to point to the notification or callback contract interace
                    targetNamespace.Types.Add(serviceCodeType);

                    // If service contract callback type contains members add callback contract to namespace
                    // and add CallbackContract reference attribute to serviceCodeType contract.
                    if (serviceCallbackCodeType.Members.Count > 0)
                    {
                        // Add the callback argument to the service description attribute
                        CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract",
                                                                                      new CodeTypeOfExpression(serviceCallbackCodeType.Name)
                                                                                      );
                        serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg);

                        // Add the callback interface to namespace
                        targetNamespace.Types.Add(serviceCallbackCodeType);
                    }

                    // If the hosted service has opeations add to Hosted Services collection for Code Gen
                    if (hostedService.ServiceOperations.Count > 0)
                    {
                        hostedServices.Add(hostedService);
                    }

                    // If the client Proxy service has opeations add to client proxy collection for Code Gen
                    if (clientProxy.ServiceOperations.Count > 0)
                    {
                        clientProxies.Add(clientProxy);
                    }
                }

                // MOD: 12-02-08 Added code to handle multiple type namespaces
                // Generate contract source file
                foreach (CodeNamespace codeNamespace in compileUnit.Namespaces)
                {
                    codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions);
                }
                dcStreamWriter.Flush();
                dcStreamWriter.Close();

                // Generate Hosted Service code
                Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal);
                HostedServiceGenerator hsGen = new HostedServiceGenerator();
                hsGen.GenerateCode(hostedServiceFilename, hostedServices);

                // Generate Client proxy code
                Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal);
                ClientProxyGenerator cpGen = new ClientProxyGenerator();
                cpGen.GenerateCode(clientProxyFilename, clientProxies);
            }
            catch (Exception e)
            {
                dcStreamWriter.Close();
                File.Delete(contractFilename);
                Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                throw new Exception("Failed to generate service code. ", e);
            }
        }
 public static RpcMarshalArgument CreateFromPrimitive <T>(T primitive)
 {
     return(new RpcMarshalArgument(CodeGenUtils.GetPrimitive(primitive), typeof(T).ToRef()));
 }
 public CodeExpression GetUnmarshalTarget(string unmarshal_name)
 {
     return(CodeGenUtils.GetVariable(unmarshal_name));
 }
示例#16
0
        /// <summary>
        /// Parses a Wsdl message parts collection and builds an array of required message elements and or types.
        /// </summary>
        /// <param name="messageParts">A collection of message parts.</param>
        /// <returns>An array list containing elements and types specified in a Wsdl message parts collection.</returns>
        private ArrayList GetMessageSchemaDefinitions(MessagePartCollection messageParts)
        {
            int       elementCount = 0;               // Used to validate message parts
            int       typeCount    = 0;               // Used to validate message parts
            ArrayList schemaDefs   = new ArrayList(); // When complete contains reference to schema elements for the parts

            // For each input message part find the schema element or type and add it to the inputSchemaParams hash
            foreach (MessagePart part in messageParts)
            {
                // This part defines an element
                if (part.Element.IsEmpty == false && part.Type.IsEmpty == true)
                {
                    // Make sure Element and Type parts are not mixed
                    if (typeCount > 0)
                    {
                        throw new XmlException("Invalid wsdl:message part. All parts of message in operation  must either contain type or element.");
                    }

                    XmlSchemaElement element = null;
                    if ((element = CodeGenUtils.FindSchemaElement(m_svcDesc, part.Element.Name, part.Element.Namespace)) != null)
                    {
                        schemaDefs.Add((XmlSchemaElement)element);
                        ++elementCount;
                    }
                    else
                    {
                        throw new XmlException("Missing element specified." +
                                               "\n Message name: " + part.Message.Name +
                                               "\n Message part name: " + part.Name +
                                               "\n Type name: " + part.Type.Name +
                                               "\n Type namespace: " + part.Type.Namespace);
                    }
                }
                // This part defines a type
                else if (part.Element.IsEmpty == true && part.Type.IsEmpty == false)
                {
                    // Make sure Element and Type parts are not mixed
                    if (elementCount > 0)
                    {
                        throw new XmlException("Invalid wsdl:message part. All parts of message in operation  must either contain type or element.");
                    }

                    XmlSchemaType type = null;
                    if ((type = CodeGenUtils.FindSchemaType(m_svcDesc, part.Type.Name, part.Type.Namespace)) != null)
                    {
                        schemaDefs.Add((XmlSchemaType)type);
                        ++typeCount;
                    }
                    else
                    {
                        throw new XmlException("Missing type specified. Message name: " +
                                               part.Message.Name + " Message part name: " +
                                               part.Name + " Type name: " + part.Type.Name);
                    }
                }
            }

            if (elementCount == 0 && typeCount == 0)
            {
                return(null);
            }
            else
            {
                return(schemaDefs);
            }
        }
示例#17
0
        /// <summary>
        /// Add an interface method to a service interface.
        /// </summary>
        /// <param name="operation">A sericce operation.</param>
        /// <param name="action">A service action</param>
        /// <param name="codeType">A CodeTypeDeclaration object used to store this interface definition.</param>
        private void AddServiceOperationToInterface(Operation operation, string action, CodeTypeDeclaration codeType)
        {
            // Add method
            CodeMemberMethod codeMethod = new CodeMemberMethod();

            codeMethod.Name = operation.Name;

            // Find request and response element or type name that defines the interface method and return types
            string inputElementName  = null;
            string inputTypeName     = null;
            string outputElementName = null;
            string outputTypeName    = null;

            foreach (Message message in m_svcDesc.Messages)
            {
                if (operation.Messages.Input != null && operation.Messages.Input.Message.Name == message.Name)
                {
                    inputElementName = CodeGenUtils.GetMessageElementName(m_svcDesc, message);
                    inputTypeName    = CodeGenUtils.GetMessageTypeName(m_svcDesc, message);
                }
                else if (operation.Messages.Output != null && operation.Messages.Output.Message.Name == message.Name)
                {
                    outputElementName = CodeGenUtils.GetMessageElementName(m_svcDesc, message);
                    outputTypeName    = CodeGenUtils.GetMessageTypeName(m_svcDesc, message);
                }
            }

            // If this is an event add event (notification) prototype
            if (operation.Messages.Flow == OperationFlow.Notification)
            {
                codeMethod.ReturnType = new CodeTypeReference(typeof(void));
                if (outputTypeName != null)
                {
                    codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(outputTypeName, "resp"));
                }
            }
            // Else add request/response prototype
            else
            {
                if (operation.Messages.Flow != OperationFlow.RequestResponse || outputTypeName == null)
                {
                    codeMethod.ReturnType = new CodeTypeReference(typeof(void));
                }
                else
                {
                    codeMethod.ReturnType = new CodeTypeReference(outputTypeName);
                }

                if (inputTypeName != null)
                {
                    codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(inputTypeName, "req"));
                }
            }

            // Create OperationContract custom attribute
            CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("OperationContract");
            CodeAttributeArgument    codeAttr     = new CodeAttributeArgument("Action", new CodePrimitiveExpression(action));

            codeAttrDecl.Arguments.Add(codeAttr);
            if (operation.Messages.Flow == OperationFlow.OneWay)
            {
                codeAttr = new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true));
                codeAttrDecl.Arguments.Add(codeAttr);
            }
            codeMethod.CustomAttributes.Add(codeAttrDecl);
            codeMethod.Attributes = MemberAttributes.Public;
            codeType.Members.Add(codeMethod);
        }