Calling WCF Service using NetTcpBinding from the same winform - c#

Hey all I have the following code that allows me to start a temp web service for WCF services without spooling up IIS Express myself.
However, the code below works just fine if I have the fetching of the data in another winform. Copying the same code over to the WCF service winform results in it freezing when trying to send patient index number.
The class code (Class1.cs):
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
/*
HOW TO HOST THE WCF SERVICE IN THIS LIBRARY IN ANOTHER PROJECT
You will need to do the following things:
1) Add a Host project to your solution
a. Right click on your solution
b. Select Add
c. Select New Project
d. Choose an appropriate Host project type (e.g. Console Application)
2) Add a new source file to your Host project
a. Right click on your Host project
b. Select Add
c. Select New Item
d. Select "Code File"
3) Paste the contents of the "MyServiceHost" class below into the new Code File
4) Add an "Application Configuration File" to your Host project
a. Right click on your Host project
b. Select Add
c. Select New Item
d. Select "Application Configuration File"
5) Paste the contents of the App.Config below that defines your service endoints into the new Config File
6) Add the code that will host, start and stop the service
a. Call MyServiceHost.StartService() to start the service and MyServiceHost.EndService() to end the service
7) Add a Reference to System.ServiceModel.dll
a. Right click on your Host Project
b. Select "Add Reference"
c. Select "System.ServiceModel.dll"
8) Add a Reference from your Host project to your Service Library project
a. Right click on your Host Project
b. Select "Add Reference"
c. Select the "Projects" tab
9) Set the Host project as the "StartUp" project for the solution
a. Right click on your Host Project
b. Select "Set as StartUp Project"
################# START MyServiceHost.cs #################
using System;
using System.ServiceModel;
// A WCF service consists of a contract (defined below),
// a class which implements that interface, and configuration
// entries that specify behaviors and endpoints associated with
// that implementation (see <system.serviceModel> in your application
// configuration file).
internal class MyServiceHost
{
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
//Consider putting the baseAddress in the configuration system
//and getting it here with AppSettings
Uri baseAddress = new Uri("http://localhost:8080/service1");
//Instantiate new ServiceHost
myServiceHost = new ServiceHost(typeof(TestService.service1), baseAddress);
//Open myServiceHost
myServiceHost.Open();
}
internal static void StopService()
{
//Call StopService from your shutdown logic (i.e. dispose method)
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
################# END MyServiceHost.cs #################
################# START App.config or Web.config #################
<system.serviceModel>
<services>
<service name="TestService.service1">
<endpoint contract="TestService.IService1" binding="wsHttpBinding"/>
</service>
</services>
</system.serviceModel>
################# END App.config or Web.config #################
*/
namespace TestService
{
// You have created a class library to define and implement your WCF service.
// You will need to add a reference to this library from another project and add
// the code to that project to host the service as described below. Another way
// to create and host a WCF service is by using the Add New Item, WCF Service
// template within an existing project such as a Console Application or a Windows
// Application.
[ServiceContract()]
public interface IService1
{
[OperationContract]
Patient GetPatient(Int32 index);
[OperationContract]
void SetPatient(Int32 index, Patient patient);
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class PatientService : IService1
{
Patient[] pat = null;
public PatientService()
{
pat = new Patient[3];
pat[0] = new Patient();
pat[0].FirstName = "Bob";
pat[0].LastName = "Chandler";
pat[1] = new Patient();
pat[1].FirstName = "Joe";
pat[1].LastName = "Klink";
pat[2] = new Patient();
pat[2].FirstName = "Sally";
pat[2].LastName = "Wilson";
}
public Patient GetPatient(Int32 index)
{
if (index <= pat.GetUpperBound(0) && index > -1)
return pat[index];
else
return new Patient();
}
public void SetPatient(Int32 index, Patient patient)
{
if (index <= pat.GetUpperBound(0) && index > -1)
pat[index] = patient;
}
}
[DataContract]
public class Patient
{
string firstName;
string lastName;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
}
the Service Code (Form1.cs):
using System;
using System.Windows.Forms;
using System.ServiceModel;
namespace TestService
{
public partial class Form1 : Form
{
bool serviceStarted = false;
ServiceHost myServiceHost = null;
NetTcpBinding binding;
Uri baseAddress = new Uri("net.tcp://localhost:2202/PatientService");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (serviceStarted)
{
myServiceHost.Close();
serviceStarted = false;
button1.Text = "Start Service";
}
else
{
binding = new NetTcpBinding();
myServiceHost = new ServiceHost(typeof(PatientService), baseAddress);
myServiceHost.AddServiceEndpoint(typeof(IService1), binding, baseAddress);
myServiceHost.Open();
serviceStarted = true;
button1.Text = "Stop Service";
}
}
private void button3_Click(object sender, EventArgs e)
{
IService1 patientSvc = null;
EndpointAddress address = new EndpointAddress(baseAddress);
ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
patientSvc = factory.CreateChannel();
Patient patient = patientSvc.GetPatient(Convert.ToInt32(textBox1.Text));
if (patient != null)
{
textBox2.Text = patient.FirstName;
textBox3.Text = patient.LastName;
}
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
The code line here:
Patient patient = patientSvc.GetPatient(Convert.ToInt32(textBox1.Text));
is where it freezes up. Again, this is the same code that is in the other winform and it works. It's just when using it inside the service itself doesn't seem to work the same way for some reason??
The error it gives is this:
System.TimeoutException: 'This request operation sent to net.tcp://localhost:2202/PatientService did not receive a reply within the configured timeout (00:01:00). The time allotted to this operation may have been a portion of a longer timeout. This may be because the service is still processing the operation or because the service was unable to send a reply message. Please consider increasing the operation timeout (by casting the channel/proxy to IContextChannel and setting the OperationTimeout property) and ensure that the service is able to connect to the client.'
Anyone have an idea on how to get it to work?
This is the other winform code:
using System;
using System.Windows.Forms;
using System.ServiceModel;
using TestService;
namespace TestClient
{
public partial class Form1 : Form
{
IService1 patientSvc = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2202/PatientService"));
NetTcpBinding binding = new NetTcpBinding();
ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
patientSvc = factory.CreateChannel();
}
private void button1_Click(object sender, EventArgs e)
{
Patient patient = patientSvc.GetPatient(Convert.ToInt32(textBox1.Text));
if (patient != null)
{
textBox2.Text = patient.FirstName;
textBox3.Text = patient.LastName;
}
}
private void button2_Click(object sender, EventArgs e)
{
Patient patient = new Patient();
patient.FirstName = textBox2.Text;
patient.LastName = textBox3.Text;
patientSvc.SetPatient(Convert.ToInt32(textBox1.Text), patient);
}
}
}
TestClient code (Program.cs):
using System;
using System.Windows.Forms;
namespace TestClient
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

Got it! Thank to #Eser for the hint :)
private void button3_Click(object sender, EventArgs e)
{
IService1 patientSvc = null;
EndpointAddress address = new EndpointAddress(baseAddress);
ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
patientSvc = factory.CreateChannel();
Thread thread = new Thread(() => sendData(patientSvc));
thread.Start();
}
delegate void SetTextCallback(string text, bool isTxt2);
private void SetText(string text, bool isTxt2)
{
if (isTxt2)
{
if (this.textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
textBox2.Invoke(d, new object[] { text, isTxt2 });
}
else
{
textBox2.Text = text;
}
} else {
if (this.textBox3.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
textBox2.Invoke(d, new object[] { text, isTxt2 });
} else {
this.textBox3.Text = text;
}
}
}
public void sendData(IService1 patientSvc)
{
Patient patient = patientSvc.GetPatient(Convert.ToInt32(textBox1.Text));
if (patient != null)
{
SetText(patient.FirstName, true);
SetText(patient.LastName, false);
}
}

Related

Access Singleton via Named pipe creates second singleton. Events not fired on host side

I have two processes and the second process needs to have access to a singleton in the first process. So I wrote a server that should help sharing the instance.
Something is wrong though, it seems like the client gets its own version of the singleton rather than the original instance.
The minimal example comes in two projects. Here is the client:
Program
using IPCServer;
using System;
using System.Diagnostics;
using System.ServiceModel;
using System.Threading;
namespace IPCEventTest
{
class IPCClient
{
static void Main(string[] args)
{
Process ipcserver = Process.Start("IPCServer.exe");
Thread.Sleep(2000);
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Main Start Connect");
Module module = Connect("WellKnownName"); //this name is used by the host
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Main End Connect");
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Main Start Raise");
module.RaiseEvent(); //raise event should raise within the server process
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Main End Raise");
while (true) ;
}
public static Module Connect(string id)
{
Console.WriteLine("Start Connect");
ChannelFactory<IModuleServer> pipeFactory =
new ChannelFactory<IModuleServer>(
new NetNamedPipeBinding(),
new EndpointAddress($"net.pipe://localhost/{id}")
);
IModuleServer serverProxy = pipeFactory.CreateChannel();
Module ret = serverProxy.GetModule();
Console.WriteLine("End Connect");
return ret;
}
}
}
The following files set up the Host:
Program
using System;
namespace IPCServer
{
class Program
{
static HOST host;
static void Main(string[] args)
{
host = new HOST("WellKnownName");
Module.Instance.myevent += Instance_myevent;
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Server Subscribed to {Module.Instance.id}");
while (true) ;
}
private static void Instance_myevent(object sender, EventArgs e)
{
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Server Event Fired from {(sender as Module).id}");
}
}
}
Module
using System;
using System.Linq;
namespace IPCServer
{
public class Module
{
public static Module Instance { get; } = new Module();
public event EventHandler myevent = delegate { };
public string id;
private Module()
{
var guid4 = Guid.NewGuid().ToString().Take(4);
id = new String(guid4.ToArray());
Console.WriteLine($"Module Constructor {id}");
myevent += Module_myevent;
}
private void Module_myevent(object sender, EventArgs e)
{
Console.WriteLine($"Module Listener {(sender as Module).id}");
}
public void RaiseEvent()
{
Console.WriteLine($"Module Start Raise {id}");
myevent(this, EventArgs.Empty);
Console.WriteLine($"Module End Raise {id}");
}
}
}
Host
using System;
using System.ServiceModel;
namespace IPCServer
{
internal class HOST
{
ServiceHost host;
internal HOST(string id)
{
host = new ServiceHost(typeof(ModuleServer), new Uri[] { new Uri("net.pipe://localhost") });
host.AddServiceEndpoint(typeof(IModuleServer), new NetNamedPipeBinding(), id);
host.Open();
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Host Opened");
}
~HOST()
{
if (host.State == CommunicationState.Opened)
{
host.Close();
}
host = null;
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} Host Destructed");
}
}
[ServiceContract]
public interface IModuleServer
{
[OperationContract]
Module GetModule();
}
public class ModuleServer : IModuleServer
{
public Module GetModule()
{
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} ModuleServer start GetModule");
Module ret = Module.Instance;
Console.WriteLine($"{DateTime.Now.ToUniversalTime()} ModuleServer end GetModule");
return ret;
}
}
}
The example runs and here is the output on my system:
Why am i not getting my Singleton from the server process.
Why is my event not raised in the server.
Edit: The Server opens the host and also subscribes to the singleton. After the client connects it raises the event via member function. Event has two subscribers, one in the constructor and one on the server side. only the Module internal subscription is handled - there is no eventhandling on the server side - no event is fired on the server side. The module listener is triggered but not inside the host process. This event is handled on the client side.
Why am i not getting my Singleton from the server process
Named pipes use Serialization to pass the object from server to client. That means that the client side have to re-run the constructor and copy existing properties.
public string id; is a field so it won't be 'copied' so the random value set by the constructor is left. That's why you have different Ids for the "same" object.
To solve this, you can change this to :
[DataContract]
public class Module
{
[DataMember]
public string id {get; set;}
}
Why is my event not raised in the server.
This is not how WCF named pipes works as you just have a duplicate version a client side. I suggest you to read about Duplex Channel

How to monitor windows services using c#

How can i monitor windows services using c# and i also have to save those services name, started time and services end time using in a CSV file. If any new services started than it should automatically write services name, started time and services end time using in existing CSV file.
In case someone is looking for a solution to this in 2021, you can do this using a service controller, async task and the WaitForStatus() method:
Update: I realized my initial solution would not work so I rewrote it completely:
CLASS DEFINITION
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.ServiceProcess; // not referenced by default
public class ExtendedServiceController: ServiceController
{
public event EventHandler<ServiceStatusEventArgs> StatusChanged;
private Dictionary<ServiceControllerStatus, Task> _tasks = new Dictionary<ServiceControllerStatus, Task>();
new public ServiceControllerStatus Status
{
get
{
base.Refresh();
return base.Status;
}
}
public ExtendedServiceController(string ServiceName): base(ServiceName)
{
foreach (ServiceControllerStatus status in Enum.GetValues(typeof(ServiceControllerStatus)))
{
_tasks.Add(status, null);
}
StartListening();
}
private void StartListening()
{
foreach (ServiceControllerStatus status in Enum.GetValues(typeof(ServiceControllerStatus)))
{
if (this.Status != status && (_tasks[status] == null || _tasks[status].IsCompleted))
{
_tasks[status] = Task.Run(() =>
{
try
{
base.WaitForStatus(status);
OnStatusChanged(new ServiceStatusEventArgs(status));
StartListening();
}
catch
{
// You can either raise another event here with the exception or ignore it since it most likely means the service was uninstalled/lost communication
}
});
}
}
}
protected virtual void OnStatusChanged(ServiceStatusEventArgs e)
{
EventHandler<ServiceStatusEventArgs> handler = StatusChanged;
handler?.Invoke(this, e);
}
}
public class ServiceStatusEventArgs : EventArgs
{
public ServiceControllerStatus Status { get; private set; }
public ServiceStatusEventArgs(ServiceControllerStatus Status)
{
this.Status = Status;
}
}
USAGE
static void Main(string[] args)
{
ExtendedServiceController xServiceController = new ExtendedServiceController("myService");
xServiceController.StatusChanged += xServiceController_StatusChanged;
Console.Read();
// Added bonus since the class inherits from ServiceController, you can use it to control the service as well.
}
// This event handler will catch service status changes externally as well
private static void xServiceController_StatusChanged(object sender, ServiceStatusEventArgs e)
{
Console.WriteLine("Status Changed: " + e.Status);
}
You can list running services using ServiceController or ManagementObjectSearcher.
Here is a sample using the ManagementObjectSearcher :
using System.Management;
...
StringBuilder sb = new StringBuilder();
string format = "{0},{1},{2},{3},{4}";
// Header line
sb.AppendFormat(format, "DisplayName",
"ServiceName",
"Status",
"ProcessId",
"PathName");
sb.AppendLine();
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_Service");
foreach( ManagementObject result in searcher.Get() )
{
sb.AppendFormat(format, result["DisplayName"],
result["Name"],
result["State"],
result["ProcessId"],
result["PathName"]
);
sb.AppendLine();
}
File.WriteAllText(
#"C:\temp\ManagementObjectSearcher_services.csv",
sb.ToString()
);
For getting start and stop times it looks like you have to query the Windows Event Log.
This blog post show how you can monitor the event log to get notified when a service is stopped or started:
https://dotnetcodr.com/2014/12/02/getting-notified-by-a-windows-service-status-change-in-c-net/

Windows service stops right after launching

I have following problem with the windows service I was writing:
When I start the service it stops immediately. When I was using a console app it wasn't crushing. I have no idea what's the cause of this problem.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration;
using System.Configuration.Install;
using WindowsService;
namespace WS
{
[ServiceContract(Namespace = "http://WS")]
public interface INewsReader
{
}
public class NewsReaderService : INewsReader
{
public NewsReaderService()
{
var config = new Config();
var scheduled = new Schedule(config);
scheduled.ExecuteScheduledEvents();
while (true)
{
System.Threading.Thread.Sleep(1000);
int i = 0;
}
}
}
public class NewsReaderWindowsService : ServiceBase
{
public ServiceHost serviceHost = null;
public NewsReaderWindowsService()
{
ServiceName = "NewsReaderWindowsService";
}
public static void Main()
{
ServiceBase.Run(new NewsReaderWindowsService());
}
protected override void OnStart(string[] args)
{
var thread = new System.Threading.Thread(() =>
{
while (true)
{
int i = 0;
System.Threading.Thread.Sleep(1000);
}
});
thread.Start();
serviceHost = new ServiceHost(typeof(NewsReaderService));
serviceHost.Open();
}
protected override void OnStop()
{
}
}
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
{
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "NewsReaderWindowsService";
Installers.Add(process);
Installers.Add(service);
}
}
}
Well, first of all I think your OnStart method is written badly. I can't see the reason for creating a, basicly, empty thread. You should there only initialize service (If necessary), immediately start a new thread that will work for whole time and leave the OnStart method.
Second of all use try catch block, because in my opinion somewhere in there is exception and that's why your windows service stops.
Thirdly see this example WCF Hosting with Windows Service

Sending messages to WCF host process

I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?
You don't need to inherit from ServiceHost. There are other approaches to your problem.
You can pass an instance of the service class, instead of a type to ServiceHost. Thus, you can create the instance before you start the ServiceHost, and add your own event handlers to any events it exposes.
Here's some sample code:
MyService svc = new MyService();
svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();
There are some caveats when using this approach, as described in http://msdn.microsoft.com/en-us/library/ms585487.aspx
Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.
using ...
using ...
namespace MyWCFNamespace
{
class Program {
static void Main(string[] args){
//instantiate the event receiver
Consumer c = new Consumer();
// instantiate the event source
WCFService svc = new WCFService();
svc.WCFEvent += new SomeEventHandler(c.ProcessTheRaisedEvent);
using(ServiceHost host = new ServiceHost(svc))
{
host.Open();
Console.Readline();
}
}
}
public class Consumer()
{
public void ProcessTheRaisedEvent(object sender, MyEventArgs e)
{
Console.WriteLine(e.From.toString() + "\t" + e.To.ToString());
}
}
}
namespace MyWCFNamespace
{
public delegate void SomeEventHandler(object sender,MyEventArgs e)
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class WCFService : IWCFService
{
public event SomeEventHandler WCFEvent;
public void someMethod(Message message)
{
MyEventArgs e = new MyEventArgs(message);
OnWCFEvent(e);
}
public void OnWCFEvent(MyEventArgs e)
{
SomeEventHandler handler = WCFEvent;
if(handler!=null)
{
handler(this,e);
}
}
// to do
// Implement WCFInterface methods here
}
public class MyEventArgs:EventArgs
{
private Message _message;
public MyEventArgs(Message message)
{
this._message=message;
}
}
public class Message
{
string _from;
string _to;
public string From {get{return _from;} set {_from=value;}}
public string To {get{return _to;} set {_to=value;}}
public Message(){}
public Message(string from,string to)
this._from=from;
this._to=to;
}
}
You can define your WCF service with InstanceContextMode = InstanceContextMode.Single.
TestService svc = new TestService();
svc.SomeEvent += new MyEventHandler(receivingObject.OnSomeEvent);
ServiceHost host = new ServiceHost(svc);
host.Open();
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] // so that a single service instance is created
public class TestService : ITestService
{
public event MyEventHandler SomeEvent;
...
...
}

WCF Service host receives null object

Environment: .net 4.6.1 on Windows 10 x64
Problem:
1. WCF Contract implemented with an event.
2. Service host will fire the event every time an event log entry is logged and called by the client.
3. The host application triggers properly however the object (EventLogEntry) does not get posted properly and is always null.
4. I have checked during debug the client side Winforms application passes a instantiated object. This somehow doesn't make it to the
server side.
5. at this Stage both the client and the server are on the same machine.
Question:
Why is object null and how can I fix this?
WCF Service Code:
[ServiceContract]
public interface IloggerWCFServiceContract
{
[OperationContract(IsOneWay = true)]
void WriteEvent(EntryWrittenEventArgs e);
[OperationContract(IsOneWay = true)]
[ServiceKnownType(typeof(EventLogEntry))]
void OnEventWritten(EntryWrittenEventArgs e);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class wcf_logger_servicebase : IloggerWCFServiceContract
{
public event EventHandler<EntryWrittenEventArgs> eventwritten;
public void OnEventWritten(EntryWrittenEventArgs e)
{
if (eventwritten != null)
this.eventwritten(this, e);
}
public void WriteEvent(EntryWrittenEventArgs e)
{
OnEventWritten(new EntryWrittenEventArgs(e.Entry));
}
}
Wcf Winforms Server code:
wcf_logger_servicebase loggerWCFService = new wcf_logger_servicebase();
ServiceHost loggerServiceHost = new ServiceHost(loggerWCFService, new Uri(loggerGlobalStatics.namedPipeServerAddress));
loggerWCFService.eventwritten += new EventHandler<EntryWrittenEventArgs>(eventhandler_entryWritten);
.....
loggerServiceHost.AddServiceEndpoint(typeof(IloggerWCFServiceContract), new NetNamedPipeBinding(), loggerGlobalStatics.namedPipeServerAddress);
loggerServiceHost.Open();
......
private void eventhandler_entryWritten(object sender, EntryWrittenEventArgs e)
{
--->textBox1.Text += e.Entry.ToString() + "\r\n" ;
}
WCF Winforms Client code:
ChannelFactory<IloggerWCFServiceChannel> loggerChannelFactory;
IloggerWCFServiceChannel loggerServiceChannel = null;
wcf_logger_servicebase loggerWCFService = new wcf_logger_servicebase();
EndpointAddress serverEndpoint;
System.ServiceModel.Channels.Binding binding;
public client()
{
InitializeComponent();
serverEndpoint = new EndpointAddress(new Uri(loggerGlobalStatics.namedPipeServerAddress));
binding = new NetNamedPipeBinding();
loggerChannelFactory = new ChannelFactory<IloggerWCFServiceChannel>(binding, serverEndpoint);
loggerChannelFactory.Open();
loggerServiceChannel = loggerChannelFactory.CreateChannel();
loggerServiceChannel.Open();
....
private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
{
loggerServiceChannel.WriteEvent(e);
}
The reason is that EntryWrittenEventArgs has no setter for Entry.
See this SO question for more details.
Why not just send Entry directly without encapsulating it in EntryWrittenEventArgs?

Categories

Resources