Consumr et appeler des services Web SOAP au moment de l’exécution – Client de service Web dynamic à partir d’un fichier WSDL

Exigence:

  1. Le client doit donner le WSDL du service Web SOAP au moment de l’exécution, c’est-à-dire choisir le fichier WSDL à partir d’un emplacement de partage de fichier.
  2. Consumz le WSDL, appelez la méthode choisie par le client sur l’interface utilisateur et gérez la réponse.

Je ne peux pas utiliser MetadataExchangeClient car le WSDL ne sera pas hébergé.

La mise en oeuvre:

var serviceDescription = ServiceDescription.Read(@"C:\Contacts.WSDL"); var metadataSection = new MetadataSection { Dialect = MetadataSection.ServiceDescriptionDialect, Identifier = serviceDescription.TargetNamespace, Metadata = serviceDescription }; var metadataSections = new List {metadataSection}; var metadatSet = new MetadataSet(metadataSections); var wsdlImporter = new WsdlImporter(metadatSet); var services = wsdlImporter.ImportAllEndpoints(); 

Barrages routiers:

  1. Le code ci-dessus n’a pas pu extraire les points de terminaison du service. J’ai donc dû créer manuellement un sharepoint terminaison de service.
  2. Je ne pouvais pas lister toutes les méthodes contenues dans le WSDL ci-dessus et ses entrées / sorties associées dans l’étape (à utiliser dans la variable operationName et operationParameters ci-dessous)
 object retVal = instance.GetType().GetMethod(operationName) .Invoke(instance, operationParameters); // Invoke 

J’ai essayé de coder en dur le nom de l’opération, analysé manuellement à partir du WSDL, mais les parameters ont échoué. Il attend un type complexe contenant la hiérarchie comme ci-dessous:

ContactInput -> ListOfContacts -> Contact -> Prénom, Nom

Prochaines étapes:

Si quelqu’un peut m’aider à réparer les obstacles, je peux poursuivre avec l’approche ci-dessus.

Sinon, je dois commencer à étudier l’utilisation de svcutil.exe au moment de l’exécution

Merci Dev

Il existe une solution pour cela décrite dans cet article:

Générer un code proxy pour un service Web de manière dynamic

Bien que vous puissiez ouvrir ce lien et le lire, j’inclus le code ici, au cas où ce lien mourrait à tout moment:

Cette méthode renvoie la liste des opérations exposées par le service Web. J’ai utilisé ServiceDescription pour y parvenir car je ne pouvais pas refléter uniquement les noms de méthodes Web à partir de l’assmebly généré. Avec les noms d’opération disponibles, il ne rest plus qu’à connaître les parameters d’entrée et de retour pour chaque méthode.

 public ssortingng[] GenerateProxyAssembly() { //create a WebRequest object and fetch the WSDL file for the web service HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.uri); request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); //read the downloaded WSDL file ServiceDescription desc = ServiceDescription.Read(stream); //find out the number of operations exposed by the web service //store the name of the operations inside the ssortingng array //iterating only through the first binding exposed as //the rest of the bindings will have the same number int i = 0; Binding binding = desc.Bindings[0]; OperationBindingCollection opColl = binding.Operations; foreach (OperationBinding operation in opColl) { listOfOperations[i++] = operation.Name; } //initializing a ServiceDescriptionImporter object ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //set the protocol to SOAP 1.1 importer.ProtocolName = "Soap12"; //setting the Style to Client in order to generate client proxy code importer.Style = ServiceDescriptionImportStyle.Client; //adding the ServiceDescription to the Importer object importer.AddServiceDescription(desc, null, null); importer.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync; //Initialize the CODE DOM tree in which we will import the //ServiceDescriptionImporter CodeNamespace nm = new CodeNamespace(); CodeComstackUnit unit = new CodeComstackUnit(); unit.Namespaces.Add(nm); //generating the client proxy code ServiceDescriptionImportWarnings warnings = importer.Import(nm, unit); if (warnings == 0) { //set the CodeDOMProvider to C# to generate the code in C# System.IO.SsortingngWriter sw = new System.IO.SsortingngWriter(); CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); provider.GenerateCodeFromComstackUnit(unit, sw, new CodeGeneratorOptions()); //creating TempFileCollection //the path of the temp folder is hardcoded TempFileCollection coll = new TempFileCollection(@"C:\wmpub\tempFiles"); coll.KeepFiles = false; //setting the ComstackrParameters for the temporary assembly ssortingng[] refAssembly = { "System.dll", "System.Data.dll", "System.Web.Services.dll", "System.Xml.dll" }; ComstackrParameters param = new ComstackrParameters(refAssembly); param.GenerateInMemory = true; param.TreatWarningsAsErrors = false; param.OutputAssembly = "WebServiceReflector.dll"; param.TempFiles = coll; //comstack the generated code into an assembly //ComstackrResults results = provider.ComstackAssemblyFromDom(param, unitArr); ComstackrResults results = provider.ComstackAssemblyFromSource(param, sw.ToSsortingng()); this.assem = results.ComstackdAssembly; } //return the list of operations exposed by the web service return listOfOperations; } 

Cette méthode renvoie les parameters d’entrée dans la liste ParameterInfo []. Pour obtenir le paramètre de sortie, il suffit de remplacer l’appel de GetParamters () sur la classe MethodInfo par la propriété ReturnParameter et de l’insérer dans une nouvelle méthode. Placez ces 3 méthodes dans une DLL et ajoutez-y une référence à partir de n’importe quelle application cliente. C’est tout. Il suffit de fournir l’URL et d’utiliser le service Web, n’importe quel service Web. Vous n’avez pas à suivre la procédure de création d’un fichier proxy chaque fois que vous souhaitez utiliser un nouveau service Web.

 public ParameterInfo[] ReturnInputParameters(ssortingng methodName) { //create an instance of the web service type //////////////to do///////////////////////// //get the name of the web service dynamically from the wsdl Object o = this.assem.CreateInstance("Service"); Type service = o.GetType(); ParameterInfo[] paramArr = null; //get the list of all public methods available in the generated //assembly MethodInfo[] infoArr = service.GetMethods(); foreach (MethodInfo info in infoArr) { //get the input parameter information for the //required web method if (methodName.Equals(info.Name)) { paramArr = info.GetParameters(); } } return paramArr; }