Contract-first WCF services - still valid? - c#

I am attempting to create a few WCF web services from existing WSDLs. There are a few awesome questions on SO for this, (1, 2, definitely more) but many of these are from 3 years ago, and I end up wondering if the advice is still valid. If it is, how do I finish integrating it into a WCF project in Visual Studio 2010? The questions and linked blog posts are considerably mum about how one configures a .svc to use the converted WSDL after it's been run through svchost.exe (see linked question 1 for details on that), and a blog post linked in the thread suggests there is a way to make Visual Studio create a .svc around a converted WSDL, but I cannot find this anywhere in either the program's interface or the documentation.
So, the question, I suppose, would be: What is the generally recommended way to approach contract-first web service design in Visual Studio 2010/.NET 4.0?

It hasn't changed. You can still generate a service interface and its data contracts using svcutil and a WSDL. Even a client will be generated, though you won't need that.
You can then create a .svc-file, which merely instructs a ServiceHost which class to host, as explained here:
<% #ServiceHost Service="MyNamespace.MyServiceImplementationTypeName" %>
Your implementation of course has to implement the generated service interface.

Related

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

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.

Generate c# classes from wsdl [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want generate C# classes from wsdl url in ASP.NET Core 2.1.
WSDL url is:https://airarabia.isaaviations.com/webservices/services/AAResWebServices?wsdl
I used "Microsoft WCF Web Service Reference Provider" tool to generate C# class and got following error:
Error: No code was generated.
If you were trying to generate a client, this could be because the metadata documents did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assemblies. Verify that you passed all the metadata documents to the tool.
Done.
Any solution will be appreciate.
Short answer
Open a development command prompt and run to generate the proxy classes:
svcutil http://airarabia.isaaviations.com/webservices/services/AAResWebServices?wsdl
Notice that I used http instead of https. The server's certificate causes problems with svcutil. Copy the classes into your project folder.
Add System.ServiceModel.Primitives from NuGet to the project's dependencies. Since ASP.NET Core doesn't use web.config files, you may have to create the bindings yourself when creating the proxy class, eg :
var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
var address = new EndpointAddress("http://airarabia.isaaviations.com/webservices/services/AAResWebServices");
var client = new AAResWebServicesClient((Binding)binding, address);
In the bindings, BasicHttpsBinding is used since no airline will accept unencrypted connections. Sabre requires TLS 1.2 or greater.
Explanation
Airlines and GDSs aren't great at following web interoperability standards. They are big enough that if there are any changes, it's the travel agent that has to accomodate them. Once they specify their standard, they don't care to change it either.
The OTA standard and Sabre's implementation for example were created in 2003 using ebXML, an alternative proposal to SOAP that didn't become a standard. Then they used ebXML over SOAP using mechanisms that didn't become part of the later SOAP standards. When the WS-* standards were created to fix the mess and ensure interoperability, they didn't even bother.
The WSDL you provided is similar to Sabre's. It uses some of OTA's operations like OTA_PING and adds custom ones. Fortunately, it doesn't include any tool-breakers like anonymous inner types.
You could use wsdl.exe to create an ASMX proxy, using the pre-2008 .NET stack. This hasn't been ported to .NET Core as far as I know though. Maybe it's part of the Windows Compatibility pack. After all, it is non-compliant and deprecated 10 years ago. ASMX hasn't had any significant upgrades in ages either. I have run into concurrency issues with deserializers in the past, when using ASXM services eg with Amadeus.
And then, there are those that won't even respect their own XSDs, eg Farelogix. They may return out-of-range values for enumerations and say "well, the XSD is for information purposes only". The wsdl file is clearly marked not for production use
There's no generic solution unfortunately. Here are some options:
wsdl.exe and ASMX are out of the question if you want to use .NET Core. You'll have to switch to the Full framework if you have to use them.
Create WCF individual proxies for each service. The size of the files is a lot smaller and you avoid clashes between types like Airport that are used by multiple services with slight variations or even incompatibilities.
Use Fiddler or another tool to capture the requests and responses. Use these as templates to create plain HTTP GET requests. It's a dirty solution but could prove quicker and ever more reliable if you can't trust the provider's WSDL and XSDs
WARNING
Making the call doesn't mean that you can communicate with the provider. One of the main problems with ebXML over SOAP is that the body is OK but the headers, including those used for authentication are all wrong. This means that one has to create the authentication element
Another issue is that authentication fields are often misused eg using authentication headers we'd consider session tokens. GDSs still use mainframes and those session tokens often map to actual terminal sessions.
This means that one has to create authentication headers manually instead of relying on WCF to generate them. It also means that transactions are stateful - one has to keep track of which session was used for that reservation in order to book it, make sure all previous transactions are complete before starting a new one etc.
Download your WSDL files to local. Then, run the following command:
wsdl.exe /verbose /namespace:Air /out:D:\t\ar /protocol:SOAP /language:CS C:\path\to\wsdl\AAResWebServices_1.wsdl
Change namespace to a namespace of your choice.
WSDL.exe is part of your Windows SDK:
C:\Program Files (x86)\Microsoft SDKs\Windows
Mine was in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin
This generated the classes without any issues. I tested this solution.

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.

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.

How to implement WSDL provided by business partner?

I have been provided to a wsdl file by another business to build webservice so that the other business can connect to service I build using the provided wsdl and xsd files. I am dot net developer using wcf. I want to know where to start having the wsdl and xsd files in hand.
Thanks
Hopefully, the schemas and WSDL are .NET friendly. If you want to use WCF, you can generate your classes using SvcUtil.exe.
svcutil -noconfig -serializer:datacontractserializer -d:../
-namespace:*,MyCompany.Services.ServiceName wsdl.wsdl Messages.xsd Data.xsd
The bad news is that svcutil actually generates the client side proxy so you have to manually go and remove the client and channel classes.
For a full description of this approach see Schema-based Development with Windows Communication Foundation.
In the article, they also talk about a Visual Studio add-in, WSCF.blue, that allows you to do Data contract generation (among other contract first development tasks).
You can use the .net wsdl tool and xsd tool to auto generate your classes.
The quick and lazy way of doing it is simply to use add reference in VS (assuming .net3.5 +) or add web reference for .net 2; and allow VS to do the work.
http://www.eggheadcafe.com/tutorials/aspnet/a1647f10-9aa4-4b0c-bbd9-dfa51a9fab8e/adding-wcf-service-refere.aspx
As ( http://andrewtokeley.net/archive/2008/07/10/the-difference-between-ldquoadd-web-referencerdquo-and-ldquoadd-service-referencerdquo.aspx ) says its basically a wrapper for the functions the Tuzo and Ben added.
Makes life easier though and with the 'Add service wrapper' you can use the advanced settings to automatically generate ASync classes & Data Contracts.

Categories

Resources