Im writing an web app that consists of a 3 projects. The ASP.net MVC5 website, a windows service which runs jobs which users schedule using the website, and then a class library which the other two projects reference. I have a JSON config file that the class library references. It contains data as to how jobs should run. I want to include it in my source control and I want it to be JSON so my colleagues who use the app can easily change it without having to recompile the solution. Only the class library needs to access the json file - the other two projects reference the class library so they essentially reference the settings in the json file by accessing classes in the class library.
My issue is, i am referencing the json config file path in the class library classes like so: AppDomain.CurrentDomain.BaseDirectory + "config.json"
However, when the web server instantiates a class from the class library the path resolves the the base directory of the web server instead of the class library, which isn't surprising.
Whats the best way to do this? Can I keep the config file permanently in the webapp project and then have a link to the config file in the windows service project perhaps? Not sure how that would work after deployment of the solution though?
Web project is .NET standard MVC 5. JSON much preferred over XML for config file type.
I've just tested it to make sure, so this should work:
If your file is in your class library project, you can just go to solution explorer, right click on it, > properties, then in the window look for copy to output directory. Set that to Always or only if newer which ever you feel is best, and it should be copied to your bin folders of your projects that reference the class library.
Related
Now I have seen this question before on SO in a variant ways, but surprisingly not in this form:
I have a solution with multiple web services (projects) that need to talk to each other. After publishing each of these web services might end up on a different machine with a different database. To tell each web service where all other web services are, I want to maintain a single config file during development.
I would like to expect that after publishing the config to be present in each published project. And I would like to expect the config file to be editable after publishing, so I can swiftly migrate a certain web service and then just edit all config files of the other web services.
I don't want to do this in the database, for the config file its self should also hold connection settings to the database(s).
I came across the following ideas/thoughts/questions:
I have a dll project called 'common' that is referenced by other projects. Let's give that one a shared.config and build a class in that project that can be used to read out the shared.config by doing System.Configuration.ConfigurationManager.OpenExeConfiguration("shared.config"). Just need to make sure the shared.config will be published along with the DLL.
I would favor this solution, as it would also let me keep a web.config inside each project having just the project specific settings. And have the shared.config having the shared settings. But I read on SO that this should not be considered lightly and could have some unwanted side-effects, like file-access-issues; though I wonder if this would apply to my case. Also I would like to ask your help here on how to actually realize this as I don't think Visual Studio supports app.config for DLL projects out of the box.
I also thought about creating a shared.config file in the Solution Items. Then linking that file inside each project. And in the Web.config of each projects, add: <appSettings configSource="shared.config" /> pointing to the linked file in that project.
Though I cannot find any reason why not to do this, first implementation failed. It seems (at least during development), c# cannot find the linked shared.config file. I'm guessing linking files is not done instantly nor maintained after creating the linked file, but the file is only copied to the projects WHEN I do a publish. Thus leaving the file missing during development. Is this correct?
The config files are app specific. This mean that you can add a config file to a class library but the file will then by used by the app (windows service, webservice and so on) referencing the library.
Same thing for external configSource, this are app specific as well and need to be included withing the project using it.
So if your solution is composed by 2 projects you then need 2 config files. One for each project.
While for a windows based application(services, winforms) the expected folder for config files is the bin directory, for web based projects this will be the directory is the root folder of the virtual directory.
This said, using a shared config file looks the easier solution (and you don't have to copy the app.config from the class library for each project). Here are the steps :
Create a solution folder.
Add the config file to it.
Add the file as a reference for each project needing it. Right click the project and Add existing item - > Choose the file and Add as link
Ensure the file is always copied by setting the copy option (properties of the file) with Copy Always.
At this point you should have the config file deployed into your project directory everytime you compile the solution.
EDIT:
I'd avoid looking into the bin for config files within a web app, the
convention is that file should be in the root, so I would avoid the
first option.
Linked files end up in the bin after building the project. Try the same steps for importing the file but this time simply add it (not as link) and it will be deployed as content in the root of your site, so it can be always available.
If your hosting in IIS it is possible to have a single web.config file at the root site level but Giorgio is right in that app.config files are app specific. it is possible to use custom build steps to automate the copying of config files across multiple projects so personally I would go with that.
This actually drove me a bit crazy. In the end I fixed it like this:
Created a Shared.config file in the dll project 'common', having the contents look like any ordinary web.config/app.config.
Set the file to be Content and Copy Always, so it would surely be copied out to all projects that reference project common. (Though the config file will indeed end up in the bin folder.
Created the class SharedConfiguration inside the common project. The really tricky part was having to use OpenMappedExeConfiguration() , and getting the path to the executable directory (including bin, and without file:// in front of it).
Now when I want to access a setting from the shared settings, I do SharedConfiguration.instance.AppSettings.Settings["CubilisEntryPointUrl"].Value.
(I cannot use SharedConfiguration.instance.AppSettings["CubilisEntryPointUrl"] directly because of this issue)
.
public static class SharedConfiguration
{
public static readonly Configuration instance = GetConfiguration("Shared.config");
private static Configuration GetConfiguration(string configFileName)
{
ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
Uri uri = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
exeConfigurationFileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, configFileName);
return ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
}
}
I gone through lot of threads about this topic but did not get any solution.
First I created a windows application. In that I used app.config file to store some variables it worked properly. Then the application converted to class library. While extracting the varibles it gives only null values.
Any other option to get or set variables in config file in the class library
Thanks.
If you converted you code to some class library you have to remember that it will reuse web.config/app.config of an application, which references it. So I would suggest to add settings from "old" app.config to the configuration file of an application, which uses your library.
We can not use app.config or web.config in class library. Add app.config for Console/Windows application or web.config file for your web application which calls your class library then application will automatically takes and uses that configuration file.
I am working on a MVC Application, which has WCF as back end.
I have all POCOs in my Data Entities CS project, which is shared between WCF and Web application projects. Now, I have a scenario, where I need to convert an MVC application to multilingual.
I have created one resource project, and given reference of it to both Entities project (to use display attributes) and Web.
But it copies the Resource dll to WCF as well, which I feel is wrong.
So, where can I put my resource files?
If in Web, then how to use Data Annotation attributes?
I am using Display attributes on Enums, instead of description to display it in multilingual form. So again, where should these Enums be (I kept them in Entities)?
Instead of adding a reference to your project. Try adding just a reference to the DLL within the bin folder of the project your trying to share. That way when you reference from 2 projects, each project points to just that one dll. In production you should setup a folder parent of your root web directory that contains those "shared" DLLs.
I have a project which contains shared functionality that can be used both by a ASP.NET WebApplication and a WCF Service.
The shared project is a Class Library, and has some dependencies on files.
Normally I would simply call HostingEnvironment.MapPath() in order to resolve these dependencies, however this isn't possible in this context since System.Web isn't available (it's a class library).
Is my only real option passing the absolute path to the Class Library? This would require me to do some further processing as it would be the root for the respective projects, and not the root of the Class Library.
In the end I've found the following solution:
Set the properties on the dependent files: Copy to Output Directory = Copy if newer
This copies the files into the bin folder of the Hosting Environment (so it will copy it into either the WCF Service or the WebApplication from the Class Library)
HostingEnvironment.ApplicationPhysicalPath then returns this location
The difference is the files are being copied cross project when building (I didn't know copy if newer did this). I can therefore access the files from the applications' bin (and not from the Class Library as I was attempting before).
I have a Visual Studio 2010 Solution that contains three projects:
A Windows Service which will read Data from a SQLite Database to perform actions
A Winforms App which will provide a method of configuring the behaviour of the Service (by updating the SQLite Database)
A Class Library Project to abstract all database access away from the service and the config app (making it easier in the future to update anything having to do with the database without having to hunt down queries in the other two projects)
All of these projects are in the same solution, and I have added references from the Winforms App and the Service to the class library. In both projects I am able to see the classes from the class library and interact with them, but I am having an issue. I have created the database in the /Resources/ directory of my class library project (because to me the "common" project is the only sensible place to store the common database), however whenever I attempt to access the database in the Winforms app, it is not returning data that I know is in there. Since System.Data.SQLite has the default behaviour of creating an empty database file if the file isn't found (an odd choice in my opinion), I can't even go back and tell if the database exists or not.
This leads me to suspect that I am not understanding properly how files from one project are referenced in another. Here is what my project looks like:
WorkModeCommon Contains the classes SQLiteDatabase and ScheduleManager, where ScheduleManager has a SQLiteDatabase() and SQLiteDatabase interacts with Resources/WorkModeSchedules.s3db
Both the WorkModeConfigApp and the WorkModeService have a WorkModeCommon.ScheduleManager(), which should in theory take care of all of the database interaction.
Do I have a major flaw in my design, or could someone point me to a resource which could help me solve the problem I'm having?
I think this is what's happening.
When you reference the common class library, it's simply using the .dll output as the reference, since it's the only output.
However, if you right-click on the .s3db file and go to its Properties, you can set its Copy to Output Directory setting to Copy if newer, that way the database file itself is in the output directory, so the .dll file can see it.
Now, when your form or service access the .dll file from the output directory of your common class library project, it'll reference the .s3db file, too, so then they'll all see the same data.
Whether this is a good design or not depends on your needs.
If the form and the service are both looking at the same data at the same time, then you have to make sure they're at least looking at the same file, not at their own copies of the .s3db file.
If it's just the form or the service accessing the database, I'd be ok with it, but since multiple processes (the form and the service) are accessing it, a common database server is a good choice.
Compiled classes are visible to outside assemblies that reference them as long as their visibility is Public (with some exceptions). Non-compiled files are a different story. You can specify the build action as "embedded resource", which will allow you to access the file from referencing assemblies, albeit in a read-only fashion. The other option, and likely what you want, is to specify "copy to output directory" as either "copy always" or "copy if newer." This will copy the file to the output directory at build time.
When you start debugging your WorkModeConfigApp, the app runs from its bin\debug directory and has no way to reach the resource directory of the class library. Simply referencing the class library doesn't means that VS copy the resource directory of the class library inside the bin/debug of the Config app. If you set the Copy Local = true for the class library VS will copy the compiled DLL inside the bin\debug of WorkModeConfigApp but doesnt' copy the content of the resource directory
On the other way, you could set the property copy to the output directory for the .s3db file, in this way the file and its directory will be copied in the bin\debug of the WorkModeConfigApp. But this will be the source of other problems because during debug your test database risk to be overwritten from the one coming from the class library.
I think that your best option is to save inside the configuration files of the service and of the config app where to locate this file and don't mess with the aforementioned property.
We are talking about a Database so probably in the config file for App and service you need to add a connection string. You could add the required nodes to your App.config, see the example below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="WindowsFormsApplication1.Properties.Settings.MyDatabaseConnection"
connectionString="Data Source=C:\ProgramData\MyAppName\/WorkModeSchedules.s3db;Version=3;Pooling=True;Max Pool Size=100;"/>
</connectionStrings>
</configuration>
You could then access this value using one these methods:
string cnnString1 = ConfigurationManager.ConnectionStrings["MyDatabaseConnection"];
string cnnString2 = Properties.Settings.Default.MyDatabaseConnection;
(The ConfigurationManager method requires the reference to System.Configuration assembly)
Ok folks, I've solved my problem. What I did is include a copy of the DB file in each project, and set the "Copy To Output Directory" property on all but one of those instances (the "Common" project) to "Do Not Copy". After that I changed the output directory for all three projects to the same directory (more specifically, I created centralized Debug and Release directories and pointed the proper build configurations to the proper directories). I am now able to test successfully using a single DB file and a centralized class library!