Asp.net MVC2 - Multiple databases - c#

I have a database called
"Config" where I have a table called "Customer"
In the Customer table I hold the login credentials, along with a connection String to the client's database.
Inside of my controller I'm checking to see what customer database i'm querying
String connectionString = "";
if (id == 1)
connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Client1.mdf;Integrated Security=True;User Instance=True";
else if (id == 2)
connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Client2.mdf;Integrated Security=True;User Instance=True";
using (TestDbaseDataContext db = new TestDbaseDataContext(connectionString))
{
var searchRecords = db.SearchRecords;
return View(searchRecords.ToList());
}
There will be an undetermined number of client's using separate databases, these connection strings will change based on archived status, and other factors. I don't think hard coding these strings in app.config will do what I need.
I have a "Master" database, that holds all of the client's configuration settings, along with the client's database connection string. The mater database is only used to mitigate which client database to search. I store the connection strings in the master database so I can pass that connection string for the logged in customer to query the correct database. It is a requirement to have each client in it's own database
How would you store this connection string so I can pass to my datacontext when needed?
Should it be stored in a session variable, or should I query the Config database Customer table in each controller method?

I've set up a similar "siloed" multi-client application before. This is a good case for a session variable. Each user relates to a client, which has its own database. On login, each user should get a "context" object in Session state containing all necessary identifying data, including database connection string.

Related

Oracle connection with port, service name, and database from C# (ORA-12514

I'm new to Oracle. Trying to connect C# windows app to an Oracle database but can't seem to establish a proper connection. Keep getting exception: "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor". I have to specify the port, service name, and database name in the connection string because the service id has access to multiple databases. I know that the values in the string are valid (valid server, valid serviceid, valid username, password, etc) because I have a third-party tool that is able to connect using the same parameters from a wizard. I've tried a lot of different ways to format the connection string but I always get the same 12514 error. In the code example, you'll see three formats (cxn, cxn2, and cxn3), I've tried each of them but get the same error.
string cxn = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyServerName)(PORT=MyPortNumber))" +
"(CONNECT_DATA=(SERVICE_NAME=MyServiceId)));User Id=MyUserName; Password=MyPassword;";
string cxn2 = "DATA SOURCE=MyServerName:MyPortNumber/MyUserName;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
string cxn3 = "DATA SOURCE=MyServerName:MyPortNumber/MyServiceId;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
using (OracleConnection conn = new OracleConnection(cxn3))
{
string sqlSelect = "SELECT * FROM PERSONS";
using (OracleDataAdapter da = new OracleDataAdapter(sqlSelect, conn))
{
var table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 1)
Console.WriteLine("Successfully read oracle.");
}
}
Again, I've used MyServiceId in the third-party tool's wizard and I connect just fine and select my database. I'm using Oracle.ManagedDataAccess.Client. I consulted a number of articles online including Oracle's guidance in section "Getting Started with ODP.NET, Managed Driver". How can I get the driver to recognize the valid service id and then also accept the database name? Any guidance is appreciated. Thanks.
Well I wish I had a more definitive explanation but as it turns out the code from my original question works NOW using the connection string defined in variable "cxn". I ran it many times before with no success, so my only guess is that the DBA changed something or rebooted the server since initial configuration.

How to write query with prefix for table name in entity framework

I have WPF app with Oracle DB. I use Entity Framework. Connection string:
DATA SOURCE=localhost:1521/ora;PASSWORD=1;PERSIST SECURITY INFO=True;USER ID=user
I need to connect to new DB with the same namespace, but another USER ID and PASSWORD. I can't create new connection string because USER ID and PASSWORD are unique for each user of the app. I need to run only two queries to new DB. For example
SELECT t.column1, t.column2 FROM "USER ID".tableName t;
What is the best way to do this?
Thanks
You can create a new connection string dynamically at runtime and use this one to connect to the database and run your two queries.
How to: Build an EntityConnection Connection String: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/how-to-build-an-entityconnection-connection-string
SqlConnectionStringBuilder Class: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder(v=vs.110).aspx

How to create connection string that independent on instance and server name?

i want my application can run on every device that maybe have different server name and instance. my connection string is below:
DBDataContext db = new DBDataContext(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_data\DB.mdf;Integrated Security=True;User Instance=False");
If I understand you correctly and the Data Source is always on the local server, why don't you get the ip address of the server with System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
string myLocalserverIP = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
then use that in your Data Source string.

Mysql connect to server without any database

In my program C# program I need to create several mysql databases if they don't exist on the mysql server.
So I created a connection string to the server:
add name="ServerConnection" connectionString="Server=localhost;Port=7070;uid=root;password=pass;" providerName="MySql.Data.MySqlClient"/>
Once the databases are created how can I use the existing connection to connect to one of the databases ?
Should there be a connection string for each database on the mysql server ?
Thanks
No you don't need to create separate connectionstrings in your config file for each database you have the need to create.
You could use the, not so well known, class called MySqlConnectionStringBuilder living in the usual namespace MySql.Data.MySqlClient.
This class allows to specify any single key/value pair required by your connectionstring.
It also accepts, as a constructor parameter, a previous connection string that is internally splitted in the various key/value pairs and then it exposes these key/value pairs as properties of an instance of the MySqlConnectionStringBuilder.
This permits to change one property (the Database for example) and then rebuild a connection string with the updated values.
So for example you could write
MySqlConnectionStringBuidler mcb = new MySqlConnectionStringBuilder("yourinitialconnectionstring");
mcb.Database = "yournewdatabasename";
string newConnString = mcb.GetConnectionString(true);
using(MySqlConnection cnn = new MySqlConnection(newConnString))
{
......
}
The final call to GetConnectionString requires a boolean value set to true if you want the connectionstring returned to contain the password.
(Example based on MySql Provider 6.3.6)

System Data Entity. The underlying provider failed on Open

I am creating 2 projects that have the same database (it's an MDF database). The first one is the map editor, and I use XNA 4 and Web Services to connect to it. The second one is the game itself and uses XNA 3.1 and Entity Data Model to connect database.
When I run the map editor and access the database, it runs properly. Bbut when I run the game and access the database, it shows an error "The underlying provider failed on Open"
I think the connection from the web service is not closed yet. But I don't know where I should close the connection.
Here is my code from the web service:
public Map AddNewMap(string username, string mapName, int sizeX, int sizeY)
{
using (BaseModelDataContext context = new BaseModelDataContext())
{
Map newMap = new Map()
{
Username = username,
Name = mapName,
SizeX = sizeX,
SizeY = sizeY,
Upload_Date = DateTime.Now,
Status = 0
};
context.Maps.InsertOnSubmit(newMap);
context.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
context.Dispose();
return newMap;
}
}
EDIT:
Here is the entity data model code :
using (MazeEntities ent = new MazeEntities())
{
ent.Connection.Open();
return (from map in ent.Map
select map).ToList<Map>();
}
This code runs properly if I did not use the web service before. If I use the web service first, it shows an error at ent.Connection.Open();
Here is the inner exception:
Cannot open user default database. Login failed.\r\nLogin failed for user 'erkape-PC\erkape'.
Connection string for web service :
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Connection string for the game:
"metadata=res:///MazeDataModel.csdl|res:///MazeDataModel.ssdl|res://*/MazeDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\eRKaPe\DropBox\TA\Program\3D_Map_Editor\3DMapEditorServices\App_Data\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
For a quick check, can you try adding the following line after the using:
using (BaseModelDataContext context = new BaseModelDataContext())
{
context.Connection.Open();
OR
context.Database.Connection.Open();
// your code here
Finally I found a way to solve my problem after reading some articles.
The connection from the web service doesn't close automatically after I close the map editor. That is why I can't access my database from the game.
I have to change the connection string from both application, I set the User Instance to False. The game can access the database this way.
Please check the following post
http://th2tran.blogspot.ae/2009/06/underlying-provider-failed-on-open.html
Also please Enable for 32 Bit application in the APplication Pool of that application.
This may resolve.
You are trying to return an object (Map) which is associated with the Context. This object has the context information which can't be returned to the client.
You will need to create your own DataContract (a type having necessary properties) that you want to expose to the client.
Or you can use the POCO implementation As described here

Categories