Sharing an XML file between two projects? - c#

I have looked around and simply cannot find a way to open a linked XML file. My folder structure is like this:
...\projects\ConfigService\
...\projects\Shared\
...\projects\WebTool\
Inside the Shared folder I have a single XML file that will be modified by the WebTool project and read by the ConfigService (many times after each one is built and running). To make things as simple as possible, I simply tried "add as link" at the XML in each project, but then how do I actually get a full path to the linked object so I can open it? I use a link because the file will be changed after my projects are built, but I will not rebuild.
All answers I have found either try to pack the linked file into the project's binary, or the instructions are for adding classes/code instead of just a flat resource.
Or is there a better way to do this?

The solution that worked out best for him was to use the Server.MapPath() method to find his Shared folder regardless of where in the file system his website was rooted. Since it will always be [virtual-directory]\Shared this works out perfectly and he doesn't need to worry about config settings.

I think you want to use an app.config file to resolve this. Here's how you would do it.
In the WebTool service, and in the Config service, add an app.config file with the following text:
<configuration>
<appSettings>
<add key="XmlFileLocation" value="c:\folder\projects\shared\myfile.xml" />
</appSettings>
</configuration>
Then, you can retrieve the file location in each program by using the following:
string filepath = ConfigurationManager.AppSettings["XmlFileLocation"];
You'll have to add a reference to System.Configuration in your projects though.
Good luck!

Two ways to go
One depends on how you are going to deploy. If they are all going to same folder, the Mr Oded's solution is a quick and simple.
If you are deploying to a more complex folder structure e.g
MyApps
Shared
ConfigService
WebTool
The create a folder structure that mirrors that and set the output directory in each project to the relevant one (instead of the default bin\debug bin\release). The you can grab it with a relative path from from each tool e.g. (..\MyXmlFile.xml).
That said, I like neither of the above.
What else in shared? If there's a dll, then may be it should have a method that returns the location of the file, or the content, and let it manage where that location is.
PS don't forget seeing as it is exposed on the file system (somewhere), you need to cope with some well meaning individual deleting or modifying it.

Related

Trouble accessing folder path from web config file

I was trying to use the solution found in this post:
How to access the folder path in web config using c#
but I get a null reference exception (System.Collections.Specialized.NameValueCollection.this[string].get returned null)?
I have this in my web config file (it's inside the configuration like shown in the post linked above):
<appSettings>
<add key="SessionTest" value="C:\\Settings\\XmlDir\\Session\\20180824.xml"/>
</appSettings>
and retrieve it like so:
string path = System.Web.Configuration.WebConfigurationManager.AppSettings["SessionTest"].ToString();
Is there something simple that I'm missing here? The file exists in the folder (and I copied the path from the file explorer, so I'm having trouble understanding what is causing the null exception >.<")
Thanks in advance :)
As far as I'm aware this is the standard way to access web.config <appSettings>
System.Configuration.ConfigurationManager.AppSettings["SessionTest"]
There was a second web config file that I wasn't aware of (I'm working on an old project so I didn't realize the first team that wrote this had added one to the folder I was working in, which in hindsight is probably a little strange)
When I added it to the web config file that is associated with the entire solution and not the one inside the folder I was working in, I was able to retrieve the value successfully!
I want to also note I included SLaks suggestion from the comment he made (which is not to say it doesn't work with the double slashes, but I didn't include them when I found success so I can't confirm that).

Multiple applications with single app.config [duplicate]

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);
}
}

Visual Studio Solution with Multiple Projects: Reference Paths

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!

TFS, testing and placement of test files (where)

I am currently experimenting with TFS, and I really like it.
One small question, regarding test files:
I have a directory with some demo TXT, images, dirs... These are used during tests, so up until now, the path was hardcoded to a folder on my computer. Now I need to change this, of course, the TFS need access to the files too.
My idea was to place them inside the folder of my solution, I currently have roughly this structure:
Solution Folder
mysol.sln
SomeProjectDir
OtherProjectDir
_LIB for external .dll
_DEMO_FILES for test files
The whole solution folder is under source control. Would you do it the same way? How is the best and elegant way to get the "real" path of the folder for usage in unit tests? Using the execution path an cutting away the rest? Do test files belong under source control?
Thanks for any input,
Chris
EDIT: Beside the tip given in the answer, please be aware that with testing there are some pitfalls with this. The test is executed in a different folder (often named after some timecode), the testfiles do not get copied there automatically. Even if they are set to copy always.
The solution is to either add the files manually by using a attribute called DeploymentItem in the unit-test, or, in my opinion much better, adjust the Local.testsettings and add the folder there. Keep in mind, the folder itself will not be added, so you need to do it one level higher..
You will understand what I mean if you try it. Or search for DeploymentItem on google
test files are part of your project, so there is NO reason to keep them out of the version control system. You should commit to the version control system everything that is needed to build, test and run your system, including 3rd party libraries, config files, test files, and even arguably documentation. Please note that most of these things should be part of your Visual Studio solution as well.
In my projects usually I try to have all my resources as Embedded Resource, so that I don't need to figure out the path, they are compiled into the assembly. If for some reasons I can't go this way, I would make the build copy them to the output folder (so mark them as copy always in VS) and then use relative paths.

C# Settings xml file location

I have a project that reads in a file based on a value in a C# Setting class. This value however changes from machine to machine and Id rather not ask the user the first time the program is run as its a corporate environment, instead Id like it to be set in the installer, but where is the file located? Is there an easier method?
This is a visual studio addin not a standalone program
From your post it appears you have a windows application? , you can store an initial value in the application config, you can make an installer in Visual Studio and write custom actions that can write values to the file on first install in you install project.
The configure file is the easiest way to do what you are asking, however it is NOT the best. In fact it is recommended Not to use .config files for such cases.
whenever users install an 'update', there is a risk of overwriting their existing changes.
some businesses might have policy restrictions on the .config files.
the user cannot easily move his settings from one PC to another.
From my own experience, using XML, MS-Access, Registry or text files to store user settings has proven more useful than using the .config files.
I believe you are talking about designer-generated settings (the .settings file)?
The exact path usually contains some sort of a Hash (check this link). I usually have my own settings class which I serialize to and from xml using XmlSerializer, which gives me more freedom (I think C# settings files don't allow you to add custom enums, for example, or they make it a bit harder to do it than simply adding them to the .settings file).
However, maybe there is no need to set values during installation? For example, you could add a FirstStartup setting (set to true initially), which you can read when your App is started for the first time, and then set it to false. That way you can set your default settings when you detect a "first startup".
You will certainly need some sort of custom action at the end of your installer. You haven't mentioned what technology you're using to deploy your application so I will refrain from giving any specific guidance.
I recommend setting the value in your App.config. This is an xml file which will be named MyApplication.exe.config in the same directory as your application. Add it to your installer if it is not there already. In your installer, add a new setting:
<configuration>
<appSettings>
<add key="MySetting" value="My Value"/>
</appSettings>
</configuration>
In your code, retrieve the setting:
String setting = ConfigurationSettings.AppSettings["MySetting"];
If this is a machine-wide setting, this installer is the right place to set this. If you do it on the first execution you will run into a host of problems with permissions on the files and directories if the first person to run the app is a user with limited permissions.
Registry or an INI file or a XML file whatever suits you best.
Best option would be registry. Istalling the application will require Admin access so writing to the registry during installation will not be an issue.
More over if some one accidently deletes the ini or settings file then the program might stop working.
You said that this is for a corporate environment. You can create an administrative template for group policy to set the default in the registry. Then, your program can just query that one registry value if the default hasn't already been set.
I personally would never use web.config or app.config. Just read your own xml file, have a look at my post on this:
http://www.picnet.com.au/blogs/Guido/post/2009/09/10/XML-Settings-Files-No-more-webconfig.aspx
Thanks
Guido
To answer the "Where is the file located" bit of the original question for those interested (I'm assuming that the "settings file" in question is the "Settings File" item available from the "Add New Item" dialogue).
In Win7 (and probably all the other ones) the settings file will generate under the path:
C:\Users\[user]\AppData\Local
The folder structure from here on out depends on your AssemblyInfo and build information, the "AssemblyCompany" field (if populated) is used for the top-most folder, beneath this is a folder copying the application executable name, followed by the build and then finally the settings file (named "*.config").
In my case, the complete path is as follows:
C:\Users\[user]\AppData\Local\[company_name]\Application.exe_StrongName_zx0v1qxyoass4d0z3mtwe3vbrhaehkjg\0.0.5812.21662\user.config
My case is different, my project is a class library (dll) which have the app.config file. I decided to create 4 application settings variables (title, url, limit, rate). To create this, i right-click ont he project --> Properties --> Settings. this values you can retrieve in code using this command --> Settings.Default.title, ...etc
the problem is let say i instantiate 5 objects (same object for example MyProject.MyClass) from this library, i want the instance be able to have its own settings. i mean each of the instance may have their xml setting file. can this be done?

Categories

Resources