Multiple database single application with ASP.NET - c#

I created an application with Visual Studio and ASP.NET 4.0 with MSSQL 2012 Express as backend.
Initially there was no planning of multiple databases, so I programmed the app accordingly with single connection string for a single database.
Now, client's requirements has changed and he is asking for separate database for each year, DATABASE2015 for year 2015, DATABASE2016 for year 2016 and so on.
I will migrate structure and data from previous year database to new year database and thats fine.
But how will I connect to different database for different user as per their year selection at login time?
Also, I am having a single connectionstring in web.config and I have referenced that connection string throughout my project in both code side and html side for asp.net controls.
Please advise.

As Jon P said, what your client is asking would be a nightmare for you to manage and extensive multiple year reporting would be very difficult. But since you have asked a solution, so I think I can guide you somewhere about how to do that.
In your web.config file you could make your connection string as,
<add name="YourConnStr" connectionString="Data Source=.;Initial Catalog={0};UID=sa;PWD=password;"
providerName="System.Data.SqlClient" />
Then on every user login as per the selected year on login screen you would be validating the user name and password from some database table. In that table, you could make a column for storing the database name, and on successful login, store that name in a session variable.
Or you might make another table with a foreign key from Users table. In your new table you could store the database names per user per year.
In your DAL, while getting the connection string for SqlConnection, you could do as,
var db = System.Web.HttpContext.Current.Session["dbName"].ToString(); // from session variable
var connection = System.Configuration.ConfigurationManager.ConnectionStrings["YourConnStr"].ConnectionString;
return new SqlConnection(string.Format(connection, db));

Related

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

Switching between database servers [duplicate]

This question already has answers here:
Determining if a SQL Server table is read-only
(3 answers)
Closed 9 years ago.
We have 2 database servers with the same database (in both servers) for a web application, (only 1 was there when the application was deployed to production).Now the current database in the server connected to the web application is made read only and the second database in the second server is active. We are supposed to switch between the servers as the first primary one turns readonly.
The web application is in asp.net ,C# with sql back end. How do we check the read only for a db and connect to the next server ?
Create a second connection string in the Web.config and use whichever you need to establish a connection in the app.
You should be able to query the database to check if it is read-only , then change your connection string based on the result of the query.
In MSSQL I believe this information is held in the is_read_only column of the sys.databases table
http://technet.microsoft.com/en-us/library/ms178534.aspx
How do we check the read only for a db and connect to the next server ?
using T-SQL
SELECT name, is_read_only
FROM sys.databases
WHERE name = 'databaseName'
GO
This will return 1 in is_read_only column when database is set to read-only mode.
You could have both connections strings in your app.config and create a table in your 'non read only' database that will contain one row and one column. Make this row a boolean and once you make the change, swap this value to true. When your application loads, it will check this table's value and if it's true then it will use the connection string to the non read only DB. If it's false, it'll change to the 'soon to be read only' database.
Eventually you will want to change it so that you only have one connection string, unless you will need to have access to both. Typically I've only seen this setup for reporting, and generally there is only one application that connects to the read only/archive database.

Connection string when database (*.mdf) is copied on the web hosting server

I am continuing my previous question, as the reply lead to further doubts/points/concerns. I need help with the connection string on the web host server.
My connection string in the local computer is:
string connectionString = "Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\data.mdf;Integrated
Security=True;User Instance=True";
Now, I simply used the website copy tool with the VS 2010, and the entire website is copied as it is on the web host, with the database being at domainName/httpdocs/Experiment/App_Data/data.mdf
Now, I don't know how the complete connection string on the web hosting server look like. Some of the things which I learned, on the basis of those, I guess it should be:
string connectionString = "Data
Source=IP_Address_Of_WebHostingServer;AttachDbFilename=|DataDirectory|\data.mdf;User
ID=XXXX;Password=XXXX;User Instance=True";
Is it right (or COMPLETE?)? Also, I have no clue what the user id or password is? So on local computer, with the help of Integrated Security=True the windows authentication was being made. How to do it on the remote web host?
In the webhosting console, I see features such as create database, create database users, I can see the username and password aspects there. If those are required then how do I connect that with the database I just copied? It seems like those are the one's where database is created from scratch, while I already have the *.mdf (database) uploaded/copied.
I am stuck at this stage, and have no clue on how to proceed further. I know its something trivial, but out of scope of my knowledge. Please help me in completing the connection string. How do I make the database (data.mdf) file reachable/accessible?
I came across some articles which told to import the database and such (but where/why?), but I don't get it. When the database is in the App_Data folder, then why/how do I do that?
I am confused, please help.I'll highly appreciate step-by-step approach to fix it.Thanks.
EDIT (solution):
The solution given below is perfect. Apart from that this website/blog is worth checking.
-- http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/asp-net-hosting-options-cs
And if you don't have SQL Management Studio, best way to install is instructed here:
-- http://blogs.msdn.com/b/bethmassi/archive/2011/02/18/step-by-step-installing-sql-server-management-studio-2008-express-after-visual-studio-2010.aspx
Step 1 - Create a DB Script from SQL Management Studio
You will need to firstly script off you database schema and data (not as scary as it sounds - follow the steps here http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/ ) .
Step 2 - Create your DB at HostGator and Import your DB Script
Create your database at HostGator and import your script file (Follow this guide here http://support.hostgator.com/articles/plesk/plesk-9/how-to-create-or-import-databases-plesk-9 ).
Step 3 - Update your connection string and deploy!
You'll need to update your connection string to be something like this (you will need to add your details).
<add name=”CRMConnectionString” connectionString=”Data Source=Server IP;Initial Catalog=DBName;User ID=UserName;Password=Pwd;” providerName=”System.Data.SqlClient”/>
This connection string was cribbed from this resource here http://asoftwaredeveloper.wordpress.com/2012/01/06/hostgator-web-hosting-and-mssql-db-access/
Then publish your website and upload your files. Its worth noting that you won't need to update your App_Data folder and its contents when you publish because you'll be pointing at the DB on their server not the one in your directory.

How to connect to different databases?

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.

Database Error while launching application

I deployed C# application and created installer. Installer gets created successfully but when tried to launch the application it throws up following error:
An attempt to attach an auto-named database for file CampusPointe.mdf
failed. A database with the same name exists, or specified file cannot
be opened, or it is located on UNC share.
connection string in app.config is as follows:
<connectionStrings>
<add name="App_Key_Management.Properties.Settings.VendorKeyConnectionString1"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Vendor Key Management\VendorKey.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Any help would be appreciated.
Regards,
Sri
Sri,
First of all, you need to ensure a couple of things:
1. You have installed SQL Server
2. You need to deal with the creation or replacement of the file you created. I think this is your issue ... If the .mdf file exists then you need to either update the existing file or drop and replace it (USE [database] GO DROP TABLE... GO CRATE TABLE ... GO). You will also need to consider step 4 below.
3. If you are accessing a a file located in a database you need a fully formed name. You also need to add the database user to the connection string in ASP.NET Web.Config or App.config (depending on the app). I looks like you have started this ...
4. Make sure the user account that you are using in the connection string has the necessary privileges on the database side. If this is a full fledged database in SQL SERVER then the user account will need update, delete, create privileges. If you are replacing or creating databases on the fly then the user will need CREATE DATABASE or DROP / CREATE privileges.
I think to best answer your question we would need more information on the architecture of the application. My guess is that your code creates the database fine the first time and then when you try to run it the second time it fails because the database is already there. If this is the case you also need to address your code (with IF statements or SWITCH CASE ... your call) to handle situations where the table (1) does not exist and needs to be created; (2) exists and needs to be updated; and / or (3) exists and needs to be replaced. The correct answer again depends on your code and what you are trying to do.

Categories