How to dynamically call the webservices from .NET Core - web-services

Currently I am consuming some webservices with multiple endpoints in .NET with the help of WCF Webservices reference provider tool. If there are any changes in webservices then I have to update or delete and reattach, then again will have to build to get the DLL and put in to deployment server.
This is very time consuming. Are there any alternate options?

At first, the WCF created by some complex bindings, authentication security may not work well with NetCore,such as Wshttpbinding. Generally, basichttpbinding is supported by the Core-based client.
With the interface, address and other service information unchanged, we can call the service dynamically through the channel factory, No matter how the server changes the implementation of the service. It does not affect the client’s invocation.
Here is an example.
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://10.157.13.69:1500");
BasicHttpBinding binding = new BasicHttpBinding();
ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(binding,new EndpointAddress(uri));
ICalculator service = factory.CreateChannel();
try
{
var result = service.Add(34.32, 2.34);
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
}
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double a, double b);
}
Here is a related document.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-channelfactory
Feel free to let me know if there is anything I can help with.

Related

GCP Pub/Sub: How to get event details in onFailure() of PublishCallbackListener

We want to have the fail back mechanism in case of any failure to publish event to Pub/Sub. I am using "ListenableFutureCallback" to know message published successfully or not. In case of failure, it is just throwing exception and I need event details to post it to internal messaging service. How do I get event details in onFailure() method.
I am using Spring Integration.
Below is piece of code.
Listener:
#Component
public class PubSubOperationListener implements ListenableFutureCallback<String> {
private static Logger LOGGER = LoggerFactory.getLogger(PubSubOperationListener.class);
#Override
public void onFailure(Throwable throwable) {
LOGGER.error("Failed to publish the message and details : {}",throwable);
// Logic to process it using different approach.
}
#Override
public void onSuccess(String s) {
LOGGER.info("Message published successfully.");
}
ServiceActivator:
PubSubMessageHandler pubSubMessageHandler = new PubSubMessageHandler(pubSubTemplate, testTopic);
pubSubMessageHandler.setPublishCallback(pubSubOperationListener);
return pubSubMessageHandler;
Please suggest if there is different approach to do same.
Currently, it's not possible because Spring Cloud GCP simply delegates to the Pub/Sub Publisher in the client library.
However, when we wrap the Future provided by the Publisher in Spring Cloud GCP, we can potentially include the original message there and other metadata. This would be a feature request that should be filed here.

Can't start a WCF Service installed as a Windows Service

I created a service that basically exposes some methods to update a sql server database.
I tested the service as a normal WCF Service (not a Windows Service) and it worked fine (which tells me that the ServiceModel definition in App.config is ok)
Then I turned it into a Windows Service, I installed it using InstallUtil, and it installed fine. But when trying to start it in the Services console, I get this message "The service WCFProductsWindowsService service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs"
The solution that exposes the service is composed of two projects,
a class library that defines the service, the contract, and an ADO
NET Entity Data Model to the database,
and a console application that exposes the service
The class that exposes the serice is:
public class ProductsWindowsService : ServiceBase {
public ServiceHost serviceHost = null;
public ProductsWindowsService() {
ServiceName = "WCFProductsWindowsService";
}
public static void Main() {
ServiceBase.Run(new ProductsWindowsService());
}
protected override void OnStart(string[] args) {
if (serviceHost != null) {
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(ProductsServiceImpl));
serviceHost.Open();
}
protected override void OnStop() {
if (serviceHost != null) {
serviceHost.Close();
serviceHost = null;
}
}
}
I uploaded the simple project in SkyDrive
What could I be doing wrong?
Does not allow me to add a comment.
This error "The service WCFProductsWindowsService service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs" indicates an exception is thrown.
I would check the event viewer to see the exception logged.
Does ProductsServiceImpl exists? I can't find it in your image or in your solution.

Access SOAP webservice with ServiceStack

I'm creating my client/server application intercommunication with ServiceStack, and is working great, but I need also to access an external SOAP web service.
I tried to use the Soap12ServiceClient to access it, but I couldn't find any example, and then I went the add service reference WCF way that actually worked, but creating a ton of code.
Is it possible to use Soap12ServiceClient in the same easy way I use JsonServiceClient to send a message/request and receive the message/response? If so, can you help or point me to a sample?
I'm not sure where you're stuck as all of ServiceStack's C# Service Clients implement the same IServiceClient so they can be used in the same way. Here is an example of all of ServiceStack's built-in C# Service Clients calling the same Hello World service:
[TestFixture]
public class HelloWorldServiceClientTests
{
public static IEnumerable ServiceClients
{
get
{
return new IServiceClient[] {
new JsonServiceClient(Config.ServiceStackBaseUri),
new JsvServiceClient(Config.ServiceStackBaseUri),
new XmlServiceClient(Config.ServiceStackBaseUri),
new Soap11ServiceClient(Config.ServiceStackBaseUri),
new Soap12ServiceClient(Config.ServiceStackBaseUri)
};
}
}
[Test, TestCaseSource("ServiceClients")]
public void HelloWorld_with_Sync_ServiceClients(IServiceClient client)
{
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
Assert.That(response.Result, Is.EqualTo("Hello, World!"));
}
}
Although SOAP works similar to any other C# client, it's un-common to use it in this way because if you're able to use a generic C# SOAP service client you're also likely able to use any of the other service clients which are all faster, more resilient and more versionable than SOAP - which has effectively has no redeeming quality over the other formats other than its ability to generate client proxies which you said you don't want to do anyway.
If you're undecided which endpoint or format you should use I recommend reading my Interview on InfoQ which discusses the disadvantages of SOAP and the benefits of using the other formats.

Design pattern to distinguish call as Web Service vs. Local

I have to come up with a design for service lookup i.e. decide on whether the service request can be handled locally or should be sent to a remote server (using SOAP Web Service calls). The first thing that comes to my mind is Service Locator.
Are there any other design patterns that fit the requirement? Any pointers or sample code would be helpful?
Service locator + Factory is exactly what you need.
The code , in my humble opinion, should look like this:
public enum ServiceOrigin {
REMOTE,LOCAL;
}
public class ServiceLocatorFactory {
MyService getService(ServiceOrigin origin) {
///Return a proper service instance
}
}
public interface MyService {
void doSomething();
}
ServiceLocatorFactory factory = //Get the factory somehow
MyService service = factory.getService(ServiceOrigin.REMOTE);
service.doSomething();
You can use Dependency Injection. If clients are unaware of where service are located (whether locally or remote), they should depends on abstractions:
public interface MyService {
void doSomething();
}
public class MyClientThatUsesMyService {
private MyService _service;
public MyClientThatUsesMyService(MyService service) {
_service = service;
}
public void Go() { _service.doSomething(); }
}
Then you can use a Dependency Injection container or (Poor Man's DI) to configure your composition root and set lifetime of the objects.

Consuming services that consume other services

What is the best way to confirm that these consumed services are actually up and running before I actually try to invoke its operation contracts? I want to do this so that I can gracefully display some message to the customer to give him/her a more pleasant user experience. Thanks.
I created an IsAvailable method that checked all of my underlying dependencies for my service. My client would call this method before doing anything else with my service. If it returned true, my service was available for use.
We also put intermediaten checks to rollback any changes if one of the underlying dependencies was not able at the time of the transaction.
Example:
Here is a simple example of how my IsAvailable is used by the client:
IsAvailable code
[WebMethod]
public bool IsAvailable()
{
bool EverythingUpAndRunning = true;
try
{
string TestConnectionString = WebConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(TestConnectionString);
sqlConnection.Open();
sqlConnection.Close();
sqlConnection.Dispose();
}
catch(Exception ex)
{
EverythingUpAndRunning = false;
}
return EverythingUpAndRunning;
}
The client code:
MyWebService proxy = new MyWebService();
if(proxy.IsAvailable)
{
//if true, you can use the other available methods in the service
}
I wouldn't consider myself a part of the SO Community but I have been in this situation before and it was simple exception handling around the service calls. If you're in control of the services, than you can put up a status method that returns it's current state. If the network is down and you can't even hit the service than you'll have to handle that with some exception handling but you could get a status back if the parent service is unable to use it's child services.
If you're following SO though, my own opinion here, you shouldn't be concerned with the consumed service consuming other services.