Continuing to learn WCF, I'm trying to write a small program that would with a click of a button take the work from texbox1 , pass it to ServiceContract and get back its length.
Here's how far I got.
Form1.cs:
...
wcfLib.Service myService = new wcfLib.Service();
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = Convert.ToString( myService.go(textBox1.Text) );
}
...
and the wcf file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace wcfLib
{
[ServiceContract]
public interface IfaceService
{
[OperationContract]
int wordLen(string word);
}
public class StockService : IfaceService
{
public int wordLen(string word)
{
return word.Length;
}
}
public class Service
{
public int go( string wordin )
{
ServiceHost serviceHost = new ServiceHost(typeof(StockService), new Uri("http://localhost:8000/wcfLib"));
serviceHost.AddServiceEndpoint(typeof(IfaceService), new BasicHttpBinding(), "");
serviceHost.Open();
int ret = **///// HOW SHOULD I PASS wordin TO StockService to get word.Length in return?**
serviceHost.Close();
return ret;
}
}
}
what I can't figure out right now, is how do I pass the wordin variable above into the ServiceContract?
You need to create the client in your form and call wordLen() directly... only a class that inherits from IfaceService can be called as a WCF service. So:
// You'll have to create references to your WCF service in the project itself...
// Right-click your form project and pick 'Add Service Reference', picking
// 'Discover', which should pick up the service from the service project... else
// enter http://localhost:8000/wcfLib and hit 'Go'.
// You'll have to enter a namespace, e.g. 'MyWcfService'... that namespace is
// used to refer to the generated client, as follows:
MyWcfService.wcfLibClient client = new MyWcfService.wcfLibClient();
private void button1_Click(object sender, EventArgs e) {
// You really shouldn't have the client as a member-level variable...
textBox2.Text = Convert.ToString(client.wordLen(textBox1.Text));
}
If your Service class is meant to host the WCF Service, it needs to be its own executable and running... put the code you have in go() in Main()
Or host your WCF Service in IIS... much easier!
Edit
IIS = Internet Information Services... basically hosting the WCF Service over the web.
To host in IIS, create a new project, "WCF Service Application". You'll get a web.config and a default interface and .svc file. Rename these, or add new items, WCF Service, to the project. You'll have to read up a bit on deploying to IIS if you go that route, but for debugging in Visual Studio, this works well.
To split into two applications, just make the form its own project... the service reference is set through the application's config file; you just point it to the address of the machine or website, e.g. http://myintranet.mycompany.com:8000/wcflib or http://myserver:8000/wcflib.
Thanks for the vote!
You've definitely got things back-to-front. You don't want to create the ServiceHost in your Go method, or at least, you'd never create it in any method invoked by the client, because how could the client call it if the service hasn't been created yet?
A service in WCF is started, and THEN you can invoke its methods from a remote client. EG, this is your Main() for the service:
ServiceHost serviceHost = new ServiceHost(typeof(StockService), new Uri("http://localhost:8000/wcfLib"));
serviceHost.AddServiceEndpoint(typeof(IfaceService), new BasicHttpBinding(), "");
serviceHost.Open();
Console.WriteLine("Press return to terminate the service");
Console.ReadLine();
serviceHost.Close();
Then for your client you'd use "Add Service Reference" in Visual Studio (right-click on the Project in Solution Explorer to find this menu option) and enter the address for the service. Visual Studio will create a proxy for your service, and this is what you'd instantiate and use on the client. EG:
MyServiceClient client = new MyServiceClient();
textBox2.Text = Convert.ToString( client.wordLen(textBox1.Text) );
Related
I've been trying to create an application that can receive information from other running applications through WCF.
I've setup a void method in a separate class, created the interface, and hosted the service.
In my Host application I have the following method.
public Class ReceivingMethods : IReceivingMethods
{
Public void HelloWorld(string text)
{
MessageBox.Show(text);
}
}
and
[ServiceContract]
interface iReceivingMethods
{
[OperationContract]
void HelloWorld(string text);
}
In the client, I would like to do this:
HostService client = new HostService();
client.HelloWorld("Hello World");
client.close();
But it doesn't work and instead I have to do this.
HostService client = new HostService();
HelloWorld hi = new HelloWorld();
hi.text = "Hello World";
client.HelloWorld(hi);
client.close();
I've gotten it to work as the former previously in an Application/ASP combination, but not on this application and I cannot find any difference in the setup between the two applications.
Can anybody tell me what is required from the WCF setup to get it to work as the former?
HostService client = new HostService();
You haven't mention what endpoint or which class object to use.Typically the servicehost class must create the object of particular end point,something like below one.
using(System.ServiceModel.ServiceHost host =
new System.ServiceModel.ServiceHost(typeof(ReceivingMethodsnamespace.ReceivingMethods )))
{
host.Open();
Console.WriteLine("Host started # " + DateTime.Now.ToString());
Console.ReadLine();
}
Generally the hostservice must create an object of the class which is implementing servicecontract interface(servicename of AddressBindingContract file)
Turns out I found the issue somewhere else.
I configured the client service reference to "always generate message contracts"
Unchecking this and updating the service reference solved the issue.
I found the solution here.
https://social.msdn.microsoft.com/Forums/en-US/b9655eeb-cdbb-4703-87d8-00deac340173/add-service-reference-creates-message-contracts-requestresponse-objects-with-always-generate?forum=wcf
I'm trying to make an application that can send sms using twilio API
This API contains statusCallback attributes, which we can include a link that the API can send data about the delivery behavior ( if sms are received etc...)
public void sendSMS()
foreach (var toNumber in TOnumbersList)
{
var message = MessageResource.Create(
to: new PhoneNumber(toNumber),
from: new PhoneNumber(fromNumber),
body: msgBody,
provideFeedback: true,
statusCallback: new Uri("http://localhost:5000/"));// <----
}
As you can notice , in the statusCallback I precised that I would like to send the information on localhost:5000/
In my solution explorer of visual studio 2015 I added a separated project and called it windows Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
// ServiceBase.Run(ServicesToRun);
_httpListener.Prefixes.Add("http://localhost:5000/"); // add prefix "http://localhost:5000/"
_httpListener.Start(); // start server (Run application as Administrator!)
Console.WriteLine("Server started.");
Thread _responseThread = new Thread(ResponseThread);
_responseThread.Start(); // start the response thread
}
static HttpListener _httpListener = new HttpListener();
static void ResponseThread()
{
while (true)
{
HttpListenerContext context = _httpListener.GetContext(); // get a context
var a = context.Request.Url; // Now, you'll find the request URL in context.Request.Url
byte[] _responseArray = Encoding.UTF8.GetBytes("<html><head><title>Localhost server -- port 5000</title></head>" +
"<body>Welcome to the <strong>Localhost server</strong> -- <em>port 5000!</em></body></html>"); // get the bytes to response
context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length); // write bytes to the output stream
context.Response.KeepAlive = false; // set the KeepAlive bool to false
context.Response.Close(); // close the connection
Console.WriteLine("Respone given to a request.");
}
}
}
}
After that , in the configuration of the solution I precised that I wanted the service to run before the windows form project as you can notice in the picture
So once I start the solution , I went on localhost:5000 and noticed that the service is running and the page is displaying a welcoming message
But , once the sendSMS() function is called (or invoked ) ( while the service is running) I'm receiving this error :
Error : The status callback on localhost is not a valid URL
So my question is what I am doing wrong ? I would like to understand I am not very experienced with the web service techniques , did I forget to enable something? Or something related to asynchronous and synchronous issue ?
Note : In the past , (instead of using local-host ) , I have created a url using http://requestb.in/ ( which does the job of a webservice) and I have copied the created url and there was no problem sending data on the link . But with when the link is localhost , the issue is noticed
"Localhost" resolves to the machine the code is currently running on, which is 127.0.0.1 (IPv4) and ::1 (IPv6).
If you pass localhost to a remote service like Twilio, the remote service will resolve "localhost" to 127.0.0.1/::1, which is itself. This doesn't make any sense and is why Twilio rejects the URL.
The callback URL you specify must be public and reachable from Twilios services, otherwise this won't work. I usually use a cheap or free Azure website for tests like this.
I've been following tutorial here and trying to host a simple REST Server using WCF. Basically, I created the WCF interface and class file as described in the tutorial:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GET/{msg}/{msg2}")]
string GetRequest(string msg, string msg2);
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "/PUT/{msg}")]
void PutRequest(string msg, Stream contents);
}
and the concrete class:
class Service : IService
{
static string Message = "Hello";
public string GetRequest(string msg, string msg2)
{
return Message + msg + msg2;
}
public void PutRequest(string msg, Stream contents)
{
Service.Message = msg + msg + msg;
string input = new StreamReader(contents).ReadToEnd();
Console.WriteLine("In service, input = {0}", input);
}
}
These 2 WCF service classes work perfecting in a Console Application I created. Here is how "Main" looks like. When I submit a GET request to the Console Application, I get a 200 OK:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(Service)))
{
var ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), new Uri("http://1.10.100.126:8899/MyService"));
ep.EndpointBehaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Service is running");
Console.ReadLine();
host.Close();
}
}
}
}
However, when I want to use those 2 classes in a WPF Application, they don't work anymore. Here is the MainWindow class for the WPF Application. When I submit a GET Request to the WPF Application, I get error 502 BAD GATEWAY:
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
using (var host = new ServiceHost(typeof(Service)))
{
var ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), new Uri("http://1.10.100.126:8899/MyService"));
ep.EndpointBehaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Service is running");
Console.ReadLine();
host.Close();
}
}
}
}
How do you make those 2 WCF classes work with a simple empty WPF Application project? Why does those 2 WCF classes work with an empty Console Application project, but not an empty WPF Application Project?
Giving you a complete, thorough answer on how to properly host a WCF service properly in a WPF application is really a bit too broad, but here are some pointers.
You have a few major problems with your WPF attempt:
You're attempting to host the service on the UI thread, a big no-no in GUI design and programming. If you got it working the way you have it, you'd lock your UI and the user wouldn't be able to do anything but force-close your application.
You're handling it all in a code behind for a Window - WPF encourages the MVVM pattern, which guides you to separate concerns of how your view (window, controls, etc.) is rendered vs. what services are used/hosted/consumed.
You're attempting to block the thread by using Console.ReadLine() in a GUI application, where there is no Console listening - so Console.ReadLine() is just returning immediately (but if you did manage to block the thread, you'd be back to problem #1).
For a full tutorial on how to do what you're attempting with better design principles, see the following blog
Some highlights from that:
Create some controls (e.g. buttons that say 'Start' and 'Stop') to start and stop your service.
Wire up those buttons to the logic to start your service and stop your service respectively.
There's definitely improvements that could be made there - starting and managing the lifetime of the service, using the Commanding model in WPF, using the TPL or a BackgroundWorker to run the service in a different thread, making fuller usage of the MVVM pattern - but it's a start.
I think I've literally checked for all possibilities but I still keep getting this error (written in eventvwr) when I attempt to start my service:
Service cannot be started. System.InvalidOperationException: Service
'NexolNotifierWinService.NexolNotifier' has zero application
(non-infrastructure) endpoints. This might be because no configuration
file was found for your application, or because no service element
matching the service name could be found in the configuration file, or
because no endpoints were defined in the service element.
Service installation goes smoothly using installutil.
I'm genuinely not sure why I'm having this error. It's just a simple Windows Service project, so there's no app.config to mess around with either.
Here's my code:
Program.cs
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new NexolNotifierService()
};
ServiceBase.Run(ServicesToRun);
}
}
NexolNotifierService.cs
public partial class NexolNotifierService : ServiceBase
{
private ServiceHost host;
public NexolNotifierService()
{
InitializeComponent();
this.ServiceName = "NexolNotifierService";
}
protected override void OnStart(string[] args)
{
Type serviceType = typeof(NexolNotifier);
host = new ServiceHost(serviceType);
host.Open();
}
protected override void OnStop()
{
if (host != null)
host.Close();
}
}
ProjectInstaller.Designer.cs (For installing service)
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.ServiceName = "NexolNotifierService";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
and my actual service:
NexolNotifier.cs
public class NexolNotifier
{
public NexolNotifier()
{
....
}
Service was added from add new project->Windows Service in Visual Studio 2008.
I'm just trying to get a very simple windows service working. From what I can see, there is zero reason why this shouldn't work.
What do you want to do?
If you want just a plain Windows Service - no communication, nothing - then you don't need ServiceHost! You just need to derive from the ServiceBase class in the .NET framework and implement/override some of the methods - that's all. Read values from a database, do something with them, send e-mails - whatever - you will never need a ServiceHost for this!
If you use ServiceHost then you're using the WCF infrastructure, which means, you're writing a self-hosted web service.
So what do you want to do, really??
What's the task/job that your Windows Service is supposed to do?? ServiceHost has nothing to do with a plain Windows Service! ServiceHost == WCF - always. You don't need a ServiceHost for just a plain Windows service
For just plain Windows service (no WCF), see e.g.
Creating a Basic Windows Service
Simple Windows Service Sample
and many, many more samples. Both samples show just a plain Windows service, no WCF, no ServiceHost anywhere in sight.
Add service endpoint from code like this
Uri baseAddress = new Uri("http://localhost:8095/Service");
serviceHost = new ServiceHost( typeof(YourService), baseAddress );
serviceHost.AddServiceEndpoint( typeof(IYourService), new BasicHttpBinding(), baseAddress );
serviceHost.Open();
I have a WCF service (service1). I host several instances of this service in managed application (simple .NET applacation). And I have another WCF service (service2) hosted in windows service.
When a run my application all service1 instances connect to service2 and everything goes fine. But when service2 tries to connect to any instance of service1 there is an exception "There was no endpoint listening at net.tcp://localhost:8732/TestComponent_6a4009df-cc68-4cd9-9414-16737c734548 that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
All services1 instances has unique addresses (see guid in uri) but similar service contracts and binding types. I use netTCP bindings with port sharing turned on.
Any advices?
Note: when I host the only one service1 instance in managed application everything goes fine. I can run several instances of my app and there are no errors too. And only when I hosted several service1 instances in one app I have problems.
There are some code:
Service1 instances creating:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Component = new TestComponent("net.tcp://localhost:8732/TestComponent", Component_OnMessageReceivedEvent);
Component.JoinServer();
Component2 = new TestComponent("net.tcp://localhost:8732/TestComponent", Component_OnMessageReceivedEvent);
//guids is added to addresses in TestComponent constructor
Component2.JoinServer();
}
How it works inside the component:
public void JoinServer()
{
this.StartComponentHosting();
if (ServerClient != null)
{
ServerClient.Close();
ServerClient = null;
}
ServerClient = new ServerClient();
ServerClient.Open(); //conneting to service2
ServerClient.JoinComponent(this.ProviderInfo); //calling some method on service2
}
private void StartComponentHosting()
{
if (ComponentHost != null)
{
ComponentHost.Close();
}
ComponentHost = new ServiceHost(this);
var portsharingBinding = new NetTcpBinding("NetTCPBindingConfig") { PortSharingEnabled = true };
ComponentHost.AddServiceEndpoint(typeof(IComponent), portsharingBinding, this.Address);
ComponentHost.Open();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Component = new TestComponent("net.tcp://localhost:8732/TestComponent", Component_OnMessageReceivedEvent);
Component.JoinServer();
Component2 = new TestComponent("net.tcp://localhost:8732/TestComponent", Component_OnMessageReceivedEvent);
//guids is added to addresses in TestComponent constructor
Component2.JoinServer();
}
From this code section, it seems that all of your service1 instances are using the same port and adress. ASAP, it is not possible to host multiple instances on the same port, if you are not using IIS.