Auto run a method in a webservice on startup - c#

I want to create a web-service that run a specific method on startup.
this is the service's interface:
namespace MyClass
{
[ServiceContract]
public interface IService
{
[OperationContract]
string getData();
}
}
and on the service itself i want a specific method (not one of those) to run when the service loads (or deployed to IIS). is there a way to do so?

You need to be clear what really happens when a WCF service is hosting in IIS.
IIS provides a service host that loads on demand
when a request comes in, IIS instantiates the service host, which in turns instantiates an instance of your service class, passes it the parameters from the request, and then executes the appropriate method on the service class
As such, there is no point in time when the "service loads" and then just lingers around in memory. The "service" isn't just loaded when IIS starts up and then would be "present and ready" at all times...
So where do you want to plug in??
when the service host loads in IIS? In that case, you'd have to create your own custom service host and register it with IIS so that IIS would use your custom host instead of the WCF default service host
when the actual service class is instantiated to handle the request? THen put your logic into the constructor of your service class - it will be executed each time a service class is instantiated to handle a request

Though this might not be exactly what you want, you could use the class's constructor, perhaps:
public class Service : IService
{
public Service()
{
//code here will execute when an instance
//of this service class is instantiated
}
string getData() { ... }
}
It would be more clear if you could inform us of the method you wish to call, and any surrounding information about it, so that you don't get ill-advice. Specifics are nice.

Here's where I put some code in order to get (and cache) data on the webservice start (in VB). You do need to trigger the service by navigating to any valid or invalid
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
'Run this method on startup to cache the addresses
Address.GetAll()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
End Sub
End Module

Related

State inside self-hosted WCF service being lost with InstanceContextMode.Single

I am using WCF service and self hosting it as not everything is contained within the service itself (some external events are happening outside of the service):
WCF Service and I am self hosting it in a C# Console App. When WCF clients conncet they call the Login function, and I (try!) to store their callback via GetCallbackChannel
3rd party DLL which calls my console back via a delegate on a different thread from the library
On this console callback I then call in to the WCF service who pool which is then passed on to the WCF service who then broadcasts to all connected clients via a callback contract.
All is fine with the client connecting, calling Login, and I save the callback interface object.
However when I access the code from my service, i find it is an entirely new object and my _endPointMap is empty (despite me storing it in the Login method which is called by the client):
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service : IService, IEndpointNotifier
{
public readonly TwoWayDictionary<string, IClientCallback> _endpointMap = new TwoWayDictionary<string, IClientCallback>();
// called by WCF client when they click the login button - it works
public void Login(string username)
{
var callback = OperationContext
.Current
.GetCallbackChannel<IClientCallback>();
_endpointMap.AddOrUpdate(username, callback);
list.Add(username);
}
// called by the WCF self-host console app
public void IEndpointNotifier.Notify(string info, string username)
{
// at this point my list _endpointMap is empty despite
// having received a Login previously and adding to the
// list. so i am unable to call my clients back!!
_endPointMap.Count(); // is 0 at this point?!!
}
}
My main console app starts up the service fine also as below:
static void Main(string[] args)
{
var service = new Service();
var host = new ServiceHost(service);
// between the above line and the task below calling
// service.Notify I click a number of times on client
// which calls the Login method
Task.Run(() =>
{
for (var i = 0; i < 3; i++)
{
Thread.Sleep(10000);
// at this point, service seems like a new object?!
// any data saved in the list member will be lost,
// and will only see the single entry from time of
// construction
service.Notify("hi","bob");
}
});
Console.ReadLine();
}
Questions please
The object seems totally different to the one that was modified in a previous operation (on login from client) - is there any way to tell what service object I am actually looking at (equivalent to the old C++ days and looking at the address pointer for this)?
The singleton attribute seems to be ignored [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] Any ideas what I am doing wrong (why the internal list variable keeps getting reset)?
The WCF service cannot be self contained. How does one achieve communication between WCF self-hosted app and the WCF service according to best practice or is this abusing WCF and what is was designed for (when considering scopes etc)?
I set the breakpoint in the constructor with some dummy values. That breakpoint is only ever hit the first time when i construct it. When i go in to the object via the service.Notify method although the object seems new (members are empty) the constructor breakpoint is not hit - how so?
I have hosted the 3rd party app behind a static global member variable that I control. So I am responsible for all communication and state and cleanup between the 3rd party lib and the normal wcf calls. I am responsible for thread lifetimes for the 3rd party app. If I create them I have to close them. Holding references in my own lists.
It is like it is a separate app but they just happen to be in the same process space. All communication to and from the 3rd party app is controlled by me formally.
You will probably need a thread that looks for completed or abandoned 3rd party objects after usage to kill them your self outside of normal wcf msg processing.
This lets the wcf part be a normal threaded (thread pool) concept with no special declarations.
side note:
I would take out the loop and make it two lines in your simple model.
service.Notify("hi")
Console.ReadLine();
This will expose your object lifetime details instead hiding them for 3 seconds.
I found why the values were not being saved... my WCF client proxy was connecting to the VS WCF Service Host and not my host in the code!
I noticed this when I saw the WCF Service Host running in the service bar tray.
I disabled WCF Service Host starting up for the WCF .svc service by right clicking on the WCF Project -> Properties -> WCF Options -> unticked Start WCF Service Host when debugging another project in the same solution

Having WCF service proxy configurable

I am writing a basic WPF GUI to connect to a WCF service and consume an interface. So far I have connected to the test system by creating a service reference, putting in the URI for the test service I want to consume, it finds the interface and creates the proxy via service reference for me.
What I want this to do when you run the GUI app is for the user to be able to pick an environment - development, test or production and for the GUI to then connect to the appropriate WCF service depending on the environment selected.
How can I do this?
You can overwrite the Endpoint like this:
client.Endpoint.Address = new EndpointAddress(GetAddressForCurrentMode())
The other way you could to it, is to write a method, maybe an extension method, that accepts the service contract and the implementation class. Further more it either accepts a configuration name, or an endpoint:
public static TClient GetServiceClient<TClient, TContract>(string endpoint)
where TClient : ClientBase<TContract>
{
// Construct client
}
To construct the client, use one of BaseClient<T> overloads (from MSDN).
To then consume the client, just use the method above as normal:
using(var client = ServiceInterop.
GetServiceClient<MyClient, IMyContract>("http://foo.bar"))
{
// Consume client
}

When Will the Default Constructor of Service.svc in a WCF Service is executed?

Here is a sample code
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class Service : IService
{
public Service()
{
// here I am getting value from web.config
// using configurationManager which will be
// changing frequently
}
//Method1
....
//Method2
.....
}
When will be the constructor of my service will be executed ?
During the First request or On every request ?
afaik the constructor is called for every request/call to the service.
Also, when the web.config is changed the application pool will recycle if your application is hosted in IIS.
If you consume/call your WCF service through browser like below then every call create new object of service so execute your service default constructor.
Browser Call: .../pricedataservice/DataService.svc/web/GetHistoryData
but if you call service via adding reference to other project then it would be call/execute constructor only when you create object of service

How would I add a WCF service to an existing winforms application?

I have a winform application that handles some data entry and billing. I'd like to add a WCF service that is accessible over the local LAN only. I'd like my billing program to query my database and fetch some data for the client. It is important that this be done in the -same- program instead of creating another.
My question is it difficult to setup a WCF service like this where I'm starting from an existing winform application instead of creating a fresh WCF service. Is it a simple matter of putting the right using directives or is something else fundamentally missing since I didn't set it up as a WCF service from the get go?
Another concern is do I need to worry about threading or is that automatically handled by the WCF service? For instance, if 10 computers all query my winforms application at the same time will WCF seamlessly handle that or I do I need to implement additional functionality to handle this?
Thanks for reading
Basically, to create a WCF service, you need three things:
a service contract (typically expressed as a .NET interface) to define the methods the service provides. This also includes what datatypes the methods expect (and possibly return)
[ServiceContract(Namespace="http://services.yourcompany.com/Service/2012/08")]
interface IMyService
{
[OperationContract]
SomeReturnType ThisIsYourMethod(string input, int value, .....);
}
[DataContract(Namespace="http://data.yourcompany.com/Service/2012/08")]
public class SomeReturnType
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
a service implementation that creates the actual service code to be called. This is just a plain .NET class the implements the service contract
public class MyServiceImplementation : IMyService
{
SomeReturnType ThisIsYourMethod(string input, int value, .....)
{
/// .... do some processing, fetch data etc.
return ......
}
}
a service host to actually host the WCF runtime and spin up the whole WCF processing; this is a ServiceHost instance (or derived class) that will be able to host your service. This class needs to be instantiated and opened somewhere in the startup process of your Winforms application. Once the service host is open, your services are available to be called from the outside world. You'll need to make sure to close the service host when your Winforms application is closing down.
and you might need - in addition - some configuration settings in your app.config file to define what endpoints (address, binding, contract) your WCF service offers up to the world.
So this is really quite simple - just create those items in your Winform project, and you're done.
Please look at this article Hosting and Consuming WCF Services
Windows service hosting the WCF ServiceHost (example from this article)
using System;
using System.ServiceModel;
using System.ServiceProcess;
using QuickReturns.StockTrading.ExchangeService;
namespace QuickReturns.StockTrading.ExchangeService.Hosts
{
public partial class ExchangeWindowsService : ServiceBase
{
ServiceHost host;
public ExchangeWindowsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Type serviceType = typeof(TradeService);
host = new ServiceHost(serviceType);
host.Open();
}
protected override void OnStop()
{
if(host != null)
host.Close();
}
}
}
Another concern is do I need to worry about threading or is that
automatically handled by the WCF service? For instance, if 10
computers all query my winforms application at the same time will WCF
seamlessly handle that or I do I need to implement additional
functionality to handle this?
I think wcf will easily handle this load. But it depends on operations that you want to do on it.
For services hosted as windows services and web-services, your clients also need a proxy class to gain access to exposed contract members.

Refuse the connection to a service

I would create a WCF service with some methods. One of these methods (that is, the Connect method) should be the first to be called in order to use the service: in other words, before you can use all other methods of service, must be called the Connect method. For this reason, I defined it with IsInitiating property set to true, and I have defined the other methods with this property set to false.
In addition, the node offering the service must be able to refuse the connection request from another node (for example, if other nodes are already using the service): is there a way to prevent the use of the service?
Thanks a lot!
Well, sure.
First understand that by default, WCF services are an "instance-per-request" construct; The HttpApplications that IIS maintains in the app pool will "new up" a copy of your service contract class, make the call pertaining to the request, then the object will go out of scope and be destroyed. You can override this by stating that your service should run in "instance-per-session" mode:
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyServiceContract
{
...
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyServiceImplementation: IMyServiceContract
{
...
}
Now, when your service is called, a "session" is established between client and server, and a single copy of your class will be created and remain in memory for the life of that session (unless the app pool is refreshed, which can happen automatically or by a manual action within IIS). This is the first step.
Now, you can do one of two things:
Simply check in any method besides Connect() whether Connect() has been called on this instance since its creation. If not, throw out.
Have the Connect() method return some instance-scoped token or GUID that the client must then pass to all other method calls. If the GUID the caller provides doesn't match the one kept in instance memory, then throw out of the method.
Understand that sessions can time out between requests. If this happens, your current instance will leave scope and be destroyed, and a new instance will be created to handle subsequent requests. I would thus opt for the second option even though the system can identify instances based on their session; the GUID ensures that both the client AND service instance have not changed since the last call.

Categories