Which one of this two ways of using wcf service is better? why?
Generating proxy from Service Reference
using ChannelFactory
ex.
ChannelFactory<IMyContract> factory = new ChannelFactory<IMyContract>();
IMyContract proxy1 = factory.CreateChannel();
proxy1.MyMethod();
It is a bit boring to call wcf service like so
IMyContract proxy1 = null;
try
{
proxy1 = factory.CreateChannel();
proxy1.MyMethod();
((ICommunicationObject)proxy1).Close();
}
catch
{
((ICommunicationObject)proxy1).Abort();
}
Should we repeat this snippet for every proxy call? Or Is there generic way to create a wrapper class for closing and aborting proxies?
Is writing class like this ServiceExecution.Execute(proxy=>proxy.MyMethod()); which creates proxy, and closes or aborts it good way to do that?
Here is an MSDN post, that recomends not to use generated proxies in .Net 3 because it creates ChanelFactory each time, .Net 3.5 ChanelFactory is cached.
But personally I prefer to use ChanelFactory myself, generated code is always a pain even after partials come out
In first case when you use VS to add Service Reference it generates all the code for you including ServiceContrcats and DataContracts.
But when you use ChannelFactory you must have service contracts and etc on client side already.
I suggest using approach 1.
I've found this blog with an example including source code that also explains how to properly handle the connection (closing, aborting, etc.). The blog also contains links for more details at MSDN.
Manually creating the service proxies from a running service might be a good alternative. The tool svcutil is what Visual Studio uses under the hood when adding a service reference. Using this, you can generate the proxy class in a common location, and then link to it in each project you require, and also gain better control over your proxy classes.
For example, to generate a proxy for a service called TestService running locally on port 8000, you would run the following in the Visual Studio command prompt, generating a proxy class TestServiceProxy.cs in the proxies directory.
cd "C:\src\proxies"
svcutil /noLogo /out:TestServiceProxy http://localhost:8000/TestService
There are some other useful parameters for the tool, for example:
Add /n:*,WcfServices.TestService will specify a namespace for the proxy class.
Add /config:TestServiceProxy.config and svcutil will generate a sample configuration file for using TestService including endpoints, bindings etc.
Add /r:"Common.dll" and the proxy class emitted by svcutil will not have definitions for types used by the service, but defined in the assembly Common.dll.
Use svcutil /? for more information.
Related
I am consuming a webservice from a Java server. The webservice provides me with some methods that need. Up till now I have been using the method where I added the reference of the webservice in the project explorer, typed the address of the webservice and compiled it. But now I need it to pick up the address of the service at runtime from an xml file or something! is that possible?
There is Url property in generated proxy object that you can set at runtime. Covered in Creating the Web Service Proxy article on MSDN.
Sample from the article (shows how to also set credentials, you may also need to set Proxy):
var rs = new ReportExecutionService();
rs.Url = "http://<Server Name>/reportserver/reportexecution2005.asmx?wsdl";
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
Note that above answer is for case when you don't know exact Url of server till runtime, but you have WSDL/sample server available at design time and able to generate proxy via add web service in VS (or manually).
Alternatively you can call service via other classes implementing "HTTP GET" like HttpClient and configure anything you want, but will need to do your own parsing of results.
The ONLY argument I can see for SOAP WCF over REST (json) wcf is the fact that once my service is created I can add a a reference in visual studio and I get a load of strongly typed classes ready for me and a client class that I can call all my webmethod through. It even sets up the web.config as far as I remember.
However when I expose a REST (json) service I still get a WSDL. So Im wondering is there still a way to build my references automatically?
Not using WCF tools. Unlike with SOAP (which has an established protocol for describing services - WSDL), REST doesn't. WADL is one such protocol, but it isn't too widespread and WCF does not support it. You still get a WSDL, because WCF will describe everything it can from the service. However, the WSDL won't have a <wsdl:port> element, which would describe the REST endpoint, which is why you get the WSDL, but cannot generate a reference to it.
The post at http://blogs.msdn.com/b/carlosfigueira/archive/2012/03/26/mixing-add-service-reference-and-wcf-web-http-a-k-a-rest-endpoint-does-not-work.aspx has a lot more info on this issue.
Very old question, newer answer.
today using openapi (swagger) I can achieve this by using swagger inspector doing samples i can document my rest services as well as create a spec yml/json file allowing for validations and acceptance criteria as well as automated clients for java,python,c#,ruby,javascript and others I'm sure
I would like top elaborate:
Although it is true you cannot get a WSDL add service reference with a JSON REST WCF service, what I do is create two met data hooks:
is the operations returning JSON
is a single XML op returning a class wrapper which includes all the service classes I allow, I call it Discover:
i.e.
public class Discover
{
public Manager Manager {get;}
public Employee Emp {get;}
....
}
[OperationContract]
public Discover DiscoverDTOs()
You can, indirectly. While the client generated by Visual Studio won't work, that client implements an interface, also generated, that you can use like this:
WebChannelFactory<IService> factory = new WebChannelFactory<IService>(new Uri(endpointAddress));
IService proxy = factory.CreateChannel();
int result = proxy.Operation(1, 2, 3);
WebChannelFactory has another overload which accepts a WebHttpBinding, you can configure based on the service configuration, or you can make this configuration manually in your app.config file.
Environment :
Visual Studio 2010 Professional
.NET Framework 4
C#
Added Service Reference using the following WSDL : https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
Problem 1 : When compiled simply like this, get a bunch of errors from the Reference.cs file. Looks like namespace errors. It mentions that it cannot find the Service Reference Namespace in my project's Namespace. Therefore, I went into the Reference.cs file and whereever I got this error, I removed the project's namespace before the method names, and now it compiles.
Finally getting access to all classes.
Created and populated DoDirectPaymentReq and CustomSecurityHeader objects with the required properties.
Created an instance of PayPalAPIAAInterfaceClient class, which contains the method DoDirectPayment which takes in the arguments of type CustomSecurityHeader and DoDirectPaymentReq. Looks like this :
using (var client = new **PayPalAPIAAInterfaceClient**())
{
var credentials = new CustomSecurityHeaderType
{
Credentials = new UserIdPasswordType
{
Username = "xxxxxxxx#xxxxxx.com",
Password = "xxxxxxx",
Signature = "jksadfuhasfweakjhasf"
}
};
_doDirectPaymentResponseType = client.DoDirectPayment(ref credentials, _doDirectPaymentReq);
}
Problem 2 : After writing a TestMethod for the method which contains the above code, I get the error as follows :
System.InvalidOperationException: Could not find default endpoint element that references contract 'Paypal.PayPalAPIAAInterface' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
at System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(ServiceEndpoint serviceEndpoint, String configurationName)
at System.ServiceModel.ChannelFactory.ApplyConfiguration(String configurationName, Configuration configuration)
at System.ServiceModel.ChannelFactory.ApplyConfiguration(String configurationName)
at System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address)
at System.ServiceModel.ChannelFactory`1..ctor(String endpointConfigurationName, EndpointAddress remoteAddress)
at System.ServiceModel.EndpointTrait`1.CreateSimplexFactory()
at System.ServiceModel.ClientBase`1.CreateChannelFactoryRef(EndpointTrait`1 endpointTrait)
at System.ServiceModel.ClientBase`1.InitializeChannelFactoryRef()
at System.ServiceModel.ClientBase`1..ctor()
at PaymentEngine.Paypal.PayPalAPIAAInterfaceClient..ctor() in Reference.cs: line 30063
Therefore, so far I have not been able to make a successful transaction using PayPal SOAP protocol via using WSDL in C#.
I was under the impression that this is very simple. Simply Add Service Reference and utilize the Classes with their properties and methods created in the proxy from WSDL.
Where am I going wrong ?
Am I using the wrong WSDL ? I'd like to test against Sandbox first and then go Live.
If I am right with the WSDL, looks like the class PayPalAPIAAInterfaceClient doesn't know its endpoint, which I don't know if I am suppose to set manually or not since its already there in the WSDL definition at the end (check it out). I think the class itself should know which endpoint to call depending on whether I am using Signature or Certificate to populate CustomSecurityHeaderType.
But how does the PayPalAPIAAInterfaceClient class know whether I am trying to call into the Sandbox (testing) or it is a live transaction ?
PayPal used to have two different WSDLs for Sandbox and for Live. They can be found here :
->https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_soap_PayPalSOAPAPIArchitecture
After speaking to their support I was asked to use the following WSDL for both Sandbox and Live:
->https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
But how do I tell the PayPalAPIAAInterfaceClient class when it is suppose to perform Live or Sandbox tests. And also to which end point to use depending on my method of SOAP and Signature. The endpoints from PayPal are mentioned here :
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_endpoints
HELP !
You have a few problems here, but none should be too painful to resolve. First of all, when I add a Service Reference to the WSDL you link at the top of your post I don't have any of the problems with namespaces that you describe. It could be that your own namespaces/references are conflicting somehow with the auto-generated terms, or perhaps that you selected some strange option during the add reference process? A delete-and-re-add might solve the problem, or I guess you can just ignore it since you've already worked around it. (It is kind of a hassle to edit auto-generated code, however, so you should plan on a fix eventually.)
To resolve the InvalidOperationException, you probably just need to specify one of the endpoints that Visual Studio has automatically added to your app.config file. You should have something like this in your config file:
<system.serviceModel>
<client>
<endpoint name="PayPalAPI" ... />
<endpoint name="PayPalAPIAA" ... />
</client>
</system.serviceModel>
You can pass the name of the endpoint you want to the constructor of the proxy class. There are other options to solve this problem, but just specifying an endpoint is easy and clean. (Note: if you don't have this section in your config file, then something went wrong during the Add Service Reference phase. Again I would just suggest resetting your project and re-adding the reference.)
Finally, you don't want to use a using block when you make use of the proxy class in spite of it being IDisposable. Basically, there's a design bug in WCF.
I had the same problem, because I was doing unit testing.
You have to copy the application.config file to the test project, otherwise it won't find the WCF config.
I want to invoke a web service in my C# client application.
I want to be able to bind to this web service dynamically.
I am using the following code for dynamically calling a web service:
class Program
{
interface IInterface
static void Main(string[] args)
{
BasicHttpBinding bin = new BasicHttpBinding();
EndpointAddress endPoint = new EndpointAddress("http://api.wxbug.net/webservice-v1.asmx");
IInterface myInterface = ChannelFactory<IInterface>.CreateChannel(bin,endPoint);
}
}
My question is, how to I generate a ServiceContract Interface for my web service? Is there any tool to autogenerate this? This is because my target web service is quite complex with lots of exposed methods, and I dont want to write the Service Contract Interfaces all my hand.
The svcutil tool is what you use for this. This is also what gets run behind the scenes when you select "Add Service Reference" in Visual Studio.
If you are working in Visual Studio, then "Add Service Reference" will probably be easiest, as it should automatically start up your service in order to get the metadata.
If you can't or don't want to use Visual Studio, you'll need to make sure your service is up and running, and then use svcutil.exe (if you open a .Net Command Prompt it will be in the path variable). Using svcutil is sometimes necessary if you don't want to generate/overwrite the client configuration, or if you want to specify a specific class for the proxy to go in. There's also a handy switch in svcutil which will generate generic collections in the proxy, rather than defaulting to arrays.
You can to right click your project and to select Add Service Reference; it'll grab your web service WSDL and to create your proxy classes.
I have two websites, both using .Net framework 3.5. One website is hosting a soap web service and the other is referencing this service.
I'm having some unexpected happenings with my web method signatures. I have a simple method in my web service with a signature such as:
[WebMethod]
public string[] HelloWorld()
{
return new[] { "Hello World" };
}
But when I reference this web service using the 'Add Service Reference' feature in VS2008, with configuration set to "Always generate message contracts" (although when i check the 'reuse types in referenced assemblies', i seem to have the same issue), the signature seems to be changed by the auto generated proxy objects to the following:
HelloWorldResponse HelloWorld(HelloWorldRequest request)
I've tried to look this up on the net, but having trouble finding something that will simply explain to me why this is happening, and whether I can/should try to work around it?
I also have this question:
How does one determine whether they should choose the service reference configuration option to "reuse types in referenced assemblies" and "always generated message contracts"?
The message-contracts option might have this effect; the purpose here being to allow fine-grained control over the underlying request. Ultimately, what you are sending (behind the scenes) is a request payload.
The reuse-types option is more typically used with objects (not things like string[]) - and means that if you have a 100% matching Customer (say) class locally, it can re-use that for the web-service rather than generating a proxy type.
Additionally, note that you aren't actually consuming a WCF service ([WebMethod] is the older web-service style). As such you may have better results with a "Web Reference"; when adding the service, hit "Advanced", then "Add Web Reference...". This uses the older UI and wsdl.exe to generate code intended for [WebMethod] (asmx), rather than WCF (svc).
Of course, rather than hosting a [WebMethod], you could (since the server is also 3.5) host a WCF service; this may make things easier.
A final point of WCF; if you really want the same contract at client and server, you can use either assembly or class sharing to use the very same types at both end. This is not supported for [WebMethod], though.