How to read a web.config from .Net Window Application - c#

I'm developing a .NET Framework 4.0 based Windows application.
I have a requirement of distributing this window application, along with source code to client.
When I test I'm using my own database credentials.
So I want a method to somehow hide the app.config details.
For this, I tried with encrypting values in app.config but faced an issue with token keys.
While researching about it, I found that I can use:
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration.
But that again required username and password for accessing remote server and don't want to show them to the client.
So for this I planned to read web.config hosted on IIS 7.5 Server.
Could you please help me in that context?
Or if you have better ideas to achieve the objective, do share.

The code is designed to be very close in syntax to the usual method used for accessing web.config from a web app. Pass the constructor the location of the web.config file you wish to parse and then use the AppSettings method to obtain the desired value;
string filename = #"c:\temp\Web.Config";
UK.Org.Webman.ConfigurationSettings ConfigurationSettings =
new UK.Org.Webman.ConfigurationSettings(filename);
string PrimaryDatabase = ConfigurationSettings.AppSettings["PrimaryDatabase"];

Related

Change xmlSerializer tempFilesLocation for a wcf client

We use WCF client in our project which is an Azure functions app, to communicate with an external web service. We need to change the xmlSerializer's tempFilesLocation because of the permission issue. I searched online and found the following configuration that we can use in our web.config which will solve the problem.
<system.xml.serialization>
<xmlSerializer tempFilesLocation="an absolute path of your choice"/>
</system.xml.serialization>
But in Azure Functions app, we don't have access to web.config, so we need to find a way to do it in the code. Is there any way to change tempFilesLocation in the code?
It's not possible to modify the web.config for functions running on the dynamic sku (where you pay-per-invocation).
However, if you create your function on the non-dynamic/classic sku (where you pay per vm, the pricing model for regular web apps) then you can modify the web.config settings via an applicationHost.xdt file. More details on how to work with xdt file here: https://github.com/projectkudu/kudu/wiki/Xdt-transform-samples

DNN Database Repository Reuse in Console Application

I have a project based on the Chris Hammond, Christoc, module template. I have a ton of code that I use to access data an external database. In my repositories I change the database from the default to whichever I need for that particular object. I do so with code that looks like this:
using (IDataContext ctx = DataContext.Instance(MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY))
{
var rep = ctx.GetRepository<Product>();
products = rep.Get().ToList();
}
The default database is switched in the call to .Instance(). The repositories are used by my custom DNN modules. The repository is part of the solution that contains multiple custom modules. When I compile and install using the Extensions part of DNN, everything works well. In the code above, MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY is found in a file MyModuleSettingsBase.cs file of my module solution. It is set to a simple string like "ProductDatabase". In the solution for the base DNN install (not the module solution), within the web.config file, there is a value in <connectionStrings> with name="ProductDatabase" which contains the actual connection string. This all links up fine on the DNN website.
Now I am writing a console application that does some monitoring of the site. I want to access the database to check values in the product table. I would like to reuse all of the repository code I have written. In an attempt to do so, I added a reference to the MyModules.dll file so I would only have one copy of the base code. This works to give me access to all the objects and the associated repositories but when I attempt to query data it fails. When debugging I can see that it fails on the line:
using (IDataContext ctx = DataContext.Instance(MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY))
When viewed in a debugger, the string value MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY is correctly set to "ProductDatabase" but the code is unable to link this with the actual connection string. I don't know where it would be checking for the connections string when running from my console application. I attempted to put a <connectionStrings> section into my App.config file but this didn't do the trick.
Is it possible to have MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY map to the connection string in an external application which references the DLL?
If so, where can I set the value of my connection string so it matches up to the key value stored in MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY?
I was faced similar problem 3 months ago, at that time I want to use DNN core libraries in my console application but I was failed.
I placed my queries in DNN official forum website and I got a valid response from Wes Tatters (DNN MVP).
Here is the post link: Reference URL
As your requirement of monitoring, I suggest you to create DNN Schedule Application. You can schedule it within DNN (Host->AdvancedSettings->Schedule), even good point is that you can use your repositories (DNN Libraries) in that schedule application.
I hope it solved your problem. Let me know if you have any questions.

Storing SQL credentials correctly

First off, this is an educational question - not something I am implementing in a productional application since I am learning the basics of C#.
Currently I have a solution containing 2 (actually 3, but one is unit testing) projects;
Form
Class Library
Inside the Class Library I have a class called Database.cs and it communicates with a MySQL database. I don't directly communicate with this Database.cs class, but other classes inside the Class Library do (for example Products.cs).
Though, I need credentials to connect to this MySQL database and I am not sure which way to go to do it safely.
Storing it inside the Class Library / hard-coding the credentials inside the class.
This wouldn't make sense to me since a user can easily grab the DLL and he technically got the credentials to the database.
Pass the credentials through the form to a class (like Products.cs) and that class passes it on while initializing the Database object
Could work, tried and it works but I am not sure if this is the 'neatest' way to do it.
Write a static class that contains properties with the credentials
Again, if I create this static class inside the Class Library I am pretty much off the same as my first example. If I would create this static class inside the Form, I require to add a reference to the Form-project from my Class Library (not the way I want it to be).
I tried looking stuff up but I am apparently not doing it right. Is there any other way to do this?
First of all never hard-code credentials into code because credentials tend to change over time so that means you will have to recompile and redeploy your application each time SQL credentials change.
Usually all information needed to connect to database is stored in application configuration file in a form of connection string.
If your application is web application then you're good to go because web.config (a web application configuration file) is stored on a web server and is never served to web requests.
But if your application is windows forms application, then security considerations kick in meaning that any user who uses your app could peek into application configuration file and get credentials. If it would be Microsoft SQL I would advise to use Windows Authentication. But with MySQL I guess you're doomed to store user name and password into connection string. Then I would suggest securing your connection string by encrypting it.
Also if your users can/have to authenticate against MySQL server (enter MySQL username and password), then you could use a connection string template and substitute certain parts of it with user name and password:
app.config
<connectionStrings>
<add name="MyApplication" connectionString="Location=myServerAddress;Data Source=myDataBase;User ID={0};Password={1};
Port=3306;Extended Properties=""""; />
</connectionStrings>
C# code
var username = textboxUsername.Text;
var password = textboxPassword.Text;
var connectionString = string.Format(ConfigurationManager.ConnectionStrings["MyApplication"].ConnectionString, username, password)
// at this point you have a connection string whitch could be passed to your Products class
Do not hardcode your credentials as that may prove to cause issues, firstly if you need to change your login credentials to the database at a later stage then you will have to recompile your class library, secondly as you mention the security will be compromised.
It is a good technique to leave the connection information to the main application instead of storing them in your data layer. Refactor your data layer to accept the connection string during runtime, this value needs to be passed by the main application to the data access layer.
This way you get 2 advantages:
When you deploy your application, the deployed location can have a different connection credential than your development environment
You can encrypt connection strings in your configuration file so as to increase security

Modifying configuration at runtime in ASP.NET

I am having the following problem. I have an ASP.NET (VB.NET) application that is trying to connect to Amazon Web services using the AWS .NET SDK, and in order to do that the user is entering their Access and secret key. I am then adding the key to configuration like so:
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
Dim settings As KeyValueConfigurationCollection = config.AppSettings.Settings
settings("AWSAccessKey").Value = AmazonAccessKeyText.Text
settings("AWSSecretKey").Value = AmazonSecretKeyText.Text
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
While this successfully modifies the web.config file, it still throws an exception at runtime saying that it can't find the Access key. Can anyone tell me what I am doing wrong?
If I understand correctly you have as ASP.NET application that connects to the AWS on the clients behalf, if so storing the clients credentials locally might be the best idea from a security point of view.
You can either
Only store the credentials in memory in the session only when needed in something like a SecureString
Store them encrypted on the disk using any crypt apis.
The amazon sdk doesn't need the credentials stored in the app/web.config. If you look at something like AWSClientFactory.CreateAmazonS3Client , you will notice that you can pass them as parameters to this function
Probably, it is better to keep your received in key in Application object? for example static.
It is much clearer and simpler and will not cause a recycle of application when web.config is modified

How to retrieve on which site the web application is currently running?

I am currently running a WCF service on an AppFabric server and my application needs to load a the web.config file dynamically to retrieve custom configuration sections.
On my development machine I can just load the configuration like this:
WebConfigurationManager.OpenMappedWebConfiguration(webMappedFile, virtualPath);
But on the test machine (AppFabric server) I am getting an exception and it seems that I need to specify a third parameter which is actually the site the web application is running on:
WebConfigurationManager.OpenMappedWebConfiguration(webMappedFile, virtualPath, "MySite");
So I tried to hard code it and it worked. Anyway this is not acceptable, so I need to dynamically provide the site to the WebConfigurationManager because I do not on which site the service will be running in the future. Do anybody knows how to achieve that?
Thanks.
If you are running this code as part of handling a request you could use:
Request.ServerVariables("server_name")
see: http://msdn.microsoft.com/en-us/library/ms525396(VS.90).aspx
Edit based on your comment
The parameter that you need is the Site Name, not the machine name, your code be running on many machines. If the code is running somewhere where it no longer knows that it is on a web site, then it is difficult for it to get the name of the web site that it is running on.
You then have two options:
Send the name as a parameter from a layer that has httpconext
Not sure if this will work: but you could try adding a reference to system.web to your project. It may compile, but you could get a null reference exception when you run it. Probably worth a try.
How about Server.MachineName

Categories

Resources