C# - Create Variable Accessible Through Whole Project - c#

I have a connection string placed throughout my whole project, and would like to be able to bury it away from anyone who may be able to find it when I put my project into production. How can I create a string outside of my .cs files that contains this connection string that can be used inside of my .cs files?
I have tried to Google search this and have had no luck finding any answers.

In Dotnet Core, consider using configuration files. When your app start, it reads configuration settings (connection strings included). This will separate your configuration values from your code. Take a look at this:
Configuration in ASP.NET Core

You can create a textfile out of your project and write your value in there.
Then you access it again with a FileReader.
Another way is to write it in your configuration files
or decrypt it as good as you can.
A full security to hide your ConnectionString from others is unfortunately not possible.

Maybe you can create TEXT file with encrypted string inside folder of project, than whenever you need it decrypt an use it

Related

C# how to define global constants like api keys and prevent from being uploaded to Github

I'm working on a Visual Studio C# project (.net 4.7.2) where I need to store some private API keys as constants. The project gets uploaded to a public github repo, but I don't want the API keys to be shared.
What is the best practice for achieving this?
It seems if I create a Constants class file with a static class containing the constant values, then omit file via .gitignore, the project won't build for other users who download it because the file will be missing. If I upload the skeleton of the file first, then omit it via .gitignore, it won't be updated if I change or add new constants later.
I'm looking for best practices to achieve this.
a pattern that I see often and I personally use:
create a skeleton file like settings.json.sample and put placeholder values for your keys
copy that file to settings.json and put the real values
add settings.json to .gitignore
in the readme add instructions to rename settings.json.sample to settings.json and populate with actual values

What is the easiest way to generate an App.Config file through pure c# code

I know the easiest way to generate a config file is through visual studio. however the environment my program is going to be functioning in we are going to have several different configurations and the application needs to be able to build the config files on its own. Just curious if there is an easier way than making a large string literal and then copying over to a new file. Thanks for any help.
Not sure what kind of information you want to save in generated configurations.
If you are using only appSettings section which as only key values, then it would be better to generate a JSON file. It is very easy to generate it using newtonsoft.json.
in your app.config file you can keep the path of JSON file and load the settings at app startup if the file is already available.
NOTE:
JSON can also store any kind of complex configurations, you will have to generate the classes to hold those configurations.
Once you application puts value in these objects, serialize it to JSON and keep it in appropriate folder which is accessible to application.
Hope this helps.

how to store settings for deployable c# application?

I want to store settings for my C# application, such that default setttings can be easily shipped with my binaries and the end-user can change them using a simple text editor(or in some other simple way).
I seem to face several alternatives : a .config file, .settings file or a .resx file. What are the pros and cons of these?
Edit1: End-users are computer professionals mainly, so editing these files should not be much of a problem.
Edit2: The settings are something like connection strings, and some other parameters (mostly one-time stuff). Building some kind of GUI/API for changing them is not really an option. Also my application will not edit any of these values, so persistence through code is not required.
Yes, Project + Properties, Settings tab was designed to do this. Add your settings here, change the Scope to Application. That generates a app.exe.config file in your build direcctory, deploy it along with your EXE. Use Properties.Settings.Default.SettingName in your code to obtain the setting value. Your user will normally need admin privileges to edit the .exe.config file on the target machine to change the setting value.
The small print: settings do not work well for DLL assemblies, you have to merge the .config files by hand. When using the debugger, settings are retrieved from the app.vshost.exe.config file.
The .settings file is a helper file used by the IDE, ignore it. .Resx files store resources, they get compiled and embedded in a binary form in an assembly. They are not editable by the user.
I think you can have two ways of doing this.
For regular users, you can make a custom GUI that will make it simple for them to use.
For advanced users, they can edit the configurations using a text editor if it's stored in a text file (ini file, config file, etc..) or you can make an API.
The .settings file is typically used for user-specific preferences and configuration information (whereas the .config file is used for global settings for the application or anything that modifies the .Net runtime. Simply putting parameters in a .config file can alter the behavior of your application even without you writing a single line of code for it).
Check out the Settings article on MSDN for more: http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
Since the file will be modified by the users, I think using app.config is not a good idea. What if they break the file structure? Or set an invalid value? Probably your application will crash directly.
One of the solutions would be to use a custom XML file. You will then validate it when your application starts. XSD will probably be the more elegant way to do it, but you can also parse it directly and validate it in code. If the file is invalid, instead of crashing, you will try to solve the problem, and if impossible, display a pretty error to the user, explaining that there is an error in XML at line n, position n, which is [error description here].
If the end user is really going to be editing them, I'm not sure I would want them editing my app.config file.
You have another couple alternatives that you haven't included. You could use an old-school .INI file that is simpler for an end user to understand. You could also use the registry. I would recommend the INI file, unless your users are very savvy, in which case use the .config file.
The answer depends on the deployment method. For instance, if you are using ClickOnce and offer updates, you might encouter problems using Application Settings.
I believe the best way to go is to create a GUI, something that is most certainly suitable for novice users. Given that you already excluded that option, use John's suggestion (ini files).

Issue with appSettings using 2 different projects

I'll try to do my best to explain my problem.
I have 2 separate projects which are part of the same application in Visual Studio. One of them is server-sided and the other is client-sided.
The client sided project uses an appSettings key called XMLFileName which is used to retrieve data from an XML and populate a dataset with the retrieved info. In this client sided project I have a method that performs some check in the dataset.
When I try to call that method from the server sided project, I can't get the dataset populated since the XMLFileName isn't being read by the server sided project due to it not being defined in its application settings. If I hardcode the file name string on the server sided project it won't find it since it looks in a different folder.
How should I proceed with this? Am I being clear enough?
Thanks,
Eton B.
Why not just add the same setting to the server-side project? Am I missing something?
I may not understand the problem completely, but it sounds like you have two different applications (client and server) using the same method (e.g. GetXmlFile()) to retrieve the same file (File.xml). If that's the case, then you probably need to have the XML file on a shared drive that can be accessed by a UNC path (e.g. `\myclient\XMLFiles\File.xml').
If that is the scenario, can you change the method GetXmlFile() to use a UNC path to access the file, and to store a UNC path and file name in your appSettings?
If I'm mis-understanding the situation, please let me know and I'll update my answer accordingly.
Hope this helps.

How do you embed app.config in C# projects?

When you compile a C# project, the app settings from app.config are saved along with the exe file. For example, if the program name is "solve_np.exe", there will be a "solve_np.exe.config" next to it, making it look less neat than I want it to. How can you embed it into the .exe?
I tried to set Build Action to Embed Resource, but that did not do the trick.
Aha. I guess you're falling foul of Visual Studio automatically placing stuff in configuration that you DONT want configured by the end user.
In this case use resources. Simply add a new file of type .resx. With this you'll be able to add things like strings and images to the resource file. After you build this it should provide static access to the resources (it typically generates a code file from the resources for you so you don't have to access ResourceManager yourself).
E.G. If I made resources.resx with a string called MyConfigValue after a build I should be able to access this like:
textBox.Text = Resources.MyConfigValue;
If you want values that are kinda variable but shouldn't be configurable then this is the right place to put them.
HTH.
It isn't unprofessional to have an app.config file shipped alongside your exe. I think the word you may be looking for is untidy. I personally don't find this is the case myself however everyone is different! Perhaps you could simply make the app.config file hidden by default?
Or another alternative is to create your own config file which you could save to the App Data folder or even storing the settings in the registry instead.
Here's another factor to consider. Seasoned .Net developers are accustomed to the standard application design, which incorporates using config files in both web apps and desktop apps. If you depart from that practice, you will make it more difficult for any developers who follow you to understand what you have done. Even sa's on the web server may be confused by the absence of a config file.
Since pretty much everybody does it this way, your code does not look "untidy" to others. On the contrary, it would be befuddling not to see a config file where one is expected.
Typically the theory of a configuration file, is that it stores settings you may want to change once you've deployed the application (for something like user preferences). To do this, you need to be storing somewhere external to your application. If you use the default setup, you get "[Your].exe.config". There are many other options you could look at, but nearly every one of them ends up with a file written somewhere, if you providing a mechanism that saves settings of some kind.
I agree with serhio darasd and Quibblesome but you can just delete "solve_np.exe.config" and it'll just use default configs.
After considering what was written in these comments and other searching, I decided that the best way to handle my issue of wanting my Entity Framework connection string to be embedded into my executable instead of needing the MyApplication.exe.config file with my deployed solution was to created a derived class like such:
Public Class MyEFDataContainerLocal
Inherits MyEFDataContainer
Public Sub New()
MyBase.New(My.Settings.MyEFContainerConnectionString)
End Sub
End Class
I just created an Application Setting of type Connection String that contained the same string as what is found in the App.Config file. I just had to replace the &quote;'s with actual quotes.
Then whenever I wanted to use the MyEFDataContainer as in Dim db As New MyEFDataContainer I would just use Dim db As New MyEFDataContainerLocal instead.

Categories

Resources