Could you explain me how to construct correct ConnectionStrings? I mean that one you can find in web.config file in MVC project. I understand that if you want to add a new connection string you have to write <add ... /> XML tag with parameters such as name, connectionString (it is the most interesting parameter for me) and providerName (perhaps some else?). What each parameter does and means? How to construct connectionString parameter? Where is the db engine indicated?
The questions above are only examples. I care about collecting the most amount of information about constructing ConnectionStrings.
Starting from NET 2.0 you have at your disposal a class named SqlConnectionStringBuilder
Its purpose is to help building dynamically the connection string. But the various properties available explain in great detail the functionality underlying to each possible setting
The SqlConnectionStringBuilder class is derived by a base class named DbConnectionStringBuilder and this allows all the ADO.NET provider to implement their own version of this class. In the link provided there are the references relative to other ADO.NET providers
If you are trying to construct entity framework connection string just use as follows.It will help you..
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
UPDATED:
The easiest way to get the connection string is using the Server explorer window in Visual Studio (View-->Server Explorer menu) and connect to the server from that window. Then you can see the connection string in the properties of the connected server (F4 with your connection selected).
If you create the database in SQL Server Management Studio, that database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express installed on your machine.
Related
We are using the Audit.NET SqlServer Data Provider to store Audit logs in our Microsoft SQL Server. We are currently in the progress of migrating to the use of Azure SQL with Managed Identity to access the database. We haven't been able to get Audit.NET working with Azure SQL and the use of Managed Identity to connect to said database. The documentation doesn't provide any information on whether this functionality is supported or not.
We have managed to do this for our own database connections using Entity Framework Core by adding an Access Token to the SQL connection used by the Context like so:
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.AccessToken = new AzureServiceTokenProvider()
.GetAccessTokenAsync("https://database.windows.net/")
.Result;
This works perfectly fine. The issue we are running into is that we want to achieve the same with the Audit.NET Sql Data Provider. Due to the AuditContext being used by the SqlDataProvider being internal we are unable to pass an Access Token to the SqlConnection used.
The only solution we've come up with is writing our own Data Provider that is virtually the same as the SqlDataProvider, the only difference being that the Context used will set an Access Token on the SqlConnection. Is this the only viable solution here or does Audit.NET offer some other way to get it working with Azure SQL and Managed Identity?
I think the best way could be exposing an optional setting to provide the DbContextOptions where you can set an Interceptor like the one from here to set the AccessToken for the connection.
So you could initialize your configuration like this:
Audit.Core.Configuration.Setup()
.UseSqlServer(sql => sql
.ConnectionString("connection string")
.DbContextOptions(new DbContextOptionsBuilder()
.AddInterceptors(new AzureAuthenticationInterceptor(new AzureServiceTokenProvider()))
.Options));
or
Audit.Core.Configuration.Setup()
.UseSqlServer(sql => sql
.DbContextOptions(new DbContextOptionsBuilder()
.UseSqlServer("connection string")
.AddInterceptors(new AzureAuthenticationInterceptor(new AzureServiceTokenProvider()))
.Options));
UPDATE
The new DbContextOptions settings was added on version 16.2.1
I'm new to ASP .Net Core and am working my way through a demo project to learn the tech stack.
My project is using .net core 2.2 and Oracle.ManagedDataAccess.Core and Oracle.EntityFramework.Core.
I created a model and then went and scaffolded my view and controller through VS 2019. I've set up ConfigureService(...) to use Oracle. I added an HTML link on my main index page to hook into the view created for my model. When it calls the Controller::Index() function, I end up getting the following timeout error
OracleException: Connection request timed out
OracleInternal.ConnectionPool.PoolManager<PM, CP, PR>.Get(ConnectionString csWithDiffOrNewPwd, bool bGetForApp, OracleConnection connRefForCriteria, string affinityInstanceName, bool bForceMatch)
Any help or guidance as to what I could be doing wrong would be greatly appreciated!
It looks like a error connecting to the database.
There are some things you should check:
Make sure the connection string to the database, stored in the appsettings.json is correct.
Make sure to have a firewall rule which allows inbound traffic to the port from where the Oracle db is listening.
If the problem persists then you should provide the code you are using to access the database.
Apparently, using AttachDbFilename and user instance in your connection string is a bad way to connect to a DB. I'm using SQL server express on my local machine and it all seems to work fine. But what's the proper way to connect to SQL server then?
Thanks for your explanation.
Using User Instance means that SQL Server is creating a special copy of that database file for use by your program. If you have two different programs using that same connection string, they get two entirely different copies of the database. This leads to a lot of confusion, as people will test updating data with their program, then connect to a different copy of their database in Management Studio, and complain that their update isn't working. This sends them through a flawed series of wild goose chase steps trying to troubleshoot the wrong problem.
This article goes into more depth about how to use this feature, but heed the very first note: the User Instance feature has been deprecated. In SQL Server 2012, the preferred alternatives are (in this order, IMHO):
Create or attach your database to a real instance of SQL Server. Your connection string will then just need to specify the instance name, the database name, and credentials. There will be no mixup as Management Studio, Visual Studio and your program(s) will all be connecting to a single copy of the database.
Use a container for local development. Here's a great starter video by Anna Hoffman and Anthony Nocentino, and I have some other resources here, here, and here. If you're on an M1 Mac, you won't be able to use a full-blown SQL Server instance, but you can use Azure SQL Edge if you can get by with most SQL Server functionality (the omissions are enumerated here).
Use SqlLocalDb for local development. I believe I pointed you to this article yesterday: "Getting Started with SQL Server 2012 Express LocalDB."
Use SQL Server Compact. I like this option the least because the functionality and syntax is not the same - so it's not necessarily going to provide you with all the functionality you're ultimately going to want to deploy. Compact Edition is also deprecated, so there's that.
Of course if you are using a version < SQL Server 2012, SqlLocalDb is not an option - so you should be creating a real database and using that consistently. I only mention the Compact option for completeness - I think that can be almost as bad an idea as using AttachDbFileName.
EDIT: I've blogged about this here:
Bad Habits : Using AttachDBFileName
In case someone had the problem.
When attaching the database with a connection string containing AttachDBFile
with SQLEXPRESS, I noticed this connection was exclusive to the ASP.NET application that was using the database. The connection did block the access to all other processes on the file level when made with System.Data.SqlClient as provider.
In order to assure the connection to be shareable with other processes
instead use DataBase to specify the database name in your connection string
Example or connection string :
Data Source=.\SQLEXPRESS;DataBase=PlaCliGen;User ID=XXX;password=ZZZ; Connect Timeout=30
,where PlaCliGen is the name (or logical name) by which SQLEXPRESS server knows the database.
By connecting to the data base with AttachDBFile giving the path to the .mdf file
(namely : replacing DataBase = PlacliGen by AttachDBFile = c:\vs\placligen\app_data\placligen.mdf) the File was connected exclusively and no other process could connect to the database.
I have written a trivial Entities code-first WinForms application with one simple class and one database context class as all the tuturials describe it.
But I did not add a connection string in the app.config file.
Nevertheless, when I start the application, it can insert objects into the database and even show all objects already inserted.
I figure there must be some default database in SQL Server for that case but I cannot find out which instance and database name is used.
Database name is the same as the name on your DbContext class. By default it creates a database on the local machine Sql Server express installation. You should be able to see it in Sql Server Managment when you connect to your local SQLEXPRESS.
If you spesify a connectionstring with the same name as youd DbContext it will use that instead.
I am new to ASP. I have two databases production and developer databases.
I need to check developer site is going to developer database or not. Both databases have same data and same table names.
But i must work on developer database only how can I?
Generally you'd have an environment configuration file. If you're talking about ASP.NET then it would be the Web.config file. If you're indeed talking about classic ASP then it would probably be an included script with some constants.
If the databases are structurally identical (which they should be) then all you should need to change is the connection string. For classic ASP, you'd probably just store it in a variable:
Dim connString = "This is your connection string"
On the production server, the connection string would be set to your production database. On development machines, it would be set to a development database. (And so on for a test environment, etc.) All of the data access code would just use this connection string variable.
Even more to the point, this should not be the only thing that prevents a developer from using the production database. The DBA should set the permissions such that only the production application has only the access it needs to that database and others do not. Developers should never be able to accidentally modify the production database. So even if you did use the production connection string from your workstation, the database should simply deny you access.
Have two connection strings. Then create a constant variable which will act as your switch and pick the correct connection string:
Dim strCon
CONST DEVELOPMENT = true
if(DEVELOPMENT = true) then
strCon = "Development connection string"
else
strCon = "Live connection string"
end if
adoCon.open strCon
Then you can simply change the switch to true/false depending on which database to pick.
When you specify the database connection you know where you are pointing, so this should be straightforward. But it might be a good idea to use separate logins on dev and production.
So the answer is that you should use the connectionstrings in the config files to get what you need: the "database =.." setting should be set correctly and your problem is aolvedsolved To get extra certainty use different logins, which is recommendable in any case.
you can also use server tracing to monitor activity, but it is not easy on a multi user database and is only a diagnostics tool, not a cure.