Weird Service Behavior - c#

To give you some background, I've been trying to modify our local hosting arrangement so that an existing WCF service is hosted in IIS locally, dispensing of the current host console application.
I created a new WCF project which contains nothing more than a svc and web.config.
The svc references a servcie factory in the service assembly and the web.config is at the low end of complexity. This mimics how the service is deployed in our dev/test/uat/pre-prod environment.
The service has a service behavior that sets the certificate validator during the call to AddBindingParameters - this has worked for longer than I have been working at the company.
The problem is locally, AddBindingParameters gets called numerous times, but ultimately with the channel state set to "opened" and the service credentials object set to readonly, mushroom clouding.
I thought it may be environmental but I've scoured IIS looking for the "set to evil" flag, no luck. I tried deploying the service (file copy) to a known good server - no good, same issue. Environmental, I say. So I tried copy a known good service locally (file copy) - no good. OK, WTF. Checked the installer (the service is installed with a WiX installer) - it does create the virtual directory but nothing stands out.
I know I could move the authorisation logic into an authorisation policy but I'm reluctant to change something that has worked for so long without understanding the underlying issue.
At this point I'm ready to give up unless I get some good ideas!

Related

Connecting a Test project to a WCF Service Automatically

I have written a WCF web service (not a web site, just JSON over HTTP) intended to run in Azure. I need to write tests for it.
I know how to do this, but it seems amateurish:
Run the web service,
Copy the root URL (e.g. http://localhost:81/)
Apply the root URL to my test project,
Run the test project.
I would like to be able to do this:
Hit F5
--> web service starts running
--> tests start running, automatically finding where IIS decided to run the service.
Is there a way?
There are 2 ways you can do this. Since you're using Windows Azure I assume you're using the emulator. Using the emulator means that the RoleEnvironment is available and you can get a list of roles, their instances, and their endpoints that are available.
var endpoint = RoleEnvironment.Roles["WebRole1"].Instances.First().InstanceEndpoints["Endpoint1"];
var siteUrl = String.Format("{0}://{1}", endpoint.Protocol, endpoint.IPEndpoint);
This code will get the role named WebRole1, get the first instance on this role (you could use this to test if your web service supports load balancing) and get the InstanceEndpoint. The instance endpoint will give you all info you need like protocol (http/https) and the IP/port (these are things you configure in the ServiceConfiguration).
Note: This also works for processes running outside the emulator (like your test project). The only thing you'll need to do is reference Microsoft.WindowsAzure.ServiceRuntime.
Besides that you can also try to use the ServerManager class to find the current sites running in IIS, but I don't think this will work if you're running in IIS Express (which is also possible if you're working with Azure).
Fix the port number of the WCF project: go to the properties of your project, set "use dynamic ports" to false then specify a fixed number, for example 81.
Specify multiple startup projects in your solution: right mouse button on solution: select "set startup projects", then check the radiobutton "multiple startup projects", include your WCF service project in the startup list.
I hope this meets your needs...

What determines your USERPROFILE Environment Variable when launching a .NET app

I have a .net/C# application when launched on a test server running VMWARE / Windows Server 2008, receives a USERPROFILE Environment Variable pointing to C:\windows\system32\config\systemprofile, but other applications seemingly built in a similar fashion inhert the correct value of C:\Users\{username}.
A slight twist - the application receives the correct value when run locally on my development machine. So I'm thinking this is a profile/registry issue with some combination of setting in my app.
The issues is manifested when you attempt to open an OpenFileDialog or similar. You get the exception "Location is not available: C:\Windows\system32\config\systemprofile\Desktop refers to a location that is unavailable..."
Any ideas?
UPDATE: The application is WPF running web services against IIS via WCF. Locally in development I am using IISExpress. I've found that after touching the WCF services in the client, the application inherits the APPDATA and USERPROFILE of the IIS AppPool the services are running under. If I adjust the AppPool values to use my user account instead of ApplicationPoolDefault and set LoadUserProfile = true - things work. Obviously this is a bad thing. As an alternative, I cache off the environment variables when the WPF app runs, and after it initially connects to WCF, I reset the variables. This appears to get around the issue but I'd like to solve it a better way but I have no idea what is influencing this behavior in WCF and my IIS Services.
It might have to deal with what account the web app is running under in IIS. You can change it from the default "Network Service" account to an actual user account.

Auto Upgradable WCF service

I'm working on application that does some tests on Windows Servers. Front end of application connects to small application installed on each server via WCF.
Problem with this flow is that when i make slight update to small application on server or even change WCF server signature i should re-install this application again on numerous servers.
How did you tackled such problem or would advice to ?
WCF handles most compatibility issues without complaining such as adding new parameters to a method (old clients still work, new parameters are initialized as default). Removing params also does not affect the client (extra params ignored). Other changes and how to deal with them can be found here: http://msdn.microsoft.com/en-us/library/ff384251.aspx.
For deployment, as stated in another answer click-once is a quick way to have client machines auto-update, if you prefer more of a push model, you may be able to setup msdeploy to push a build out to the other machines (provided you have access to them).
Hope this helps.
could you use a more restful service, this would give you a little more flexibility to change?
Could you use click once deployment, to automatically redeploy when the app changes (if it is an app)?
http://msdn.microsoft.com/en-us/library/ms730203.aspx

Best Practice for storing settings for a .NET Windows Service: Service Property Settings, Serialization,

I am working on a .NET Windows Service where I am trying to store settings that will be used when the service is started and while it is running. I have searched through posts on SO and found that using the Settings in the properties of the project is great for use with console and winforms applications. However, Google and SO are silent when it pertains to storing these settings with a windows service.
Does anyone one know if it is proper to use these settings in a .NET service? If not, is Serialization my next best choice? Has anyone had practical uses for settings in a service and found that it is best to use a specific method?
I've had problems with using Settings.settings. For instance, if you need to make changes at run-time, there can be problems with the settings being overridden by those that were initially stored in the settings.settings file as opposed to what's shown should be stored per the app/web.config. Consequently I make all my Web Service proxy settings "static" in the properties and pull them manually from the app/web.config via a helper method and programmatically set them. This circumvents any problems.
An example of the issue we had: I pointed my development machine to a web service on a test server to test the code that consumed the web service. When the code was moved to our test server, no problems manifested - as the test server was still pointed at the same web service on the same test server. However, when we moved the application to the production server and reconfigured the web.config to point at the production server we started getting screwy results. It took quite a bit of effort to pinpoint that even though we had reconfigured the application to point at the production server's implementation of the web service, it was still connecting to the web service on the test server. It wasn't until we changed settings.settings on my development machine and recompiled the application that it worked. Further to this, we also noted that if there were DNS problems connecting to the production web service, rather than fail, it fell back to the original settings that were specified in the settings.settings from when we created the web service proxy in our application - the proxy generator actually hard codes them. Consequently when there were network outages, instead of getting easily diagnosed connection failures, it simply fell back to the test server and we started getting incomprehensible data issues. I'm not sure if this was a known problem or if it's been fixed, but it's certainly something you should be aware of.
Consequently, since then, I've always set the service properties to static and used a helper method to read the correct settings from the web.config directly and written them programmatically as this seems to circumvent the problem.
It may seem like the problem I had has nothing to do with yours because I was using Web Services which isn't anything to do with Windows Services, however, any environment where you need to be able to change the settings at runtime without having to recompile could be affected by this issue, so you should be aware that if you run in a Dev/Test/Production environment or indeed any environment where you need your app to be reconfigured at run-time (i.e. without having to recompile) that you can get unpredictable results when using settings.settings. Beware.
I normally use the registry to store information I need in my service i.e port etc.
string lsbkey = #"Software\mycompany\adas";
RegistryKey adaskey = Registry.LocalMachine.OpenSubKey(lsbkey, false);
try
{
object regip = adaskey.GetValue("IP");
object regport = adaskey.GetValue("PORT");
localip = regip.ToString();
localport = int.Parse(regport.ToString());
}
catch (NullReferenceException ne)
{
localip = null;
localport = 0;
writelog(#"Aborting Service, IP or PORT doesn't exist in \local machine\software\mycompany\adas : "+ne.Message);
status = 0;
}
I use the Settings.settings stuff for storing the config for my services and I've had no problems. Just the usual that the user settings that are changed will be stored in it's usual obscure location that you have to hunt around for if you want to edit them by hand.
I dont see any reason not to use Settings in the properties of the project as you would for a winForms app. We do this, and it works fine.

Passing a Windows Service Parameters for it to act on

I want to turn a program I have into a service so I can use it without logging it. Basically what it does is it backs up specified folders to a specified location using SSH. However the problem I'm running into is I don't know how to tell it these items. I only know how to start, stop, and run a custom command with only an integer with a parameter.
How can I do this?
Windows Service, not a Web Service
edit: The folders it backs up will not remain consistent and will be updated at every runtime
You can instantiate your service and pass command line arguments using the ServiceController class.
using (ServiceController serviceController = new ServiceController(serviceName))
{
string[] args = new string[1];
args[0] = "arg1";
serviceController.Start(args);
}
"arg1" will then be available as regular command line arguments in main() when Windows starts up the service.
I see that you (or someone) voted Sebastian Sedlak's answer down, because he mentioned hosting a WCF Service in the Windows Service. Your reply was
It's in nice bold lettering in the question. Not a Web Service, therefor WCF is out of the question
I think you misunderstood what he meant. He wasn't talking about a Web Service. He was talking about hosting a WCF Service within your Windows Service.
It's far from the same thing. You can host a WCF Service within any Windows (Forms/Console/Service) application. The point of doing so, is that the application is then reachable for communciation via its internal WCF Service, in the same fashion as you can communicate with a Web Service (you can also host WCF Services in IIS, btw, which would then make them "Web Services", in the sense you seem to be referring to).
In a Windows Service, this means you can send any command to it and also get any information you want from it - while it's running.
In fact, I am working on a project right now, which is a Windows Service that I need to be able to contact and pass commands to - and get information from - at runtime. For example, I want to be able to tell it where to store certain things, what to log, to have it reset/restart - and poll it for status messages. I do this by hosting a WCF Service inside the Windows Service. That WCF Service exposes a set of methods, that in my case includes receiving commands and returning status information. So when the Windows Service is running, I can contact it (even remotely), via its built-in WCF Service and tell it what to do.
This an extremely easy thing to implement, and in the case of Windows Services, can provide you with a much richer interface to the Service than through the basic standard commands.
However, you specified that you wanted your Windows Service to receive its folder settoings each time it starts up, which makes such a passive setup less than ideal (as it would be unable to do anything until you passed it the right folders).
One way to deal with this (using a hosted WCF Service), would be to have the Windows Service running all the time (i.e. automatic startup). Its default state would be idle. Then you could issue it a "start processing"-command, feeding it the correct folders to work on (through a call to the corresponding WCF Service method). Similarly, the WCF Service would expose methods giving you the status of the application (current folder, progress, busy/idle etc). Once the processing is done, it would go back into the idle state, waiting for the next set of folders to be supplied to it.
Doing it this way would make it very easy to control remotely - you could even make an online administration panel for it, accessible from anywhere.
The issue, is that, while passing in parameters is not difficult, when the machine restarts and windows tries to restart the service, those parameters are not there. they only exist when someone starts the service from the command line.
for example. I have a windows service which hosts a WCF service. I want the users to be able to specify a non-default port number for the WCF service to listen on. They do this by starting the windows service like so... MyService -port:xxxxx
Which works fine, until the server is rebooted, then windows restarts MyService (but without parameters) and the wcf service defaults to original port #
Any service is capable of receiving command line arguments at start-up.
Would it be possible to use a configuration file to specify these items?
Store the service's startup parameters in the registry: and then, when the registry starts, it should read its startup parameters from the registry.
Windows services have executables like any other. I believe you can write it to accept command-line parameters and specify those parameters in the Windows Service configuration. You can also have it read a config file. If you're using .NET, there are config file classes in the framework.
Why not just Host a WCF Service in the Windows Service to obatain such "admin" functions?
(Remoting is also possible)
RE: config file.
Of course a config file can be used.
And the file can be changed while the service is running.
This would be a nice solution if the config file changes in fact.
All my services use an XML config file, wrapped in a class for easy reuse.
The wrapper has an option to monitor the XML file using fileMonitor for changes, optionally refreshing the content of the config file automatically, and finally raises an event to the service class.
The service then has the option of "resetting" itself as needed to incorporate the new values in the XML configuration file.
Placing configuration into the registry has a few issues:
Security (ie: installer being granted access), depending on what tree is used
The service will not be aware of changes
Portability - although minor as the install should setup registry settings
Where an XML file is easy to copy, edit, share, view and understand.
Throw in some good COMMENT blocks and a detailed XSD file, and it becomes a source of good documentation too.
Look into XPath for easy navigation and extraction of values within the XML file.
$0.02
... david ...
Concerning the app.config file - I'm rather sure that your service will read and use those files as I write all my windows-services this way ;)
So just put everything you need in the app.config under "application" (not user) and put allway edit the "yourname.exe.config" in the folder where you "InstallUtil" the service from.

Categories