How to configure WCF in a separate dll project - asp.net

I'm developing a web application (ASP.NET 3.5) that will consume a number of web services. I have created a separate dll-project for each web service: these projects contains the service reference and client code.
However, the calling website MUST have the <system.serviceModel> information (the <bindings> and <client> nodes) in it's web.config, even though this information is also in the dll's app.config file! I have tried copying the serviceclass.dll.config over to the bin directory of the website, but this didn't help.
Is there any way to centralize the configuration of a WCF client?

I've only limited WCF experience, all with BasicHTTP bindings. But I'm allergic to WCF's xml files and have managed to avoid them thus far. I don't recomend this generally but I put the configuration details in my apps existing configuration store and then apply them programatically. E.g. With a Web service proxy I use the constructor for the Client that takes 'bindings'and 'endpoint' and programatically apply the settings to the bindings & endpoint.
A more elegent solution appears to be descibed here: Reading WCF Configuration from a Custom Location, but I haven't tried it yet.

From my experience, library projects never read app.config.
So you can really delete the file because it is not used. The library's host configuration is read instead, so that is the only place the endpoint and binding configuration should be.

It's possible to forgo xml config and build up the Binding and Endpoint classes associated with the service in the constructor or a custom "Service Factory". iDesign has some good information on this:
http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11
(See In Proc Factory)
In their approach, you set attributes on your services to specify at a high level how they should work (ie [Internet], [Intranet], [BusinessToBusiness]), and the service factory configures the service according to best practices for each scenario. Their book describes building this sort of service:
http://www.amazon.com/Programming-WCF-Services-Juval-Lowy/dp/0596526997
If you just want to share configuration XML config, maybe use the configSource attribute to specify a path for configuration: http://weblogs.asp.net/cibrax/archive/2007/07/24/configsource-attribute-on-system-servicemodel-section.aspx

Remember that a configuration file is is read by an executable that has an entry point. A library dll does not have an entry point so it is not the assembly that will read it. The executing assembly must have a configuration file to read.
If you would like to centralize your web configs then I would suggest you look into nesting them in IIS with virtual directories. This will allow you to use the configuration inheritance to centralize whatever you need.

There are 2 options.
Option 1. Working with channels.
If you are working with channels directly, .NET 4.0 and .NET 4.5 has the ConfigurationChannelFactory. The example on MSDN looks like this:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "Test.config";
Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration(
fileMap,
ConfigurationUserLevel.None);
ConfigurationChannelFactory<ICalculatorChannel> factory1 =
new ConfigurationChannelFactory<ICalculatorChannel>(
"endpoint1",
newConfiguration,
new EndpointAddress("http://localhost:8000/servicemodelsamples/service"));
ICalculatorChannel client1 = factory1.CreateChannel();
As pointed out by Langdon, you can use the endpoint address from the configuration file by simply passing in null, like this:
var factory1 = new ConfigurationChannelFactory<ICalculatorChannel>(
"endpoint1",
newConfiguration,
null);
ICalculatorChannel client1 = factory1.CreateChannel();
This is discussed in the MSDN documentation.
Option 2. Working with proxies.
If you're working with code-generated proxies, you can read the config file and load a ServiceModelSectionGroup. There is a bit more work involved than simply using the ConfigurationChannelFactory but at least you can continue using the generated proxy (that under the hood uses a ChannelFactory and manages the IChannelFactory for you.
Pablo Cibraro shows a nice example of this here: Getting WCF Bindings and Behaviors from any config source

First of all class libraries (DLLs) do not have their own configuration, however they can read the configuration of their host (Web/Executable etc.). That being said, I still maintain an app.config file on the library projects as a template and easy reference.
As far as the service configuration itself is concerned, WCF configuration can make somebody easily pull their hair out. It is an over-engineered over-complicated piece. The goal of your applications should be to depend least on the configuration, while maintaining flexibility of deployment scenarios your product is going to come across.

Related

how to deploy flex app using different web service urls?

Is there some sort of configuration settings in FlashBuilder 4.5 where you can easily switch between webservice urls? Right now I have to delete and recreate the web service every time I switch from local to production and vice versa.
The need/requirement is this – Since I work in a startup, we keep changing servers, and their IP addresses. And being a service oriented application – I need to be able to edit the webservice endpoints in my Flex application in a easy manner every time this happens.
My Solution for this -
Assumption is that my webservice endpoint looks like this -
http:////ListAllServices/
1) Create a file config.xml in a folder named “settings” that sits in the root folder of your Flex application – outside the “src” folder. And the config.xml will be a simple xml file of the following format -
localhostTestFlexApp
At the end of this exercise the directory structure of your flex source code will look like this -
flex_src(root of the source code)
-com(some source folder)
–testapp
—view
—
-images
-settings
–config.xml
-appName.mxml
2) Now in your application code, setup a HTTPService object either in mxml or action script. Set the url of that object to this value- “settings/config.xml” – And the above xml fiel containing the current settings will be loaded into memory .
Now you can store these values in a singleton object and construct your Webservice call at runtime.
And whenever you want to move this to a new server in production, edit the tag of your config.xml and you should be good to go.
And this can be automated as well via the EnvGen ant task.
This is not the best way but yes it is very helpful while switching among servers.
Alrighty... The way I was doing it before in fact worked. The problem was browser caching.
For the benefit of others I modified the subsclass for the generated service and replace the wsdl variable with whatever endpoint I need.

Using web services in different environments

We have a series of web services that live in different environments (dev/qa/staging/production) that are accessed from a web application, a web site, and other services. There are a few different service areas as well. So for production, we have services on four different boxes.
We conquered the db connection string issue by checking the hostname in global.asax and setting some application wide settings based on that hostname. There is a config.xml that is in source control that list the various hostnames and what settings they should get.
However, we haven't found an elegant solution for web services. What we have done so far is add references to all the environments to the projects and add several using statements to the files that use the services. When we checkout the project, we uncomment the appropriate using statement for the environment we're in.
It looks something like this:
// Development
// using com.tracking-services.dev
// using com.upload-services.dev
// QA
// using com.tracking-services.qa
// using com.upload-services.qa
// Production
// using com.tracking-services.www
// using com.upload-services.www
Obviously as we use web services more and more this technique will get more and more burdensome.
I have considered putting the namespaces into web.config.dev, web.config.qa, etc and swapping them out on application start in global.asax. I don't think that will work because by the time global.asax is run the compilation is already done and the web.config changes won't have much effect.
Since the "best practices" include using web services for data access, I'm hoping this is not a unique problem and someone has already come up with a solution.
Or are we going about this whole thing wrong?
Edit:
These are asmx web services. There is no url referenced in the web.config that I can find.
Make one reference and use configuration to switch the target urls as appropriate. No reason to have separate proxies at all.

Problems with Web.config and App.config

Intro:
Normally we store ConnectionStrings and some other settings (<appSettings> <add key...) in the Web.config or App.config.
My scenery:
Web application using factory pattern
with direct injection to read data
providers.
In the web.config I have the key
that tells me which DLL (provider)
will I use to retrieve my data.
I can have more than one provider
(each DLL will be a provider for MS
SQL, MySQL, or get the data from
some SOA service).
Each DLL has his own name (ID and namespaces) and will need to have is own
configurations (dataconnections,
service urls, etc...) , the first
idea is to write then in the
app.config.
Problems:
#1 - The website is running (runtime) I need to change the Data Provider, how can I do this? Somehow the default value written in the Web.config will be changed.
My objective is to be able to have multiple providers (and during runtime: add/delete providers and change configurations) - this leads me to my second problem:
.
#2 - Each Data Provider has custom configurations and App.Config files do not work with dll assemblies, only executables. This means that I need to write then on my Web.Config (I do not like this option, because once again I am updating my web.config in runtime). how can I solve this?
I am trying to avoid to write a custom settings XML file. My ideal solution is to deploy somehow the DLL and DLL.config per each provider. And once again during runtime I may need to change this configuration values.
.
Ok guys, while I was waiting for some help I put my hands to work and I was able to find a good solution (in my opinion of course :P).
Let me share it with you:
So, I have one web application, or one console application, or some other kind of application, and lots of class library, and I need to store informations (different per Visual Studio project) that will change during runtime.
Storing this information inside the Web.config or App.config is not a good idea for the many problems it takes.
The other way I see it is to have one XML config file per project.
Each application will read his own XML and add it to the Cache with CacheDependency (will expire when the XML config file is updated). This way we will not need to read the configuration all the times, and we also know when the configuration is changed.
IMO THIS IS THE FASTEST AND EASIEST WAY TO SOLVE THE PROBLEM, no need to use 3rd party frameworks (neither the time it takes to learn/program it).
.
Example code:
protected void Page_Load(object sender, EventArgs e)
{
DBConfiguration cachConf;
cachConf = Cache["cachConf"] as DBConfiguration;
if (cachConf == null)
{
cachConf = new DBConfiguration();
XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Request.PhysicalApplicationPath + "bin/MyConf.xml");
XmlNodeList xnl = doc.GetElementsByTagName("username");
XmlElement xe = (XmlElement)xnl[0];
cachConf.Username = xe.InnerText.ToString();
xnl = doc.GetElementsByTagName("password");
xe = (XmlElement)xnl[0];
cachConf.Password = xe.InnerText.ToString();
Cache.Insert("cachConf", cachConf,
new System.Web.Caching.CacheDependency(
HttpContext.Current.Request.PhysicalApplicationPath + "MyConf.xml"),
DateTime.Now.AddMinutes(60), TimeSpan.Zero,
System.Web.Caching.CacheItemPriority.Default,
new System.Web.Caching.CacheItemRemovedCallback(
CacheItemRemovedCallBack));
}
LabelUsername.Text = cachConf.Username;
LabelPassword.Text = cachConf.Password;
}
private void CacheItemRemovedCallBack(string key, object value, CacheItemRemovedReason reason)
{
//Response.Write("Hello world");
}
You could store the credentials in a secondary config file referenced from web.config as follows:
<appSettings file="AppSettings.config"/>
You would still need to be careful to avoid editing conflicts on the external file.
Problem 1 - Runtime changes:
The solution that Microsoft hopes you apply to this type of problem is to simply keep the web server stateless. When an ASP.NET application recycles, it lets existing requests complete new requests start on a new process. For background, read about IIS Process Recycling. A change to web.config recycle the worker process, but users will not notice this (unless you keep state in the web server process). That's the MS design.
If you want to monitor for changes without recycling a process, you'll want something other than default web.config behavior. An example that comes to mind are cruise controls project files. They have a component that maps objects to and from xml, using that, you can use the FileSystemWatcher class to monitor for changes.
Problem 2 - Custom configurations:
It sounds like you have components from different libraries that have different dependencies. Your main assembly needs a means to instantiate a service, with a given set of dependencies. The MS data provider model is cool, but not this cool.
To be this cool, use an inversion of control container, because this is exactly what they do. I like autofac (because I like the Philip K Dick reference), but castle windsor is great.
Now, if you are talking about changes databases or data providers on the fly, it may be that configuration is not the right place. If your are reporting against x databases of y types, you need a central repository of that database information, and a configuration file is not the right place, nor is an IOC container the right solution.
As Precipitous suggested, try Castle Windsor:
http://www.castleproject.org/container/
You're doing Inversion of Control manually. Windsor will take the burden off of you.

Specifying connection string in config file for a class library and re-use/modify in ASP.NET Web Application

How can one specify the connection string in a config file of a class library and later modify this when used in a ASP.NET Web Application?
The Class library is a data access layer that has a Dataset connecting to a database based on a connection string specified in a config file (Settings.settings/app.config).
This class library is used in a web application where user inputs data and is written to the database using the DAL classes & methods exposed in the class library.
Now, I want to migrate this application from development environment to testing environment and later to production. The problem I'm facing is that after migrating to testing, the app in testing still connects to development database. I've changed the connection string mentioned in <class library>.dll.config file but this seems to have no impact.
Can someone explain the right way to achieve this? Thanks in advance for any help. Cheers.
With the .config files the name has to match the main executing assembly. For example I had a situation like yours, I needed a class library to have its settings in a .dll.config file. While it was able to reference it the actual application would not be able to read the config file because it was expecting .exe.config. Renaming the .dll.config to .exe.config fixed the problem.
In your case migrating your connection strings from .dll.config to web.config should fix your problem!
Good luck!
Joshua is partly right ... For posterity I would like to add a bit more to this answer as I have delt with the same problems on several occasions. First, one must consider their architecture. There are several issues you can run into with .config files in ASP.NET based on deployments.
Considering the architectural ramifications:
Single tier (one server):
A simple web application may be able to leverage a reference to the sites Web.config file and resolve your issues. This would be a fine solution for a single tier application. In the case of a windows application leveraged as a .exe file, the App.config will work too.
Multi-tier (more than one server):
Here is where things became a bit hairy for me the first time I was working with .config files across boundries. Remember the hierarchy of the config structure and keep this in mind (MSDN Article on .Config structure) - there is a machine.config at the root in the appropriate ASP.NET folder. These reside at each physical server. These are overridden by the site Web.config (or App.config) which are in turn overridden by subfolder .config files. If you have more than one .config file you may want to use one of the methods to pass the file path for the specific .config you want to use. More importantly, these files each may have connection information. ASP.NET's machine.config holds some for the framework ... so you should at least be senstive to the fact this is an "inheritance" chain. Second, any changes to the Web.config file once deployed will tell the application to restart. This will result in loss of state (bad if you have active users on the site). The way around this is to keep a separate .config file (e.g. connections.config) and put a reference to that file in the Web.config. This will allow you to change the connection information (e.g. password) without having to restart the application. Here is a link to more info: MSDN: Working with Configuration Files. This article lays out all the details you need to be aware of in a normal server / IIS deployed application. Keep in mind that the .config files are mainly intended for applications, not libraries. If you have several tiers, chances are you are using some communicaiton / messaging layer (e.g. WCF). This will have / allow its own Web.config. You can keep connection strings there (and encrypt them if needed), but better yet, put them in a second file referenced by the Web.config for manageability. One final point, if you are ever going to consider the cloud, .config files are wrapped for application deployments which in effect removes all of the benefits they offer in terms of "not having restart or redeploy". Azure deployments will want to consider this article to save themselves from nightmares of maintenance: Bill Lodin blog - Configuration files in Azul / Cloud. One other point on this article – great example on how to programmatically select configuration depending on deployment! Be sure to check that out if you want to add flexibility to deploy in or out of the cloud .
I hope these points saves all of you time and headaches. I know I lost a couple days of programming time dealing with these issues ... and it was hard to find all the reasons in one place why may app was not "implementing" its connection object. Hopefully this will save you all from the same fate I had.

Visual Studio basicHttpBinding and endpoint problems

I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.
Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.
This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.
At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!
Also, the settings we need to manually change are:
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
and:
<binding maxBufferSize="655360" maxReceivedMessageSize="655360" />
We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed.
Create a .Bat file which uses svcutil, for proxygeneration, that has the settings that is right for your project. It's fairly easy. Clicking on the batfile, to generate new proxyfiles whenever the interface have been changed is easy.
The batch can then later be used in automated builds. Then you only need to set up the app.config (or web.config) once. We generally separate the different configs for different environments, such as dev, test prod.
Example (watch out for linebreaks):
REM generate meta data
call "SVCUTIL.EXE" /t:metadata "MyProject.dll" /reference:"MyReference.dll"
REM making sure the file is writable
attrib -r "MyServiceProxy.cs"
REM create new proxy file
call "SVCUTIL.EXE" /t:code *.wsdl *.xsd /serializable /serializer:Auto /collectionType:System.Collections.Generic.List`1 /out:"MyServiceProxy.cs" /namespace:*,MY.Name.Space /reference:"MyReference.dll"
:)
//W
Rather than changing the generated endpoint, uou could add a second endpoint and binding definition with the configuration you need, then in your code just put the name of the new endpoint in your service client constructor.
Somehow I prefer using svcutil.exe directly than to use the "Add Service Reference" feature of Visual Studio :P This is what we're doing on our WCF projects.
I take your point, svcutil is definetly the more advanced way of adding and updating service references. Its just a fair bit more manual work when "right click, update reference" is so close to just working in a single step.
I guess we could create some batch files or something to just output the reference code. Even then, manually checking out and updating the service code with svcutil will probably be more work than just undoing the check out on the config.
Thanks for the advice in any case.
What we do is we check out (from source control) the app.config and *.cs files that are autogenerated by the svcutil.exe utility, then we run a batch file that runs svcutil.exe to retrieve the service metadata. When it's done, we recompile the code, make sure it works, then check the updated app.config and *.cs files back in. It's a whole lot more reliable than using the oft-buggy "Add Service Reference" with Visual Studio.

Resources