Accessing .NET WCF services from Android - wcf

I have a .NET WCF service (not a web service) with many methods, some accepting and returning complex data types. I use these services from my Windows Phone 7 apps. It all works great and it's easy.
Now I'm evaluating the feasibility of porting some of my apps to Android, but I can't figure out how to invoke my WCF services from an Android client.
I have a working example I found in Invoke webservices from Android.
But this looks to be accessing a "Web Service", not a WCF Service.
My service is at http://www.deanblakely.com/Service2.svc, and it contains a simple method named "SimpleTest" that just returns the string "Alive".
Using the code in the linked article, I put http://www.deanblakely.com/Service2.svc in SOAP_ADDRESS and SimpleTest in OPERATION_NAME. But I have no idea what to put in SOAP_ACTION and WSDL_TARGET_NAMESPACE. I don't even know if this approach is valid.
In .NET, Visual Studio builds us a "Service Reference" and everything just works.
I also don't understand the following two lines of code...
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
With WCF services, the call is async so we make the call to SimpleTestAsync and leave a callback for the async return. These two lines of code appear to be synchronous, no?

When communicating with WCF services from a non-Windows client, you are basically treating it as an XML Web Service. If you configure your WCF service to use a basicHttp binding, it will act just like any other web service, as far as Java is concerned.
Normally, to call a WCF service from Java, you use wsimport to create a custom set of proxy and data classes, similar to the way a service reference works. Android doesn't have all the libraries needed for those classes, but I did find this URL:
http://code.google.com/p/androidclientgenerator-wsimport/
That is a proxy class generator specifically for Android. Instead of using the code on that web page, you may want to download this proxy generator; you simply have to pass it the URL to your service's WSDL page and it will create typed Java classes for everything. If you have complex types being passed back and forth, this is probably a much better option.
However, if you want to continue with the sample code, you'll need to fill in those variables you've identified. The variables are just the typical parameters for a SOAP envelope. These are defined in the WSDL for your service, and are primarily based on the namespace that you have defined for your service. (They are largely independent of the actual URL that your service lives at, with one exception). You specify the namespace in the WCF service contract:
[ServiceContract(Namespace = "http://namespaces.deanblakely.com/wcf")]
Note that the namespace URL doesn't need to point to a real resource, though frequently they do. It doesn't even need to be a URL (I often use urns); it just needs to be a unique string of characters. For now lets assume you assigned the above namespace to your service.
The WSDL_TARGET_NAMESPACE is just the namespace, exactly as above. The OPERATION_NAME is the name of the method you want to call, for example SimpleTest. The SOAP_ACTION is the combination of namespace an operation; in your case that would be http://namespaces.deanblakely.com/wcf/SimpleTest. In your WSDL you would see this described in an operation tag:
<wsdl:operation name="SimpleTest">
<soap:operation soapAction="http://namespaces.deanblakely.com/wcf/SimpleTest" style="document"/>
The SOAP_ADDRESS is the only one that actually points to your service file, e.g. http://www.deanblakely.com/Service2.svc.
Hopefully that will get you started calling in to your web service; if not feel free to stop back and get more assistance.
EDIT: Missed the part about async calls.
Yes, the method described on that web page is synchronous. WCF service methods are synchronous by default, with the option to include asynchronous calls when generating a service reference in Visual Studio. wsimport generates async-ready proxies, so using the Android client generate may also help you out in this area.

Related

How to implement .NET code library as a service layer - sharing same BL/CRUD between several applications

Setting: I'm developing an intranet tool set for my department, the main point of which is to centrally manage data quality and accessibility, but also to automate and scale some partial-processes.
Problem: I currently have my business logic in a CLR assembly, which is available on my SQL-Server for other CLR assemblies that run automated ETL directly on the SQL-Server. I am also developing an intranet site, which also needs the code information in that business logic assembly, but referencing the CLR assembly code has been working out sub-optimally, in terms of deployment and code maintenance. Also another department has voiced interest in using the code-base and data for their own intranet site.
Question(s): I've read quite a few Q&A(1,2,3,4,...) on SO to this topic, but I find it a very encompassing, so I'll try to ask questions for a more specific case(i.e. a single BL and Data Access code base)
Is a WCF service the solution I want? All my potential service clients run on the same server, is there maybe another way to reference the same code base both in CLR assembly and website projects? I don't need support for different platforms(ex. Java) - everything is .NET(yay for in-house progr!) - is WCF overkill?
Can code from a WCF service be used like a class library, or do I need to program a new way for accessing classes/methods from the service?
Separation of Development, Test and Productive instances?
Can a WCF service be updated while clients are accessing it, or do I need to schedule maintenance windows? When I update the service, do I need to update the client as well in some way?
Can I dynamically set the service reference, like I currently am dynamically setting the database connection string, depending on if StageConfig = dev, test, or prod?
My CLR assemblies are written for .Net 3.5, but the websites for .NET 4.0, will that pose a problem?
What minimum set of .NET service architecture programming do I need to know to accomplish this? I'll learn more about WCF with time, but I need to evaluate architecting effort and weigh it against getting things done(feature requests). Does the MS tutorial get me the desired skill?
I appreciate answers to only single questions, if you feel you know something, I'll +1 whatever helps me get closer to a complete answer.
OK, so you want to make your code enterprise-wide. There are two fundamental problems to talk about when you want to do this, so I'll structure the answer that way:
You have to understand what WCF is all about.
You have to manage your dependencies correctly.
What WCF is about
WCF is a way of doing RPC/RMI (Remote procedure call/remote method invocation) which means that some client code can call code that is located somewhere else through the network.
A callable WCF service is determined by the ABC triplet:
The service specification is implemented as a .NET interface with a "ServiceContract" attribute. This is the Contract ("C")
The "location" of the service is determined by a pair : Address ("A") and Binding ("B"). The Binding determines the protocol suite to be used for communication between client and server (NetPipe, TCP, HTTP, ...). The Address is a URI following the scheme determined by the Binding ("net.pipe", "net.tcp", "http", ...)
When the client code calls a WCF service at a specific Address, with a specfic Binding, and a specific Contract (which must match what the server at the specific Address and the specific Binding is delivering), WCF generates a proxy object implementing the interface of the contract.
The program delivering the service is any .NET executable. It has to generate one or many WCF Hosts, that will register objects or classes that implement the service contract, and asociate each delivered service to a specific Address and Binding. (possibly many thereof)
The configuration can be through the app .config file, in which you will be specifying ABC triplets and assotiate these triplets with a name that you will use in your application. You can also do it programmatically, which is very easy.
WCF does not address your problem of deploying your application, or the configuration of addresses and binding. It just addresses the problem of letting two executables communicate with each other with strongly-typed objects (through a specific interface). Sharing the service configuration is up to you. You may use a shared .config file on a Windows share, or even set up a LDAP server that will deliver all the data you need to find your service (namely A and B).
Managing your dependencies correctly
In your scenario, there are three actors that want to use your WCF infrastructure:
Your SQLCLR assembly, which will be a client.
The intranet site, which will be another client.
The service host, which will be a server.
The bare minimum number of assemblies will be 4. One for each of the aforementioned actors, and one specifying the contract, which will be used by all three actors. It should contain the following things:
The interface specifying the contract.
All types needed by the interface, which will of course be sent through the network, and therefore must be serializable.
There should be nothing more in it, or else, it will be a maintenance nightmare.
Answer to your questions
I hope that my answer is clear. Let's sum up the answers to your questions.
Is a WCF service the solution I want? All my potential service clients
run on the same server, is there maybe another way to reference the
same code base both in CLR assembly and website projects? I don't need
support for different platforms(ex. Java) - everything is .NET(yay for
in-house progr!) - is WCF overkill?
Everything is overkill. WCF is rather easy to use and scales down very well.
Can code from a WCF service be used like a class library, or do I need
to program a new way for accessing classes/methods from the service?
Setting up a WCF on existing code requires only the implementation of an additional class, and some code creating the Hosts which will serve the aforementioned class.
Calling a WCF service requires the creation of a Channel, which is a .NET (proxy) object implementing the interface.
So basically, your business code remains in the same state.
Separation of Development, Test and Productive instances?
WCF does not take care of that. Different environments, different service addresses. You have to take care of this yourself.
Can a WCF service be updated while clients are accessing it, or do I need to schedule maintenance windows?
It depends on your maintenance policy. Kill the serving process and launch the new version is the basic upgrade mechanism.
When I update the service, do I need to update the client as well in some way?
Provided that you manage your dependencies correctly like I sketched in the previous section, you need to update the clients only if the service specification (the interface) changes.
Can I dynamically set the service reference, like I currently am dynamically setting the database connection string, depending on if StageConfig = dev, test, or prod?
You have to manage that, probably by etting Address and Binding for a service programmatically.
My CLR assemblies are written for .Net 3.5, but the websites for .NET 4.0, will that pose a problem?
Provided that you manage your dependencies correctly like I sketched in the previous section, the only constraint will be the minimum CLR version required by the "contract" assembly.
What minimum set of .NET service architecture programming do I need to know to accomplish this? I'll learn more about WCF with time, but I need to evaluate architecting effort and weigh it against getting things done(feature requests). Does the MS tutorial get me the desired skill?
You'll need the result of these exercises:
Make two executables, a client and a server, that will communicate
through a WCF contract located in a separate DLL. The configuration
should be located in the app .config file.
Make two executables, a client and a server, that will communicate
through a WCF contract
located in a separate DLL. The configuration should be determined programatically.
Try to send a serializable class as a parameter to your service.
Try to send a serializable class as a return value of your service.
After that, you'll need to think about the best/cheapest way to share the Addresses and Bindings of your services.
Hope it helps.

Hosting a service with WCF from WSDL - SVCUtil generates verbose types for methods

I have a WSDL file from a published ASMX web service. What I am after
is creating a mock service that mimics the real service for testing purposes.
From the WSDL, I used SvcUtil.exe to generate code. Apparently it also generates
the server side interface.
Well the issue is that it generates very chunky interfaces. For example, a method
int Add(int, int) is showing up in the generated .cs file as AddResponse Add(AddRequest). AddRequest and AddResponse have a AddRequestBody and AddRequestResponse and so on.
The issue is that, to implement, I need to create the body and response instances for each method, even when I just want to return a simple int result.
Why can't it generate the method signature properly? Is there a better way of generating WCF Server side interface/contracts from WSDL?
The message structure you are describing is caused by two things:
better interoperability across web service stacks and their programming models (RPC vs messaging);
flexibility to accommodate new parameters into existing web services.
You are not the first one to complain about it, or the last. It's a WSDL binding style commonly called the document/literal wrapped pattern. It produces document/literal web services and yet also supports an RPC programming style. It's very "WS interoperability friendly", so to speak...
The WS-I Basic profile specifies that the soap:body must have only one child element and in this case it's a wrapper for the operation name that's being invoked. The parameters of the call are packed into only one element as a best practice since it's more flexible to later changes. In case of WCF you usualy end up with a MessageContract which has one MessageBodyMember which wraps all the parameters.
Basically, you are seeing the results of web service battles fought long time ago.
Here is some extra reading on the subject (and that's just the tip of the iceberg):
Which style of WSDL should I use?
RPC/Literal and Freedom of Choice
My Take on the Document/Literal 'Wrapped' Idiom

How does WCF Decide which Operation to Dispatch To?

I'm building a WCF SOAP application. The WSDL file has numerous operations of which many have the same argument type. The WSDL file defines all soapAction attributes as "''". When I try to start such a service WCF throw an exception saying that soapActions have to be unique.
After some googling I'm even more puzzled than before. I used SOAPUI to create a mock service with two operations which take the same input type and without the soapActions defined it always chooses the same operation. When the actions are defined it works fine.
My questions are:
Can you make a WCF SOAP service without unique soapActions (actually leaving the soapActions "''" as defined in the original WSDL)?
How can a service choose the right operation without the soapAction defined?
Edited:
I'm not in control of the WSDL. I'm using the WSCF.Blue tool to create a service stub from the WSDL file. I might be able to modify the WSDL, but I want to see if there is some possibility to leave it as it is.
It is not very clear from your question but I suggest you are building service based on some defined WSDL, aren't you? WCF by default uses SOAP action because it is required part of WS-I Basic Profile 1.1 offered by WCF services with BasicHttpBinding. WSDLs with empty SOAP actions are used when the action is defined by root body element.
WCF samples provides example of custom DispatchOperationSelector which is able to route messages to operations by their root body element. This is probably what you need to add to your service so that clients based on provided WSDL can call it.

Unable to get WCF Test client to test WCF Service Library

I am attempting to replace a WSE service with the WCF equivalent where the WSDL is provided externally.
First, I used svcutil and wsdl to generate all the service and client classes (ATP, I'm only concerned with the service implementation.) I generated an empty WCF Service Library project and replaced/renamed the IService1.cs with a class named for the interface ServiceContractAttribute generated. I then renamed the implementation class Service1.cs with the name of the implementation-class JINDEXWcfListener.cs. I removed the generated code from this class and created class definition JINDEXWcfListener:[interface name].
The tool auto-generated the implementation of the interface. I used the single method adorned with [OperationContractAttribute] to put my local implementation code. I modified the default app.config generated to adjust the contract and service names as required.
When I start debug, I can see that the service is starting in the WTC. However, when the single operation is exposed, the is a red dot with a yellow question mark in front of the operation name. When I RC on the op name, I get "This operation is not supported in WCF Test client" with no additional information. What is wrong?
WCFTestClient has quite a few limitations. I have fought "problems" for several hours that later turned out to be just WCFTestClient problems. Complex objects can give you a lot of grief, also any custom lists, etc such as a custom implementation of the IList interface. Try out WcfStorm. I think they have a free version and a trial version.

Simpler Explanation of How to Make Call WCF Service without Adding Service Ref

In Understanding WCF Services in Silverlight 2, the author, David Betz, explains how to call a web service without adding a service reference in the client application. I have a couple of weeks experience with WCF, so the article was over my head. In particular, although the author gave a lot of code snippets, but does not say what goes where. In the article, he provides two different code snippets for the web.config file, but does not clarify what's going on.
Looking at the source code there are four projects and two web.config files.
So far, I have been using the standard Silverlight project configuration of one project for the web service and one for the Silverlight client.
Firstly, does the procedure described in the article work with the standard two project configuration? I would think it would.
Secondly, does anyone know of a simpler example? I am very interested in this, but would like to either see source code in the default two project setup which is generated when a new Silverlight project is made, or find a step by step description of how to do this (eg, add a class called xxx.cs and add this code..., open web.config and add these lines...)
Many thanks
Mike Thomas
First, a little philosophy...
If you are a consumer of a WCF service that you did not write, adding a service reference to your client is really the only mechanism you have to enable interaction with that WCF service. Otherwise, you have no way of knowing what the service contract looks like, much less its data and message contracts.
However, if you are in control of both the client and the WCF service itself, adding a service reference to the client is a nice convenience, but I've recently been convinced not to use it. For one, it becomes a nuisance after the first few times you change your contract to remember to update your service reference. And in my case, I have several different C# projects that are consuming the WCF service, so I have to remember to update each one of them. Second, creating a service reference duplicates the contract definitions that are already defined in your WCF service. It is important to understand the implications of this.
Let's say your WCF defines the following type.
[DataContract]
public class Person
{
[DataMember] public string FirstName {get; set;}
[DataMember] public string LastName {get; set;}
}
When you add a service reference to your client, the metadata associated with this class is retrieved through the metadata exchange (MEX) endpoint, and an exact replica of this class is created on the client side that your client "compiles" against. So your WCF service has a definition of the Person class, and so does your client, but they are two different, distinct class definitions.
Given this, it would make more sense to abstract the Person class into a separate assembly that is then shared between the WCF service and the client. The added benefit is that when you change the contract definitions within this shared assembly, you no longer have to update the service reference within the client because it is already referencing the shared assembly. Does that make sense?
Now to your question. Personally, I've only used WCF within C# projects, not Silverlight. However, I do not think things are radically different. Given that, I would suggest that you watch the Extreme WCF video at dnrTV. It gives a step-by-step guide for how to bypass the service reference feature.
Hope this helps.
Let me try - I'm not an expert at Silverlight development, so bear with me if I say something that doesn't apply to Silverlight :-)
As Matt Davis mentioned, the "usual" use case is this: you add a service reference to a given service URL. In doing so, Visual Studio (or the command-line tool svcutil.exe) will interrogate the service and grab its metadata - information that describes the service, all the available methods to call, what parameter they expect etc. From this, it will generate a class for you (usually called the "client" or "client proxy"), which you as a client (=service consumer) will use to call the service. You can have this client proxy class generated inside your "normal" Silverlight client project, or you could possibly create your own "service adapter" class library, esp. if you will be sharing that client proxy code amongst several Silverlight projects. How things are structured on the server side of things is totally irrelevant at this point.
As Matt D. also mentioned, if you do it this way, you're getting copies of the service, its methods, and its data, in your client - those are identical in structure to what the server has - but they're not the same type - you on the client side have one type, the server has another (the fields and properties are identical though).
This is important to remember since the whole basic idea of WCF is message-passing - all that connects the client (you) and the server (the other end) are the messages and their structure - what method to call and what values to pass into that method. There's no other link - there's no way a server can "connect" to the client code and check something or whatever. All that gets exchanged is serialized messages (in text or binary form).
If you do control both ends, you can simplify things a bit - you can physically share the service contract (the definition what the service looks like and what methods it has to call into) and the data contract (the description of what data is being passed back and forth) on both the server side as well as the client side. In this case, you won't be adding a service reference, you won't be duplicating the service and data definitions, so things are a bit easier (but it only works if you're in control of both ends).
In this case, best practice would be to package up all that describes the service (the service interface with its methods and the data contracts) into a separate assembly (class library) on the server, which you can then copy to the client side, and reference directly from there (like any old assembly you might have). So in this case, you would typically have at least three projects in your solution:
your actual Silverlight client project
the website or web app hosting your Silverlight control for testing
the service interface assembly, which contains the service and data contracts
So there you have it - I hope I covered all the basics of what's going on, and why you would want to do one or the other thing. If you need additional info, don't hesitate to comment on this posting and let us know!
Marc