How to connect to different databases? - c#

I'm currently developing an application based on ASP.NET MVC3, SQL Server 2008 and EF with database first.
My application requires every user to have it's own SQL Server database. These databases all have an identical structure.
My customers are identified with a customercode, e.g. fgt. This code is provided in the url.
I need to know how can I retrieve the customercode from the url and set the connection string accordingly.
Thanks for the help
My idea is to connect to the database once the customercode is retrieved from the URL and then prompt to user to enter his username and password for access data.
But yes, is a good idea to create a database to store the connection string of each customer.
Can anyone write the code that I need for do this please?. I am new to asp. I come from php.
(I'm just learning English. Sorry about the bad grammar)

Try something like this to get started:
string customerCode = Request.QueryString["cust"].ToString();
string myNewConnString = ConfigurationManager
.ConnectionStrings["MyDatabase"]
.ConnectionString
.Replace("[placeholder]", customerCode);
Where your connection string in your .config is something like this. Note that I've assumed you'll place a token to be replaced ([placeholder]).
<add name="MyDatabase"
connectionString="Data Source=192.168.0.1;Initial Catalog=[placeholder];User ID=foo;Password=bar"
providerName="System.Data.SqlClient" />

Suggest that you whitelist your customers and their connection strings.
setup a web service on your side.
your deployed application calls your web service using the customer code.
web service validates the customer code, and returns a valid conn string.
customer's app keeps the conn string in memory (session, cache, whathaveyou).
This would allow you to ensure the conn string is always valid for a given customer code. You'd have fine grain control on access to the database for any reason (non-payment, etc). Your service would have a few hits thanks to any caching that you build in.

maybe sqlshard could help you in using multiple databases?
http://enzosqlshard.codeplex.com/

Sounds like pretty insecure solution. What if customer put another customer code in URL? Where is validated if customer can access that code if you don't have any central database with customer's permissions?
You need authentication and some central store (additional database) where you will validate that user accessing the application has access permissions to provided URL. It will also validate if such database even exists. Next you need just SqlConnectionStringBuilder and use the customer code as a name of database (or part of the name). For security reason each database should have a separate SQL account with permissions to read only from that database. This db account can also be stored with that central storage with encrypted passwords.
There can be additional complexities if you also expect dynamical adding or removing customer codes = databases. That would require high privileged account to manage logins, accounts, databases, etc.
Because you are asking how to get part of Uri it looks like you have almost no experience with ASP.NET MVC and perhaps with everything related. You should definitely ask any more skilled colleague or boss to review your architecture because at this point it looks like you are going to have serious problems and you can develop very insecure application which can significantly harm reputation of your company and your customer.

Related

SQL Database connectionstring for the users in the network

I have developed a WindowsForm C# application which is connected to the SQL database with the following ConnectionString style:ยจ
ConnectionString = "Data Source=23PC\\SQLExpress;Initial Catalog=DB;User ID=USER1;Password=***;Integrated Security=false;";
And it works perfect for me and the users on the network. I wonder how I can change the CS to make it available for Windows Authentication login rather than Mixed Mode, i.e. without determining U and P.
This is the connection string I always use:
String.Format("Data Source={0};Initial Catalog={1};Integrated Security=True", myDBServerName, myDBName)
This will require that you configure your SQL Server permissions accordingly so that your Windows users have proper logins and access to the database.
Between this question and the corresponding DBA.SE question, there is a tremendous amount of ambiguity here. It's still not very clear what you're actually asking, but you have something of a question in this "I wonder how I can change the CS to make it available for Windows Authentication login rather than Mixed Mode ..."
To address that: Mixed Mode includes Windows Authentication and, as such, requires proper permissions management. I try to guide this sort of permissions management toward Active Directory Groups. You can add groups the same way that you add users. This is covered here. From there, you can set permissions by group (keeping in mind that DENY trumps all other permissions).
To check if Mixed Mode is enabled (and to enable if necessary), check out this answer.
Please do not upvote if useful. The reality is that this question is a dupe of something already on the site, it's just a matter of figuring out what that dupe may be.

Azure Mobile Services - Connection string not found after publishing

After I deployed my mobile service to Azure, calls to the service fails because of this error:
No connection string named 'ApplicationEntities' could be found in the application config file.
The error only occurs on Azure side. When I test the service locally, the connection to the remote database works without a problem.
I separated my solution into several projects:
Web Api
Business Logic
Data Access (contains the DbContext, database first)
Common (contains the entities generated by EF)
As I always do, I copied the connection string generated in my app.config of the DataAccess Assembly into the connectionStrings-Element of my web.config (Web Api project).
<connectionStrings>
<add name="ApplicationEntities" connectionString="<the connection string>" providerName="System.Data.EntityClient" />
</connectionStrings>
In the web deploy settings, I selected the connection string for "ApplicationEntities". I tested it with and without the option "Use this connection string at runtime (update destination web.config). I always get the same error.
Then I got curious and logged the connection strings available via the ConfigurationManager with something like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
sb.AppendLine(ConfigurationManager.ConnectionStrings[i].ConnectionString);
}
trace.Info(sb.ToString());
I got two connection strings:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Data Source=theserver.database.windows.net;Initial Catalog=thedb_db;User ID=theuser;Password=thepassword;Asynchronous Processing=True;TrustServerCertificate=False;
The username and password is strangely different from the username and password stated in the management portal.
Also the EF-Metadata information get lost.
I get this connection strings when testing locally:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
metadata=res://*/DataContext.ApplicationEntities.csdl|res://*/DataContext.ApplicationEntities.ssdl|res://*/DataContext.ApplicationEntities.msl;provider=System.Data.SqlClient;provider connection string=\"data source=theserveraddress,1433;initial catalog=thedb_db;persist security info=True;user id=theusername;password=thepassword;MultipleActiveResultSets=True;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;App=EntityFramework\"
I expect to get the same connection strings when running on Azure. Any idea what's going wrong?
Update:
I just went for remote debugging the service (see here). As I opened the downloaded publish-profile in my text editor, I discovered that there is an attribute SQLServerDBConnectionString - containing the connection string that always gets forced when deployed - with the same username and password I'm not aware of that it exists.
I tried to overrwite this connection string but it did not help. That connection remains the active.
Update 2 / May 29th 2014:
Seems that in the meantime the error has been fixed by the azure mobile team. Still running the same code using the database first approach and it's working now. Thanks a lot!
I have myself tried using DB first approach with dot net backend mobile services & ran into same sort of problems as you. Digging around further, following is my observation :
The azure mobile service with dot net backend must use code first approach only. This generates a specialised connection string with metadata (starting with res:)
The name of the connection string has to be the same as it is when you download the default sample todo app I.e. Ms_TableConnectionString.
There is an option in azure websites to select custom SQL provider to help make a custom connection string, this option, however, is not available for dot net backend mobile service in Azure Management portal.
P.s. Posting as answer because I don't have a enough points to comment..
Just wanted to give an update that I have been looking at this for some time and think I for the first time see it too. I don't know what is going on but wanted to let you know that we are indeed looking at it.
Henrik
(I don't have enough points to comment so having to do this as an answer)
Henrik, I have this same problem. If I ftp on to the box I can see that the web.config has the correct connection string but it fails as trying to use the username in the SQLServerDBConnectionString property (OoWUqr****Login). Is it possible you could let me know in what order it is looking for connection strings and where?
And if it can't stop it using the other user is there a way I can permission them for the correct database through mobile services?
Thanks
F

Single connection string for multiple users in asp.net

In asp.net 4.0 c#, i have two databases on different servers 1.Sql server 2.Oracle
I want to develop a web application in which the users will login with their id password and then
perform the allowed tasks.
I want to know that how i can make a single connection string for multiple users?
I dont want to make connection string on every page.
I was looking for this for a whole day but could not found any solution.
currently i am not using web.config file but i have a class where i have made a connection string and passed the textbox values to it
and the storing them in static fields and suppling them to other classes , but i dont think it is good approach
i think most of people are not getting what i really want to ask
kindly let me know if you want any confirmation.
for example there are 40 users each having a different id,password (no of users can be increased or decreased) there are two approaches to have a connection string
1)make a connection string in a class
string conn=#"server=MYSERVER;database=mydb;user id="+userid+";password="+password);
but how the userid,password fields can be accessed in web.config? here userid=textbox1.text,,password=textbox2.text;
2)make a connection string in a web.config file
so how?
It is very common for all users to use the same connection string to talk to the database server for a web application, and for the application to control what functions the users can and can't do based on their userid and password and security you build into you application.
In this type of setup, the user's id and password are separate (and different) from the userid and password for the database server.
If you must use a separate userid and password for each users db connection, then you wouldn't store it in a connection string in your config file, but would instead build it dynamically based on the user logging in.
Like this for example:
var userid = "testuser"; //these would come from your login page, not hardcoded
var password = "letmein";
var sqlConn = new SQLConnection("server=MYSERVER;database=mydb;user id="+userid+";password="+password);

Access denied for user 'root'#'localhost' (using password: YES) in Visual Studio

Kindly bear with me. I am a Microsoft SQL Server person with loads of Visual Studio experience, but I need to get something done using a MySQL database.
I am trying to create a little tool here that will allow our developers to quickly update database records, and I am using Visual Studio to create a small Windows Form to do this.
In a Microsoft SQL Server connection string, I could write something like this:
Server=myServerAddress;Database=myDataBase;User Id=username;Password=password;
In a MySQL connection string, there appear to be multiple other options, but the first one looks basically the same:
Server=myServerAddress;Database=myDataBase;Uid=username;Pwd=password;
When I attempt to open the MySQL connection from my PC, I get the exception listed in the title (actually, it shows the Uid value and the IP Address of my PC instead of localhost, but I am hoping more people will recognize the error easier this way):
public static void MySQLi_Connect() {
m_err = null;
var str = Properties.Settings.Default.ConnStr;
try {
m_conn = new MySqlConnection(Properties.Settings.Default.ConnStr);
m_conn.Open();
} catch (MySqlException err) {
ErrorLog("MySQLi_Connect", err);
}
}
I did a search, and it seems that the Uid on MySQL needs to be granted access from the specific IP Address that the connection is being made from.
Further, I found this on the mysql.com doc pages:
If you do not know the IP address or host name of the machine from which you are connecting, you should put a row with '%' as the Host column value in the user table. After trying to connect from the client machine, use a SELECT USER() query to see how you really did connect. Then change the '%' in the user table row to the actual host name that shows up in the log. Otherwise, your system is left insecure because it permits connections from any host for the given user name.
A few things:
It looks like I can connect to MySQL by using a % setting in the Uid jp2code, but MySQL says I need to change that back right away to remove system vulnerability.
Microsoft SQL Server did not seem to require this - or, if it did, I simply never was slapped in the face with this vulnerability issue like MySQL is doing.
Now, I ask:
If this is going to be a tool used by different developers on different PCs, is it common practice to turn the blind eye to this horrendous system vulnerability?
Is this not really as big of a concern as MySQL is making it appear?
What is the best way to continue with a Windows Forms application that needs to connect from various locations? Obviously, I do not want to continuously be adding more entries for a particular application every time another developer wants to use the tool or someone tries to run it from a different PC.
You can configure the security of your MySQL server as strong as you like, usually you dont connect users but applications. So if you have your root user without password in production environment is your fault. Usually developers have access to development environment, so this is not a big deal.
Of course try to have as many users as roles you need, for your example I think one user is enough. In production use a secure config file for save a secure password and set you mysqlserver restricted.
I was having the same issue and I found out that the password wasn't correct.
GO to your sql command line and type the code below:
mydb in the line below is the name of the database you are working on.
passwd in the line has to match the password you have in c# code so in your case "password"
grant all privileges on mydb.* to myuser#localhost identified by 'passwd';
Like OP says you can wildcard the hostname portion. I used this on our dev-server (not recommended for production servers):
update mysql.user set host = '%' where host='localhost';
Then I had to restart the server to make MySQL use it (propably I could just have restarted the MySQL service).

handling the connection string with SQL Authentication

I am deploying a Windows Application that uses SQL Server 2005. The program will use SQL Authentication.
My question is, how do you handle the connection string when you don't know what the username/password will be? Do you load this from an encrypted file? Or are there provisions for handling this already?
If the user will provide their login details (username and password) then you just need to provide the ability to enter them in your app, e.g. show a dialog asking for these details. You can then use those values the user gives to build the connection string in your code.
Alternatively, if all your users are going to be using a single SQL account to connect then you can put the connection string in your app.config file using encryption if you want to hide it from your users, see cmsjr's answer for an example of how to do this.
Alternatively, if you're developing this on an internal domain (intranet) then switch your database to integrated security and put your users domain accounts into the relevant access group on your database server. Then you won't have to worry about collecting username or passwords at all.
If the enduser will provide the password you don't need to do anything, dont save the usernamne/password in the config file.
If you don't want the end user to provide the password you could put it in the config file at installation. But that could be a problem if the username needs to be changed and you have encrypted the connectionstring.
Encrypting sections of the configuration is not as simple for a windows app as for a web app, but it is certainly doable. Here's a sample.
Just make sure to check the username/password for "weird" characters that the user might enter. The last thing you want is for them to change around your connection string. Then basically you just specify the driver (if using ODBC), the database, the server, but leave all the username/password and trusted connection info out. Then just tack on username= and password= which will be set equal to what was entered by the user on the end. However watch out for semicolons. I've never tried to see what happens if there is both a username/password and a trusted_connection = true.

Categories