How to Call Web Service Using SOAP Request with example? [duplicate] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
Background:
I am creating a webservices site which will provide many types of simple services over SOAP and possibly other protocols too. The goal is to make it easy to do for example conversions, RSS parsing, spam checks and many other types of work. The site will be targeted mostly at beginner developers.
My Problem:
I have never developed any C#, or .NET for that matter. I did hack some VB6 many years ago but that's it. Now I need some examples of doing RPC calls over SOAP in C#. I have tried to search the web, and Stack Overflow, to find this but didn't find many resources, and I have no idea how to rank the resources (which are old? which are incorrect? etc).
I have created a simple example service, which is called like this in PHP:
<?php
$client = new SoapClient('http://webservi.se/year'); //URL to the WSDL
echo $client->getCurrentYear(); //This method returns an integer, called "year"
?>
I now want to call this method as easily as possible in C#. All references and examples are very welcome. Where do I begin? Which classes/modules/whatever can I utilize?
The solution does not have to involve SOAP at all if there are better communication frameworks (the back end is meant to be extensible), but note that the server side is implemented in PHP on Unix so proprietary solutions from Microsoft are out of the question on the server side.
Note that I need this so I can write documentation possible for J. Random Web Developer to follow (even if they are on shared web hosting). I therefore think the best approach should be to do this in code only, but even other ways of doing this are of course welcome.

Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
Adding a service reference step by step
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
Open your project (or create a new one) in visual studio
Right click on the project (on the project and not the solution) in Solution Explorer and click Add Service Reference
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference (or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference, the name of proxy class is CalculatorSoapClient. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();

I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.
That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):
Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.
</rant> :)

If you can get it to run in a browser then something as simple as this would work
var webRequest = WebRequest.Create(#"http://webservi.se/year/getCurrentYear");
using (var response = webRequest.GetResponse())
{
using (var rd = new StreamReader(response.GetResponseStream()))
{
var soapResult = rd.ReadToEnd();
}
}

Take a look at "using WCF Services with PHP". It explains the basics of what you need.
As a theory summary:
WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.
The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.
You have the first part of the article here, explaining how to create a very basic WCF Service.
More resources:
Using WCF with PHP5.
Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

You're looking in the wrong place. You should look up Windows Communication Framework.
WCF is used both on the client and on the server.

Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.
Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.
There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.
Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

Related

Alternative to HttpListener and Griffin.WebServer in C#

In short, i am looking for the best mehod to provide a REST or SOAP API Server in a .Net Framework application (e.g. windows forms) - without admin rights in some cases
What is currently the best way of providing a web based REST or SOAP API in a possible portable csharp application?
Basically i need something that supports the basic http standards out of the box (e.g. Expect: 100-continue and others) and at the same time is able to instanciate the classes of my csharp program directly (perfomrance and ease of use reasons).
The microsoft way is to either use IIS and possibly ASP or go for httplistener. IIS could never be run in a portable way and requires lots of installation procedure/system administration based work. httlistener on the other hand is not even close to being a webserver, i would need to implement all the standard webserver commands on my own.
I am looking around for this topic since years now, one example is this question [old question] Alternative to HttpListener?
Unfortunately this one links to a discontinued project.
Any ideas?
[EDIT] The question targets not only C# but also .NET Framework 2-4.5. The result should be useable in e.g. Windows Form, Windows Service and Commandline applications.
Currently i am using a skeleton Webserver based on HTTPListener and therefore i need to implement all the Parsing of a request, formatting of answers and reacting to special http commands on my own (which seems to be a never ending task): https://www.codeproject.com/Articles/17071/Sample-HTTP-Server-Skeleton-in-C
You could try Griffin web server. I've used it for embedding a web server into applications to host a simple web interface, file hosting, and to provide a REST API for my application.
The biggest advantage for me versus the embedio project (which is excellent) is that it doesn't require admin privileges to run. Looks like no SOAP integration out of the box though.
You should be able to do what you want using .NET Core. You can fairly easily build a self-hosted API using it that's independent of IIS. Tutorials should be easy to find, and here is a Microsoft example.
As ilikesleeping suggested you could use dotnet core, but there are complications in making it work as a service.
I suggest you to use Microsoft OWIN framework. It's really simple and straightforward way of building restful applications. It can work fine as Console or a service, and of course in Console mkode you can display a Form should you wish to.
Here are some links to get kickstarted:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api | https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/getting-started-with-owin-and-katana | https://blog.decayingcode.com/post/Creating-a-Self-Hosted-OWIN-Application/ |
https://weblogs.asp.net/fredriknormen/creating-a-simple-rest-like-service-with-owin-open-web-server-interface
EDIT:
...and here's the topic on how to have a middleware that hosts SOAP endpoint over OWIN: Any way to get OWIN to host a SOAP service?
I am the author of this question. Just wanted to make obvious for future readers what i learned here:
Most interesting about this question is that it is a "shopping" question. The accepted answer cannot be based on facts but on subjective feeling only. Most of the suggested methods hit the described usecase.
This is the reason why some users did not want to write an answer but instead put their suggestions in a comment instead. Strange but this is how SO works. We just prefer scientifically correct answers here!
By te way, this was my first "bounty" question. I am active SO user since about 3 weeks. (passive for years, like most people)

Making a software for controlling a hardware device network-capable in .Net/C#

I am responsible for developing the software for a printer-like device, for which I am using C#/.Net and WPF. We now have the necessity for making this software network-capable, so that the device can be remote-controlled over a local network.
The idea I currently have, is to be implement some way of calling the API-functions of our software over the network. This could be done by a client-side DLL, which sends the commands for the API and receives their responses as well as any events, that the device-software issues.
To this date I have only worked a little with socket-based communication using TCP/IP, where I explicitly sent strings over the network and received them on the other side. I did this completely synchronously. However for the new implementation I will need asynchronous calls to the API to query state, issue events, etc. and it seems like it would require considerable effort to implement this using socket-based communication (am I wrong?). I will have to avoid too much custom implementation, since I am under a time-constraint for the implementation.
In my search I came accross the possibility of using SOAP in ASP.Net, which from this CodeProject post, seems to be what I am looking for and does not seem to be too complicate to implement. However in my Visual Studio 2015 installation I am unable to find the project-type they are using there, which is a "ASP.Net Web Service".
My question is now:
Given my choice of technologies (.Net), would this be the most effective way for achieving, what I have in mind? Is it still possible to do this in Visual Studio 2015?
Update:
As always I found one of the questions afterwards: Here is an explanation of how to create an "ASP.Net Web Service" in Visual Studio 2015, which I have tested to work. Leaves the question, of whether this is the best way to go for what I need.
I think that you would have better luck using web api. Calling a REST based api is a lighter load on the network and is generally easier to set up. It is also easier to call from non-Microsoft based clients and usually requires less coding to get started.
Here is a good tutorial on creating a RESTful web api using .Net Core. If you have a PluralSight subscription, they have a number of tutorials on Web Api. If you don't have a subscription, it is well worth the money.
Web Api and WCF are two completely different frameworks. WCF uses SOAP, which is XML based, meaning that the number of bytes needed to send information is much larger than a RESTful service in Web Api. It is much easier to write and deploy a Web Api application and client than it is to write the equivalent in WCF.

Expose 3rd party interface (over WCF) to Silverlight

I searched a lot, apologies if I missed something obvious. And thanks for reading the looong text below.
I have a 3rd party (read: No way to access/change the source) application here. It consists of a server (Windows service) and an API, that talks to the server via remoting.
For several reasons I'd like to expose this API over WCF (see subject: One reason is a WCF client).
The problem is, the API is
unchangeable (follows 3rd party rule)
using no WCF itself (it is serializable/MarshalByRef where necessary for Remoting)
using lots of interfaces and internal implementation classes
Following 1 I cannot use the (quite intrusive) WCF attributes myself.
Following 2 the API itself can be used "over the wire" (they support remoting via TCP and HTTP), but remoting is not good enough for me.
Following 3 I have mostly interfaces (which WCF won't handle well, cannot (de-)serialize). The implementation classes could be sent over, but - I cannot access them.
The general usage for this API is based on a single interface (and its members/properties), so the typical usage is like
var entryPoint = new ApiClientEntryPoint();
entryPoint.SomeMethodCall();
entryPoint.PropertyExposingAnInterface.SomeOtherMethodCall();
and so on.
What I'd really like to do is generate (with as little effort/code as possible) a proxy (not in the typical WCF sense) that I expose via WCF and that serializes this hierarchy mapping every call/property on the client to the real thing on the server.
The closest I've come so far is stumbling upon this project, but I wonder if there are more/other tools available that take a medium to large part of this work off my shoulder.
If there are any general other advices, better approaches to wrap something preexisting and unchangable into WCF, please share.
My advice is to use a facade pattern. Create a new WCF service that is specific to your usage and wrap the 3rd party service. Clients would talk to your service and you would talk to the 3rd party. But clients would not talk to the 3rd party directly.
This would work in most but not all scenarios. I'm not sure of your particular scenario so YMMV.
BTW you can look at WCF RIA Services which is good for exposing services to Silverlight where you can avoid doing a lot of the hand coding of service stuff. But again depending on your particular scenario it might not be the best way to go.
Edit:
It's now clear that the API is too big and/or the usage patterns of the clients are too varied in order to effectively use a facade. The only other thing I can suggest is to look at using a code generation tool. Use reflection (assuming it is a .NET API?) to pull apart the API and then codegen new services using the details you gathered. You could look at the T4 templates built into Visual Studio or you could look at a more "robust" tool such as CodeSmith. But I'm guessing this would be some painful code to write. I'm not aware of an automated solution for this.
Is the API well documented? If so, is the documentation in a parseable format such as XML or well-structured HTML? In that case you might be able to codegen from the documentation as opposed to reflecting through the code. This might be quicker depending on the particulars.
Okay, hair brained scheme #1 on my side:
Use Visual Studio Refactor menu to "extract interface" on 'ApiClientEntryPoint'.
Create a new WCF service which implements the above Interface and get VS to generate the method stubs for you.
'For PropertyExposingAnInterface.SomeOtherMethodCall' You will have to flatten the interfaces as there is no concept of a "nested" service operation.
Your only other option will be to use T4 code gen ,which will probably take longer than the above idea.

Is Python good for writing standard, compatible and complete SOAP web services?

I have used few python soap libraries (SOAPpy, soaplib and Twisted wrapper around SOAPpy) to write my soap web service.
When I used python clients (SOAPpy.SOAPProxy and SUDS), I was able to communicate with my web service (returning simple and complex type objects).
But, when I tried with C# ASP.net, I got many issues. I came over returning simple types (int, string, double, boolean) issue with some hack into SOAPpy library. But, I am still struggling with returning ComplexTypes from SOAPpy.
I could not find any complete, compatible alternative python library for writing my web service.
Main Question: Any suggestions/examples for dot net compatible complex type return from python web service would be highly appreciated.
Note: I had to hack SOAPpy quite a bit to make it working in first place. And, I had to handwrite wsdl file in case of SOAPpy.
In my personal opinion, the compatibility of Python SOAP libraries with other platforms is not good.
I think that there are two issues here:
First, the compatibility of web services among web service stacks is an aspiration rather than reality. For example, look at this question to see how to use web services between Java and WCF.
That being said, the concept of WSDL which is largely compile time typing is not in line with Python's original philosophy, so less effort was put into it.
I haven't worked with web services for over a year now so may be things have changed. But the advice is the same as in the previous question:
Start with the WSDL writing if you are using more than one language/library.
As copied from the other question, "start with XSD, but confine yourself to mainstream types. Primitives, complextypes composed of primitives, arrays of same."
In the end I settled on using suds for Python web clients, after experimenting with it and soappy and zsi. That was after some time using a C based library (gsoap) and linking to it from Python.
I was never satisfied with server implementations in Python, so I used to build Python servers and connect to them from another library which can export SOAP services (in my case Java or C, you will probably use C#). The connection is usually a much simpler protocol.
That being said, if you start with WSDL you are likely to get good results using soaplib or may be zsi. But I am afraid there is almost no way around building your types slowly while checking for compatibility.

SOAP client in .NET - references or examples? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
Background:
I am creating a webservices site which will provide many types of simple services over SOAP and possibly other protocols too. The goal is to make it easy to do for example conversions, RSS parsing, spam checks and many other types of work. The site will be targeted mostly at beginner developers.
My Problem:
I have never developed any C#, or .NET for that matter. I did hack some VB6 many years ago but that's it. Now I need some examples of doing RPC calls over SOAP in C#. I have tried to search the web, and Stack Overflow, to find this but didn't find many resources, and I have no idea how to rank the resources (which are old? which are incorrect? etc).
I have created a simple example service, which is called like this in PHP:
<?php
$client = new SoapClient('http://webservi.se/year'); //URL to the WSDL
echo $client->getCurrentYear(); //This method returns an integer, called "year"
?>
I now want to call this method as easily as possible in C#. All references and examples are very welcome. Where do I begin? Which classes/modules/whatever can I utilize?
The solution does not have to involve SOAP at all if there are better communication frameworks (the back end is meant to be extensible), but note that the server side is implemented in PHP on Unix so proprietary solutions from Microsoft are out of the question on the server side.
Note that I need this so I can write documentation possible for J. Random Web Developer to follow (even if they are on shared web hosting). I therefore think the best approach should be to do this in code only, but even other ways of doing this are of course welcome.
Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
Adding a service reference step by step
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
Open your project (or create a new one) in visual studio
Right click on the project (on the project and not the solution) in Solution Explorer and click Add Service Reference
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference (or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference, the name of proxy class is CalculatorSoapClient. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();
I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.
That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):
Go ahead and do code-first to create your initial WSDL. Then, delete your code and re-generate the server class(es) from the WSDL. Almost every platform has a tool for this. This will show you what odd habits your particular platform has, and you can begin tweaking the WSDL to be simpler and more straightforward. Tweak, re-gen, repeat. You'll learn a lot this way, and it's portable knowledge.
Stick to plain old language classes (POCO, POJO, etc.) for complex types. Do NOT use platform-specific constructs like List<> or DataTable. Even PHP associative arrays will appear to work but fail in ways that are difficult to debug across platforms.
Stick to basic data types: bool, int, float, string, date(Time), and arrays. Odds are, the more particular you get about a data type, the less agile you'll be to new requirements over time. You do NOT want to change your WSDL if you can avoid it.
One exception to the data types above - give yourself a NameValuePair mechanism of some kind. You wouldn't believe how many times a list of these things will save your bacon in terms of flexibility.
Set a real namespace for your WSDL. It's not hard, but you might not believe how many web services I've seen in namespace "http://www.tempuri.org". Also, use a URN ("urn:com-myweb-servicename-v1", not a URL-based namespace ("http://servicename.myweb.com/v1". It's not a website, it's an abstract set of characters that defines a logical grouping. I've probably had a dozen people call me for support and say they went to the "website" and it didn't work.
</rant> :)
If you can get it to run in a browser then something as simple as this would work
var webRequest = WebRequest.Create(#"http://webservi.se/year/getCurrentYear");
using (var response = webRequest.GetResponse())
{
using (var rd = new StreamReader(response.GetResponseStream()))
{
var soapResult = rd.ReadToEnd();
}
}
Take a look at "using WCF Services with PHP". It explains the basics of what you need.
As a theory summary:
WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.
The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.
You have the first part of the article here, explaining how to create a very basic WCF Service.
More resources:
Using WCF with PHP5.
Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.
You're looking in the wrong place. You should look up Windows Communication Framework.
WCF is used both on the client and on the server.
Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.
Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.
There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.
Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

Categories

Resources