Send message to all via Dual Binding by specific request? - c#

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();

Related

Create a self hosted WCF Service inside a Windows Form

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.

.net remoting close connection to server after call

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);
}

Detect pipe server with same name in global namespace

Question: Is there a way how to quickly check whether particular pipename is being hosted in session 0 - preferabely during the ServiceHost.Open call?
Scenario:
Two processes PipeHost and PipeUser are trying to communicate on the system via pipe with name PeacePipe. They are not required to be started with special privileges.
PipeHost is started and hosts the PeacePipe without any problem.
PipeUser is started and connects to PeacePipe without any problem.
PipeUser tries to comunicate to PipeHost via PeacePipe, it sends messages but PipeHost doesn't see anything.
In fact PipeUser connected to DifferentPipeHostInSession0 that is hosting pipe with same name (but OS creates different pipe) in an elevated (or service) process.
Background:
ServiceHost.Open should throw AddressAlreadyInUseException when the selected pipename is already being hosted.
However it's not thrown if the pipe is hosted in session 0 and you are attempting to host the same pipe in different sessions. As windows named pipes are normally not te be used accross sessions. With the exception of pipe hosted in session 0. Any process can connect to such a pipe. This can lead to the above sceanrio.
Code:
[ServiceContract]
public interface IService
{
[OperationContract]
void Ping();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, IncludeExceptionDetailInFaults = true)]
public class Service: IService
{
public void Ping()
{
Console.WriteLine("Client Pinged me");
}
}
private static readonly Uri _pipeUri = new Uri("net.pipe://localhost/aaa");
private static readonly Binding _pipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
static void PipeHostTest()
{
ServiceHost serviceHost = new ServiceHost(new Service(), _pipeUri);
serviceHost.AddServiceEndpoint(typeof(IService), _pipeBinding, "");
try
{
//Fail here if same pipe already opened - even in Global space
serviceHost.Open();
Console.WriteLine("OPENED");
}
catch (AddressAlreadyInUseException e)
{
Console.WriteLine(e);
throw;
}
Console.ReadKey();
}
static void PipeClient()
{
ChannelFactory<IService> channelFactory =
new ChannelFactory<IService>(_pipeBinding, new EndpointAddress(_pipeUri));
var proxy = channelFactory.CreateChannel();
proxy.Ping();
}
static void Main(string[] args)
{
if (args.Any())
{
PipeClient();
}
else
{
PipeHostTest();
}
}
Run once without parameters elevated, once without parameters non-elevated. Both processes will host pipe with same name - but those are different pipes.
Then run once with any parameter. Client process will conect to the pipe hosted by elevated process.
Possible Solution:
Use a named mutex in global session new Mutex(true, "Global\\MutexForMyPipeName", out createdNew) to see if there is another process trying to do the same.
This however disqualifies even scenarios where the pipes are in 2 different sessions that do not colide.
Preferabely the ServiceHost.Open would take care about this for me as I'm using multiple bindings types (net.tcp, net.pipe, net.udp) and have single code for creating and hosting the ServiceHost. NamedPipes are the only ones that can allow creation of new host without AddressAlreadyInUseException exception while the address is actuall already in use.

C# How to force the wait for the connection to a WCF service

I have a service running as local SYSTEM that launches another application with the user credentials.
That second app is only a tray icon that shows balloon tips to the user with the string received using the callback method. This second application connects to the WCF in duplex mode.
My problem is that for some reason the connection to the WCF is finalized at the end of the method Main. So I cannot send a callback message to the app right after the execution, included in the last line "kiosk.MyStart(args);". there the callback is still pointing to null.
Any idea how could I solve this issue?
static void Main(string []args)
{
if (Environment.UserInteractive)
{
// Start the WCf service
var host = new ServiceHost(typeof(WcfService));
host.Open();
//Launch the Kiosk Agent which connects to the WCF
bool ret = ProcessAsUser.Launch("C:\\Program Files (x86)\\KIOSK\\KioskAgent.exe");
WinService kiosk = new WinService(args);
// some checks and a welcome message is sent to the user.
kiosk.MyStart(args);
//...
//...
}
}
Edit: to clarify a bit more, inside kiosk.MyStart method is where I try to execute the callback to show a welcome message, but the callback is still NULL.
As a result I assume that the client was not properly started for any reason and I launch it once again...
if (WcfService.Callback != null)
WcfService.Callback.UIMessageOnCallback(UIMessage);
else
ProcessAsUser.Launch("C:\\Program Files (x86)\\KIOSK\\KioskAgent.exe");
Add a try catch block over the callback method, if the client not reachable it falls in the catch you can unsubscribe it. Is also good practice send a keepalive message to your client, to check if it available.
private void InformClient(ClientInfo clientInfo)
{
var subscribers = this._subscriberRepository.GetAll();
foreach (var subscriber in subscribers)
{
try
{
if (subscriber.Callback.FireInformClient(clientInfo));
{
//If subscriber not reachable, unsubscribe it
this._subscriberRepository.Unsubscribe(subscriber.ClientId);
}
}
catch (Exception exception)
{
//If subscriber not reachable, unsubscribe it
this._subscriberRepository.Unsubscribe(subscriber.ClientId);
Log.Error(nameof(InformClient), exception);
}
}
}
IClientCallback
public interface IClientCallback
{
[OperationContract]
bool FireInformClient(ClientInfo clientInfo);
}
If you have more subscribers for example a terminal, server create a subscriberRepository to manage all subscribers.
var callback = OperationContext.Current.GetCallbackChannel<IClientCallback>();
if (this._subscriberRepository.Subscribe(clientId, callback))
{
return true;
}

Web Service responds to caller while still processing thread

I am creating a web service
Inside the web service, I do some processing, which is very fast, I send 2 to 3 emails asynchronously using SmtpClient.SendAsync().
My problem is that even though they are being sent asynchronously, I have to wait for them to finish processing before ending the service and sending back a response to the user. If I don't wait for the SendCompletedEventHandler to fire, the email is never sent. Sometimes the mail server takes some time to respond.
The user doesn't really need to know if the emails were sent or not. It would be nice to just send the emails and let them process somewhere else and respond to the user as fast as I can.
Would anybody have a good solution for this? Maybe I'm wording my searches wrong but I'm not coming up with any solutions.
You could fire up a new thread to do the sending:
ThreadPool.QueueUserWorkItem(delegate {
SmtpClient client = new SmtpClient();
// Set up the message here
using (MailMessage msg = new MailMessage()) {
client.Send(msg);
}
});
Here is a full example that I have tested and works with WCF. Control is returned immediately to the client, server starts sending, sleeps to simulate delay, then finishes. Just add a reference to System.ServiceModel to get the necessary classes.
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(HelloWorldService), new Uri("http://localhost:3264"));
ServiceMetadataBehavior mdb = new ServiceMetadataBehavior();
mdb.HttpGetEnabled = true;
host.Description.Behaviors.Add(mdb);
host.Open();
Console.WriteLine("Service Hosting...");
Console.ReadLine();
}
}
[ServiceContract]
class HelloWorldService
{
[OperationContract]
public void SendEmails()
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("Start Sending Emails...");
Thread.Sleep(10000);
Console.WriteLine("Finish Sending Emails...");
});
}
}
}

Categories

Resources