I have a WCF Service interface, a class that implements the contract and a hosting winforms application. This then starts worker processes who connect back to the WCF server and then the events should be getting triggered. The client worker process is not having any issues making the calls to the methods and followed by that I am expecting the attached event handlers be called within the Windows forms application too but this is not happening:
xWCFService xWCFService = new xWCFService();
xWCFService.eventWorkerProcessStart += new EventHandler<WorkerProcessProgressChangedEventArgs>(xWCFService_eventWorkerProcessStart);
xWCFService.eventWorkerProcessStop += new EventHandler<WorkerProcessProgressChangedEventArgs>(xWCFService_eventWorkerProcessStop);
xWCFService.eventWorkerProcessUpdateProgress += new EventHandler<WorkerProcessProgressChangedEventArgs>(xWCFService_eventWorkerProcessUpdateProgress);
xWCFService.eventWorkerProcessError += new EventHandler<WorkerProcessProgressChangedEventArgs>(xWCFService_eventWorkerProcessError);
ServiceHost xServiceHost = new ServiceHost(xWCFService, new Uri(serviceAddress));
xServiceHost.AddServiceEndpoint(typeof(IxWCFServiceContract), new NetTcpBinding(), address);
xServiceHost.Open();
I am passing the instance of the Service class to the servicehost and it is a singleton instance. I appreciate any help/insight that can be provided on why I'm not referencing the correct instance.
After much reading I have noticed my mistake in the client side code:
static xWCFService xwcfService = new xWCFService();
....
{
EndpointAddress endPoint = new EndpointAddress(new Uri(string.Format(xWCFServerBaseAddress, address) + address));
Binding binding = new NetTcpBinding();
xChannelFactory = new ChannelFactory<IxWCFServiceChannel>(binding, endPoint);
xChannelFactory.Open();
xServiceChannel = xChannelFactory.CreateChannel();
xServiceChannel.Open();
**xwcfService.WorkerProcessStartedParsing(strGuidClientIdentifier);**
This last line was my mistake, I was invoking the calls on the service through an instance of the service implementation class. When I used the xServiceChannel to invoke the methods on the service, all events were raised.
Related
If I use this code for self Host a WCF service in a Console application it works. I run the host app and then from another app (which I call the client app,) I can add the service reference from visual studio > solution explorer > ADD SERVICE REFERENCE > http://10.131.131.14:8080/sendKioskMessage > click GO, add the service with no problems and consume it from the client app (which is a windows form)
But if I run the same code in a Windows Form, I run first the (SELF HOST WCF) windows form app, then from the other app (client app) in visual studio I try to add the service reference from ADD SERVICE REFERENCE in solution explorer (Just the same way that it works before but with the Console App self host) but it throws the following error:
*
An error (Details) occurred while attempting to find services at
http://10.131.131.14:8080/sendKioskMessage.
(If I click Details Link, says the following:)
There was an error downloading
'http://10.131.131.14:8080/sendKioskMessage/$metadata'. Unable to
connect to the remote server. Metadata contains a reference that
cannot be resolved: 'http://10.131.131.14:8080/sendKioskMessage'.
There was no endpoint listening at
http://10.131.131.14:8080/sendKioskMessage that could accept the
message. This is often caused by an incorrect address or SOAP action.
See InnerException, if present, for more details. Unable to connect to
the remote server. If the service is defined in the current solution,
try building the solution and adding the service reference again.
*
The IP that I use is the IP of my pc where both apps are running. I also used localhost instead of my actual IP with the same result.
Windows Form Code (can't add the service from another app):
public partial class KioskosServerForm : Form
{
[ServiceContract]
public interface IKioskMessageService
{
[OperationContract]
string SendKioskMessage(string message);
}
public class KioskMessageService : IKioskMessageService
{
public string SendKioskMessage(string message)
{
return string.Format("Message sent: {0}", message);
}
}
public KioskosServerForm()
{
InitializeComponent();
}
private void KioskosServerForm_Load(object sender, EventArgs e)
{
Uri baseAddress = new Uri("http://10.131.131.14:8080/sendKioskMessage");
try
{
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(KioskMessageService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open();
}
}
catch (Exception exp)
{
MessageBox.Show(exp.InnerException.Message);
}
}
}
Console App Code (Works! I can add the service from other client app):
[ServiceContract]
public interface IKioskMessageService
{
[OperationContract]
string SendKioskMessage(string message);
}
public class KioskMessageService : IKioskMessageService
{
public string SendKioskMessage(string message)
{
return string.Format("Message sent: {0}", message);
}
}
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8080/sendKioskMessage");
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(KioskMessageService),baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
}
}
I don't know why I can consume the service if the service is self hosted in a console app, but I can't add it if the service is self hosted in a Windows Form.
I will appreciate a lot your help to achieve this from a Windows From, since I need to self host the WCF service from a windows form, no a console app.
I'm using Visual Studio 2017, .Net Framework 4.6.1
THANKS IN ADVANCE GUYS!!
TL;DR the console app works because you have a delay before shutting down the service; the WinForms host doesn't
The reason your console WCF host service works is that you start the hosting and continue until the Console.ReadLine() line:
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine(); // <-------- program waits here
// Close the ServiceHost.
host.Close();
...after which the service is torn down. Prior to that, your other clients can connect fine and add Service References.
The WinForms app has no such delay:
private void KioskosServerForm_Load(object sender, EventArgs e)
{
Uri baseAddress = new Uri("http://10.131.131.14:8080/sendKioskMessage");
try
{
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(KioskMessageService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open(); // <------ opened here
} // <------ shutdown here
}
catch (Exception exp)
{
MessageBox.Show(exp.InnerException.Message);
}
}
...it is immediately shutdown when the code goes out of scope of the using block. The using will automatically call Dispose() on the host object which in turn calls Close().
Consider placing the host into a variable like so:
ServiceHost _host; // <---------- new!
private void KioskosServerForm_Load(object sender, EventArgs e)
{
Uri baseAddress = new Uri("http://10.131.131.14:8080/sendKioskMessage");
try
{
// Create the ServiceHost.
_host = new ServiceHost(typeof(KioskMessageService), baseAddress))
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
_host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
_host.Open();
}
catch (Exception exp)
{
MessageBox.Show(exp.InnerException.Message);
}
}
Later, you can close the _host instance with a call to Close.
I am very new to .NET remoting. We have an MVC website making call to a Windows application using TCP connection (.NET remoting). There is a timer running every 30 seconds which makes a call via TCP, but after it finishes, the connection still remains established. As a result, after a few days, the server is throwing an exception because all ports are used up. Then we have to restart the app pool to resolve the issue. I am not sure how can we close the port after use, so that we can use it again. We have a lot of users for the site.
Below is the client side code to register a channel
bool Registered = false;
foreach (IChannel ic in ChannelServices.RegisteredChannels)
{
if (ic.ChannelName == ChannelNameRemoting)
{
return ic;
}
}
// Channel not found yet
IDictionary channelConfig = new Hashtable();
channelConfig["name"] = ChannelNameRemoting;
channelConfig["secure"] = false;
BinaryClientFormatterSinkProvider defaultClientSink = new BinaryClientFormatterSinkProvider();
if (remotingSinkProvider == null)
{
remotingSinkProvider = new CustomClientChannelSinkProvider();
remotingSinkProvider.EncodingDecodingProviderEvent
+= new CustomClientChannelSinkProvider.EncodingDecodingProviderDelegate(remotingSinkProvider_EncodingDecodingProviderEvent);
}
defaultClientSink.Next = remotingSinkProvider;
IChannel channel = new TcpChannel(channelConfig, defaultClientSink, null);
if (!Registered)
{
ChannelServices.RegisterChannel(channel, false);
}
return channel;
Below call will create a connection to connect to the server in timer.
var connection = (testConnect)Activator.GetObject(
typeof(testConnect),
"tcp://" + _remotingUrl + ":" + _remotingPort + "/test/test4"
);
connection.FunctionCall();
I guess you need to UnRegister you channel.
Please check the link
So ultimately we create the instance of TcpChannel and register it to channel service, and then finally return it to parent method, so that can use and can make the call. in the file/class where you have method that return the channel instance should also have another method to unregister the tcp channel, and once you are done with the call, you need to call this new methd to unregister the channel, and that will close the connection.
public void UnregisterMyTcpChannel(TcpChannel yourChannelInstance)
{
ChannelServices.UnregisterChannel(yourChannelInstance);
}
I've created a simple code to allow cross-appdomain communication using WCF and NamedPipes. I'm testing the code on my Windows 8.1 and it is causing a EndpointNotFoundException.
Here is my code:
Service Contract
[ServiceContract(Namespace = "http://PoC.AppDomainWCF")]
public interface ICrossAppDomainSvc
{
[OperationContract]
bool HasPermission(String User, String Permission);
}
Program.cs (WinForms)
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Thread thread = new Thread(new ThreadStart(StartService));
thread.Start();
Application.Run(new Form1());
}
static void StartService()
{
using (ServiceHost host = new ServiceHost(typeof(CrossAppDomainSvc), new Uri[] {
new Uri("http://localhost:12000/AppDomainWCF/"),
new Uri("net.pipe://localhost/")
}))
{
var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
host.AddServiceEndpoint(typeof(ICrossAppDomainSvc), binding, "CrossAppDomainSvc");
// Add a MEX endpoint
//ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();
//metadataBehavior.HttpGetEnabled = true;
//metadataBehavior.HttpGetUrl = new Uri("http://localhost:12001/AppDomainWCF");
//host.Description.Behaviors.Add(metadataBehavior);
host.Open();
}
}
}
Client code
NetNamedPipeBinding binding = new NetNamedPipeBinding();
ChannelFactory<ICrossAppDomainSvc> channelFactory = new ChannelFactory<ICrossAppDomainSvc>(binding);
EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/CrossAppDomainSvc");
ICrossAppDomainSvc service = channelFactory.CreateChannel(endpointAddress);
MessageBox.Show(service.HasPermission("Juliano", "XPTO").ToString());
The exception is thrown at the service.HasPermission call.
What is wrong with my code?
UPDATE
As the question has been answered and my proof-of-concept is working, I've created a repository on GitHub to help anyone who needs to allow cross appdomain communication.
CrossAppDomainWCF sample code
You open your ServiceHost and immediately close it. serviceHost.Open() method doesn't block. So your endpoint doesn't exist because host is already closed when you are connecting
I am working on an C# WCF project and I have got it pretty much working except for quite a big but hopefully simple problem.
The WCF service is hosted from within my Console application and my console application calls a function to a different class to open the connection for the WCF service.
However, if the last line of the function is host.open(); the function call then finishes to the connection gets closed and the service can no longer be used. However, if I put Console.ReadLine() after the host.open then the service stays open and I can use it but obviously the rest of the flow of the program no longer runs.
Below is the code I am using to open the host connection.
public void startSoapServer()
{
string methodInfo = classDetails + MethodInfo.GetCurrentMethod().Name;
if (String.IsNullOrEmpty(Configuration.soapServerSettings.soapServerUrl) ||
Configuration.soapServerSettings.soapPort == 0)
{
string message = "Not starting Soap Server: URL or Port number is not set in config file";
library.logging(methodInfo, message);
library.setAlarm(message, CommonTasks.AlarmStatus.Medium, methodInfo);
return;
}
//baseAddress = new Uri(string.Format("{0}:{1}", Configuration.soapServerSettings.soapServerUrl,
// Configuration.soapServerSettings.soapPort));
baseAddress = new Uri("http://localhost:6525/hello");
using (ServiceHost host = new ServiceHost(typeof(SoapServer), baseAddress))
{
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.Opened += new EventHandler(host_Opened);
host.Faulted += new EventHandler(host_Faulted);
host.Open();
Console.ReadLine();
}
Without the Console.ReadLine() there the function finishes so the connection closes. How can I keep the host open for the duration that the C# is app is running.
This function call is called from within the Main method halfway through initiliasing some stuff within the console stuff.
Thanks for any help you can provide.
You need to declare ServiceHost at class scope instead of function scope and do not use using.
using {} will automatically Dispose the object to which it pertains and Disposal means closing. Also, since your ServiceHost is defined at function scope, it will go out of scope as soon as the function finishes and will be cleaned up by the garbage collector.
The reason that your ReadLine call is preventing the closing is because it is inside the using statement and stops the program inside the function where the variable is declared keeping it in scope.
You need to do something like this:
private ServiceHost host;
public void startSoapServer()
{
// trimmed... for clarity
host = new ServiceHost(typeof(SoapServer), baseAddress));
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.Opened += new EventHandler(host_Opened);
host.Faulted += new EventHandler(host_Faulted);
host.Open();
// etc.
You will close host when you exit the application.
The main goal is to let users send message to the host. The host will think for two seconds, and then with DUAL, will send a message back. This is working fine for me.
The thing is, for every user who send a message, I'm subscribing him to a list. The thing I'm trying to accomplish is, if the user Console.Readline() == "b" ( brodadcast ), send all the subscribers "Hello".
But the list of subscribers is at the service, and the Console.Readline() is at the host.
The host:
static void Main(string[] args)
{
ServiceHost duplex = new ServiceHost(typeof (ServiceClass));
duplex.Open();
Console.WriteLine("Press 'b' To Broadcast All subscibers : Hello");
if (Console.ReadLine()=="b")
{
foreach (var registered in lstOfRegisteredUsers) //<== I cant access lstOfRegisteredUsers because its on the Service Class.
{
registered.SendBack("Hello");
}
}
Console.WriteLine("Host is running, press <ENTER> to exit.");
Console.ReadLine();
}
The service:
public class ServiceClass : ISend
{
public List<ISendBack> lstOfRegisteredUsers = new List<ISendBack>();
public void Send(string data)
{
ISendBack callback = OperationContext.Current.GetCallbackChannel<ISendBack>();
lstOfRegisteredUsers.Add(callback); // <== here i'm adding subscribers for future broadcast " hello".
Console.WriteLine("goind to process " + data);
System.Threading.Thread.Sleep(2000);
callback.SendBack("done " +data);
}
}
How can I send from the host, to each of the subscribers: "hello"?
If I understand correctly then you wish to broadcast a message to each of your service's callback clients if a key-press input is received into the console application hosting your service?
To do this you need to be able to call into your service instance from your host application.
This can be achieved by creating an instance of your service class within your host. Then when you create your ServiceHost you pass the instance into the ServiceHost constructor. Then in your service you have a method which does the actual callback and you can call it.
For example:
// Create an instance of your service class
ServiceClass sc = new ServiceClass();
// Instantiate new ServiceHost and pass in the instance as a singleton
serviceHost = new ServiceHost(sc, "(Service uri here)");
// Call the method on the service (which then calls the clients)
sc.DoCallbacks();