JSP website pre-database configuration - database

I'm working on a website in JSP (in GWT really, but on the server side, it's really just JSP), and I need to configure my database.
I know HOW to code in the database connection etc, but i'm wondering how/where the database config should be saved.
To clarify my doubt, let me give an example; in PHP, a website usualy has a config.php, where the user configures the database, user, etc (or an install.php generates it).
However, since JSP is bytecode, I can't code this info into my site and have the user modify it, nor can I modify it analogously to an install.php.
How should I handle this? what's the best/most common practice ? I've found NO examples of this. Mainly, where should the config file be stored?

There are several possibilities to do this, what I've seen done include:
Having database credentials in a special file, usually db.properties or some simple XML file that contain the required information (driver, url, username, password, any ORM parameters if needed). The properties file would be placed under WEB-INF or WEB-INF/classes; the downside of this approach is that the user would have to modify the file inside the WAR before deploying it to the application server.
Acquire the database connection via JNDI and expect it to be provided by the application server. This seems to be the most common way of doing this; on the upside, your WAR doesn't have to be changed, however, the downside is that configuring a JNDI data source is different for every application server and may be confusing if your system administrators are not experienced with Java technology.

Related

C# SQL connection string best practice

I have a winforms application that connects to a database with a connection string and a generic user
"Database=DBADAS;Server=TMT123\\SQLEXPRESS;User ID=user; Password=*****;
After connecting into the database with a login dialog, we check if the user and password are existent in the user table from the database.
My question is now if this is a good practice? because basically in the connection string there is every information needed to crack the server.
There are a few ways to go about this safely. Since it's a Winforms app and not a web application, most of your security risks involve someone already in your network peeking at the connection string. This adds a layer of security in and of itself.
1. Hardcoded
You can hardcode the connection string that fetches the users into a DLL and make your application depend on that DLL. I only suggest this because it sounds like the "generic user" password is permanent; otherwise, you'd have to recompile code every time you changed the password, then deploy again. This is very secure, however, as the value isn't stored in plain text.
2. App.Config
You can stick it in a configuration file. Within a secured network, this is probably the most versatile option, as you can store multiple strings and easily update them without updating the full application. This goes well alongside settings like a "DebugMode" setting, etc. Using App.Config or another XML file is ideal, but you can roll a quick and dirty .txt file, too.
3. Database
Probably the most secure way of all, as you can encrypt your database and code your programs to fetch their connection strings and login information from that database by using an unrelated login. This allows greater control over what can be reached by the application when a user has not yet logged in. It also prevents the software from operating outside of the network, which may be desirable.
4. Internal API
Having a separate application serve this data divorces user capability from your concerns, as the API and your app can exchange verification keys to see if your app even has permission to try to connect. This is my personal favorite, but obviously the most work to set up.
5. Registry Entry
Depending on how you have this installed, it may work well to embed the tokens you need in the Registry. This guarantees the app requires admin permissions to install, and allows you to use Windows security to restrict access to the hive.
Again, since it's an internal non-web app, I wouldn't worry too much about the plain text of the connectionstring; if someone has gotten this far into your network, chances are you have much bigger problems already. I wouldn't leave it floating as a plain text file in a local directory, but any degree of security above that is probably acceptable for your purposes.
Encrypting Web.Config
Open Command Prompt with Administrator privileges
At the CommandPrompt, enter:
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
In case your web Config is located in "D:\Articles\EncryptWebConfig" directory path, then enter the following to encrypt the ConnectionString:
ASPNET_REGIIS -pef "connectionStrings" "D:\Articles\EncryptWebConfig"
Use Aspnet_regiis.exe tool with the –pef option and specify the application path as shown above.
Note: The parameter "connectionStrings" is case sensitive.
For Winforms: You need to rename your app.config to web.config encrypt it by using steps 1 to 3 and again rename it to app.config.
Reference: https://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config

How to determine at runtime if I am connected to production database?

OK, so I did the dumb thing and released production code (C#, VS2010) that targeted our development database (SQL Server 2008 R2). Luckily we are not using the production database yet so I didn't have the pain of trying to recover and synchronize everything...
But, I want to prevent this from happening again when it could be much more painful. My idea is to add a table I can query at startup and determine what database I am connected to by the value returned. Production would return "PROD" and dev and test would return other values, for example.
If it makes any difference, the application talks to a WCF service to access the database so I have endpoints in the config file, not actual connection strings.
Does this make sense? How have others addressed this problem?
Thanks,
Dave
The easiest way to solve this is to not have access to production accounts. Those are stored in the Machine.config file for our .net applications. In non-.net applications this is easily duplicated, by having a config file in a common location, or (dare I say) a registry entry which holds the account information.
Most of our servers are accessed through aliases too, so no one really needs to change the connection string from environment to environment. Just grab the user from the config and the server alias in the hosts file points you to the correct server. This also removes the headache from us having to update all our config files when we switch db instances (change hardware etc.)
So even with the click once deployment and the end points. You can publish the a new endpoint URI in a machine config on the end users desktop (I'm assuming this is an internal application), and then reference that in the code.
If you absolutely can't do this, as this might be a lot of work (last place I worked had 2000 call center people, so this push was a lot more difficult, but still possible). You can always have an automated build server setup which modifies the app.config file for you as a last step of building the application for you. You then ALWAYS publish the compiled code from the automated build server. Never have the change in the app.config for something like this be a manual step in the developer's process. This will always lead to problems at some point.
Now if none of this works, your final option (done this one too), which I hated, but it worked is to look up the value off of a mapped drive. Essentially, everyone in the company has a mapped drive to say R:. This is where you have your production configuration files etc. The prod account people map to one drive location with the production values, and the devs etc. map to another with the development values. I hate this option compared to the others, but it works, and it can save you in a pinch with others become tedious and difficult (due to say office politics, setting up a build server etc.).
I'm assuming your production server has a different name than your development server, so you could simply SELECT ##SERVERNAME AS ServerName.
Not sure if this answer helps you in a assumed .net environment, but within a *nix/PHP environment, this is how I handle the same situation.
OK, so I did the dumb thing and released production code
There are a times where some app behavior is environment dependent, as you eluded to. In order to provide this ability to check between development and production environments I added the following line to global /etc/profile/profile.d/custom.sh config (CentOS):
SERVICE_ENV=dev
And in code I have a wrapper method which will grab an environment variable based on name and localize it's value making it accessible to my application code. Below is a snippet demonstrating how to check the current environment and react accordingly (in PHP):
public function __call($method, $params)
{
// Reduce chatter on production envs
// Only display debug messages if override told us to
if (($method === 'debug') &&
(CoreLib_Api_Environment_Package::getValue(CoreLib_Api_Environment::VAR_LABEL_SERVICE) === CoreLib_Api_Environment::PROD) &&
(!in_array(CoreLib_Api_Log::DEBUG_ON_PROD_OVERRIDE, $params))) {
return;
}
}
Remember, you don't want to pepper your application logic with environment checks, save for a few extreme use cases as demonstrated with snippet. Rather you should be controlling access to your production databases using DNS. For example, within your development environment the following db hostname mydatabase-db would resolve to a local server instead of your actual production server. And when you push your code to the production environment, your DNS will correctly resolve the hostname, so your code should "just work" without any environment checks.
After hours of wading through textbooks and tutorials on MSBuild and app.config manipulation, I stumbled across something called SlowCheetah - XML Transforms http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5 that did what I needed it to do in less than hour after first stumbling across it. Definitely recommended! From the article:
This package enables you to transform your app.config or any other XML file based on the build configuration. It also adds additional tooling to help you create XML transforms.
This package is created by Sayed Ibrahim Hashimi, Chuck England and Bill Heibert, the same Hashimi who authored THE book on MSBuild. If you're looking for a simple ubiquitous way to transform your app.config, web.config or any other XML fie based on the build configuration, look no further -- this VS package will do the job.
Yeah I know I answered my own question but I already gave points to the answer that eventually pointed me to the real answer. Now I need to go back and edit the question based on my new understanding of the problem...
Dave
I' assuming yout production serveur has a different ip address. You can simply use
SELECT CONNECTIONPROPERTY('local_net_address') AS local_net_address

Machine config instead of app.config files for console apps

Is it possible to use connection strings in a Console app's app.config file in a single machine config file instead? So all console apps on the server can use the same file?
You could, but that would mean that any .NET application could gain access to your database.
I would advise against it, for several reaons:
A possible security hole.
Most developers would look for this information in app.config not machine.config.
You may end up sharing connection strings that only one or two applications need with all applications.
You can't limit what applications will be able to use the connection strings.
You will not be able to simply move the application to another machine, with the app.config file and have everything just work (you will also need to import the connection string information to the new machine.config).
You really should keep the configuration with the application that uses it.

Access 2007 to SQL server file upload?

I have an Access 2007 database with an attachments facility. Currently the client may upload files locally but the files cannot be accessed elsewhere. I have been able to carry out a similar operation when developing on a web based system however I cannot seem to do it on an Access 2007 database and I am unsure as to whether it is even possible. Basically the system needs to connect to the SQL server online and upload the file although the database is not online itself. I would be grateful for any pointers!
I have faced this situation. Here are your choices:
Use Access attachment field in a shared ACCDB -- won't work "online" very well, but you could park the ACCDB on your LAN and make it a separate back-end ACCDB shared by all. Your post didn't say whether your users are either local or "online" -- and whether "online" meant web.
Use VarChar(Max) (aka BLOB) fields in SQL-Server to store the attachments. But, you can't populate these easily from Access. Assuming you control the server where SQL-Server is running, you can use ADO in Access to upload a VarChar(Max) using the bulkinsert T-SQL command. This works pretty well and it's easy.
Create an upload web page. Use iExplorer automation (i.e, create an iExplorer object) in VBA to navigate to that page, fill it in and press the upload button. For security reasons, you cannot use automation to fill in a file upload control, but you can use sendkeys. This doesn't work perfectly -- sometimes you have to repeat the process once or twice, but it works pretty well if it's invoked by a user who can validate it's working. This is what I did -- easiest solution.
Best solution probably is to create a web service using WCF to handle the upload. There are plenty of posts on how to encode and decode byte arrays to store files as VarChar(Max). It works extremely well. Unfortunately, Access cannot directly consume web services as far as I've been able to tell, so you would have to write a small vb.net program to do this and call it from Access.
You could store the files/attachments outside of SQL/Server - just on the server, and store only the links/URL's for those files in Access. You could make each one launchable. This is easy but harder to control the security.
You can use Sharepoint to store/share the attachments. That can work pretty well depending on the size of the attachments and your connectivity. It's built to support this.
Access allows multiple attachments in one record. SQL/Server doesn't support this. So, if you can split your ACCDB into a front-end for the programs only and back-end ACCDB that is sharable by your users to contain the data/attachments, that is by far the easiest answer.

App.Config vs Custom XML file

I have read a lot of statements like "you shouldn't clog your app.config file with custom settings". However, I was under the impression that this was exactly the purpose of the file?
Is it just indeed a preference thing? Or are there any real benefits (other than separation of settings) by using a custom XML file, as apposed to the app.config file? If you need to explicitly separate settings would it better to use a custom ConfigurationSection rather than opting for a custom XML file?
I would like to here other peoples thoughts on this.
Some people tend to go a bit overboard on custom config section handlers, in my humble opinion.
I tend to use them only when I need something that is very structed; and that is used/written by 3rd parties (i.e. I want to do some extravagent validation on it).
I think you can quite happily use app.config/web.config for all relevant settings, and use separate XML files when it is very clear that is a separate component of the app.
Have a look at the Application Settings Architecture, the app.config is for Configration regarding the Application, thats quite a general term though.. So I would suggest you look into the Application Settings Files.
I would not store settings like "load database on startup or not" in the app.config. I would rather use an Alternative Storage like Application Settings for this, don't confuse Application Configuration with Settings, even though you might want to do that, Don't. app.config is supposed to have configration regarding lower level things like Database connection, Membership Provider or any other Application Critic information.
Most settings tend to fall into one of three camps:
Technical settings that affect the internal behaviour of the code, e.g. database connection string, data file path, logging switches, error handling switches, etc.
Business settings that affect the business logic of the product, e.g. "are users allowed to access the CRM Module?"
User-specific profile values, e.g. "is this user allowed to access the CRM Module?".
The natural place for type 1 is in app.config or web.config, and the natural place for types 2 and 3 is in the database.
App.Config are good for configuration that are application specific : path to database is a good example. The rest should be out of it.
One thing you might want to do is to create user-specific files, you can then use custom xml that will be saved into an IsolatedStore.
In my opinion I consider app.config to be good for deployment-time settings such as the location of the database, or an IP address or location of critical data file, etc. User settings like font, color, behavior preferences should go in a different file which you can easily create and save with Xml serialization.

Resources