How do I set connection string in classic ASP? [duplicate] - asp-classic

This question already has answers here:
How to connect to a sql database using classic asp?
(3 answers)
Closed 3 years ago.
I have copied an older classic asp project from one of the servers, I am attempting to run it locally. I have the frontend running however, to logon obviously requires an attached db, I have moved all db files and attached them to my local machine. I am now struggling to set the correct connection string for the project to run locally
<sessionState mode="InProc" stateConnectionString="tcpip=myTCP" sqlConnectionString="data source=DESKTOP-1QG6I8F\SQLEXPRESS;user id=sa;password=" cookieless="false" timeout="20" />
<add key="mycon.ConnectionString" value="data source=localhost;initial catalog=catalog;password=password;persist security info=True;user id=sa;workstation id=localhost;packet size=4096" />
I believe these are the two relevant xml elements, coming from web.config
Ive never worked with Classic asp so bear with me
Ive fiddled with the code already, Changing datasource to my local pc
Any help appreciated
error code produced :An error occurred on the server when processing the URL. Please contact the system administrator.
The application should be logging on when entering correct login details

First, you'll want to create a Data Source (DSN) in the ODBC Data Source admin snap-on. You can find this in Control Panel > Admin Tools > Data Sources. Select System DSN tab and use the Add button to create the data source. Once you have it testing correctly for your DB, you can add the connection in your classic ASP code like this:
Dim dbConn
Set dbConn = Server.CreateObject("ADODB.Connection")
dbConn.ConnectionString="DSN=<YOUR_DSN_NAME>;Uid=<Username>;Pwd=<Password>"
objConn.Open
Give that a shot and see how you do. Good luck

Related

Setting up ASP.NET in Plesk Web Host Edition

So I'm in the process of making the configurations for my site on Plesk Web Host Edition but unfortunately I have an issue of accessing the database through my website.
I have noted the following:
1. I can access the Database through SQL Server Management Studio (SSMS) without any issues but one important thing to mention is that when I try to make my DB user as the owner of the database I get the following error:
Cannot alter the role 'db_owner', because it does not exist or you do not have permission. In other words, I'm not the owner of the database and I can't alter anything in it! although that I have created the database and the DB user through Plesk Panel.
2. I configured the web.config as follows:
<add name="xxxConnectionString" connectionString="data source=127.0.0.1\SQLEXPRESS;server=127.0.0.1;database=xxxx.mdf;Uid=xxx;pwd=xxxx" />
3. When accessing the website I get the following error:
Cannot open database "xxx.mdf" requested by the login. The login failed.
Login failed for user 'xxx'
I contacted the support of the hosting provider but it's been almost 4 days now without any reply. I'm really hoping of finding the answer with you guys.
Thanks in advance
I was able to find a solution for the ConnectionString issue. Below is the connection that I used to fix the issue:
<add name="CarRentalConnectionString" connectionString="Data Source=localhost;Initial Catalog=DATABASENAME;Integrated Security=false;User ID=USERNAME;Password=PASSWORD" />

ASP.NET ConnectionString AttachDbFilename=|DataDirectory|

This is about ConnectionStrings / ASP.NET MVC with Visual Studio 2012 ultimate & SQL Server Express 2012.
Following up with this tutorial here: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4 I came across an issue with these two connection strings at my web.config:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog=aspnet-MvcMovie-users;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnet-MvcMovie-users.mdf"
providerName="System.Data.SqlClient" />
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\Movies.mdf;
Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
the website works fine but I couldn't fingure out why the first db is created in the App_Data folder while the second one is created in "C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA"?! I supposed that both will be created in App_data because both utilize this attribute: AttachDBFilename=|DataDirectory|!
note: the tutorial mentions that it should be in the App_Data & they added a screenshot that shows it there indeed!
I have been looking for an answer and got into the complicity of SQL (I thought User Instances might be the solution) but couldn't reach an answer for this : |
(this might be useful to read about User Instances http://msdn.microsoft.com/en-us/library/bb264564(v=sql.90).aspx)
Any ideas are greatly appreciated. Thanks in advance.
Regards
after research/tests it turned out to be as follows:
VS will look at the class name of the DataContext and will look to see if you have provided a connection string with the same name as the class name; for example:
public class MovieDataContext : DbContext
and
<connectionStrings><add name="MovieDataContext" ...
if it manages to find a matching connection string it will create the DB based on the criteria you specified in the respective data string (to add the DB to the App_Data set the path of the DB to |DataDirectory| as shown in both connection strings mentioned in the question); if the name doesn't match or you didn't provide any connection string, VS will fall back to the default settings and will create the DB in the default location/settings (usually C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA).
note neither the "Integrated Security" settings nor the "Initial Catalog" play any role with this (I was able to create the DB in the App_Data with both Integrated Security = True & Integrated Security = SSPI and with/without Initial Catalog).
Hope this helps. Thanks for everyone that participated.
I had the same issue. I believe the difference is in the Integrated Security setting. I have SQLExpress installed and found my Movies database in there using MS SQL Server Management Studio.
Check out this response for a better explanation. Difference between Integrated Security = True and Integrated Security = SSPI
What AMT has given is exactly right. It was confusing as it is to use connection strings with .mdf and .sdf files.
I have another pointer for you though, you can change the default setting where the application looks for a connection string with the name matching the class name of the context class by overriding the constructor of DBContext and providing the paramter nameOrConnectionString as follows
public BlogsContext()
: base("name=EFBlogs")
{
}
Application then searches for a connection string named EFBlogs, if it cannot find connection string then it creates the database with name EFBlogs, instead of BlogsContext
Hi I notice a difference when you add a database and it asks do you want it to be placed in the app_data folder if you click yes then it goes to the app_data folder and the full path name of the mdf is also in the app_data folder whne you use file explorer.

An attempt to attach an auto-named database for file ....database1.mdf failed

I am getting the following error while debugging my visual studio 2010 website:
An attempt to attach an auto-named database for file C:\Users...\Desktop\Dpp2012New\App_Data\dppdatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users...\Desktop\Dpp2012New\App_Data\dppdatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Here is my connection string from my web.config:
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"/>
<add name="ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\dppdatabase.mdf;Integrated Security=SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And I access it from my website as:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
The stacktrace shows the error line as:
Dim conn As New SqlConnection(connectionString)
Dim dr As SqlDataReader
conn.Open() 'This is the error line as per stacktrace
I have given the needed permissions to the above folder so it can not be the " or specified file cannot be opened" issue. If we look at all the posts related to the same error in this forum, clearly the profoundness of this error can be found out. However, none of the solutions solves my issue.
Some of the resources which I have tried are:
http://weblogs.asp.net/scottgu/archive/2005/08/25/423703.aspx
http://blogs.msdn.com/b/webdevelopertips/archive/2010/05/06/tip-106-did-you-know-how-to-create-the-aspnetdb-mdf-file.aspx
http://forums.asp.net/t/1033225.aspx
I eagerly await a solution.
I had this problem also and it was a pain. I configured my connection string and managed to solve the problem. In the connection string I replaced the value |DataDirectory|\dbfilename.mdf for AttachDbFilename property, with the path to the file. |DataDirectory| can only be used if the database file is in the App_Data folder inside same project.
So changing the AttachDbFilename property to the direct path of the mdf file, fixed my issue.
AttachDbFilename=C:\MyApp\App\DAL\db.mdf
I hope this works for you.
Try to create your connection string as below:
<add name="ECommerce" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=C:\USERS\dL\DESKTOP\DATABASE\MYSHOP.MDF;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient"/>
It's working for me.
<add name="Connections" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
I had a similar error, but using a connection configured in code, rather than a config file. The solution for me was simply to add the "Initial Catalog=MyDatabase" part. My code now looks like...
DbConnection connection = new SqlConnection(String.Format(#"Data Source=.\SQLEXPRESS; Integrated Security=SSPI; AttachDbFilename={0}; User Instance=True; Initial Catalog=IPDatabase;", Location));
Location is a full path to an mdb file, that does not have to exist yet.
One of the most annoying errors when developing web apps in .Net. I had this issue on a project I was doing a year ago.
This is what worked for me: I've logged in with sa account to SQL Management Studio and attached the database to the object explorer (Databases -> Right Click -> Attach).
Then I've opened Security->Logins->[myWindowsUsername] and edited User Mappings tab, giving dbowner rights to the attached database.
I'm sure you can do those things without Management Studio, with console commands, but I'm not that good with T-SQL and can't give you advice on that.
Mine was an EF code-first project and it comes up when the file has been deleted. Running Update-Database from the Package Manager Console makes the DB and its fine.
The error occurred because the AttachDbFilename parameter is set to an absolute path, which points to the wrong file location.
It's important to know, that the database .mdf file itself will be copied to the build target folder on every build by default or, if configured to Copy if newer using the file Property Explorer, only if the file version has changed (it is recommended to use Copy if newer to prevent the database from being overwritten on every build).
To fix the issue, the AttachDbFilename parameter should point to the current execution folder. It's best to use the Visual Studio environment variable |DataDirectory| to define the relative path.
A fixed connection string could look as follows:
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True;Asynchronous Processing=True;User Instance=False;Context Connection=False"
check your web-config file, there may be more than one connection string having same name
Please check the path for your database on the connection string. I have the same error message and I later found out that the problem is a misspelled path.
I've been trying mdf portability in my application, so I've been using
public DbContext IoDatabase()
{
var directory = System.IO.Directory.GetCurrentDirectory();
var connectionString = #"Data Source=(localdb)\mssqllocaldb;AttachDbFilename=" + directory + "\\App_Data\\ITIS.mdf;Integrated Security=True;Connect Timeout=30;";
return new NerdDinners(connectionString);
}
with nerdDinners, I can't remember where I found it, being
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
{
Database.Connection.ConnectionString = connString;
}
}
Then I can use the return type as a DbContext.
The main thing I ran into was that GetCurrentDirectory() gets the compiled file path, not the project file path, so deployment should be set to GetCurrentDirectory and the mdf should be copied on compile, not reference the actual App_Data. Include your mdf in your project and go properties on it. Set the copy to output directory.
I had the same problem with EF. The absolute path solution worked. But it is not a nice solution if you want to move your program to a new location. For me this was the problem.
VS searches the mdf file in the debug folder
There is an .mdf file in the project folder, sometime VS sync the two
files
For some reason the .mdf file was not synced into Debug
My workaround:
Copy the .mdf and .ldf file to a temp folder
Make a connection for it in vs/server explorer
When you add the ADO.NET use the new connection
VS offers to copy the .mdf file into the project folder, accept it
Now the .mdf file will appear in the debug folder as well
Delete the connection for the temp folder, create a new one to the project
folder
Just change your path with a new location.
How you will get a path?
Go to database >right click > go to the property > on right-side panel data source is there, copy that data source location and update into a web.config file (the only path has to take care and to look for in the AttachDbFilename in the database).
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\manish_data\project_practice\sqlbasedprojects\sqlbasedproject\realease\mainproject\App_Data\cruddatabase.mdf;
I also got the same error and I fixed the following (I use Visual Studio 2019):
Click to Debug > [project name] debug properties, select the build item in the left sidebar. On the right sidebar, navigate to the output path entry and change bin\debug to .\
Error was fixed for me after I changed this
ConfigurationManager.ConnectionStrings[0].ConnectionString
to this
ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString
I have changed the installation folder from program files to C directory while I am installing the app. then my problem is solved
well I think reason is that in your database directory, contains a .mdf file which has the same name. So best thing is to give the full path you can just replace the AttachDbFilename. just simply get the fullpath of the database file and assign it into the AttachDbFilename which is in app.config file.
In most cases, the unit test project is separated from the main project.
This causes the generated connection string to be invalid as it fails to find an app_data folder, if your db is local to the solution.
You can just replace the |DataDirectory| with a relative path to your db in your main project if you need to connect to it from your unit test project.
what I've found so far to solve the problem, if you create mdf file in the below way, it would work just fine for visual studio.
Right-click on the data connection in the server Explorar->add connection->Select Microsoft SQL Server Database File and choose database name and select okay. Then this prob doesn't arise.
Follow the video:
youtube link
Looks like there are lots of causes for this...Here was mine.
The clue was on the last line of the error message...
System.Data.SqlClient.SqlException: 'An attempt to attach an
auto-named database for file Q:\Folder\FileName.mdf failed. A database
with the same name exists, or specified file cannot be opened, or it
is located on UNC share.'
...or it is located on UNC share.
In trying to replicate a production environment...
I originally had physical drive Q:. After my dev machine tanked..I rebuilt and just created a mapped drive.
Started getting this error...and then went back and just created another Q: partition and the problem was solved.
I had a similar problem after i moved my db to a folder within the same project.
All i had to do finally was to to properties of the database, copy the path listed under 'identity' and replaced the path at 'AttachDbFilename='.
Worked just fine.
Try this, it works for me
try {
String ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\App_Data\Test.mdf;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True";
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
MessageBox.Show("Connection is opened.!!");
connection.Close();
} catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
TLDR: May need to make the change as mentioned by HasanG in multiple files, such as App.config and Settings.Designer in my case.
To add on to HasanG's answer, there may be multiple locations that you need to change the path for your ConnectionString. In my case, I wasn't getting data persistence between two runs of the debugger and changing the ConnectionString defined in my Settings.Designer file fixed this. However, after closing and re-opening Visual Studio and running the debugger again I found that I wasn't getting persistence after Visual Studio was closing. I would either end up with an empty DataGridView or would get an error at build-time stating the following:
*An attempt to attach an auto-named database for file <database file path in debug folder> failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.*
I then searched my entire project solution for instances of that file path and found that it was also being used in the App.config file. Once I changed the path in that file as well as in the Settings.Designer file I was able to have data persistence in my DataGridView between multiple runs of the debugger, and across multiple runs of Visual Studio itself. Hope this helps someone! I pulled out a lot of hair over this one.
EDIT: Make that three files, the Settings.Settings file had to be updated as well.
In .net core 5 for create Db.mdf file in Data folder :
connection string in appsettings.json :
"DefaultConnection": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=projectPath\\Data\\Db.mdf;Integrated Security=True;Connect Timeout=30"
options.UseSqlServer in startup.cs :
var projectPath = Directory.GetCurrentDirectory();
services.AddDbContext(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection").Replace("projectPath", projectPath)));
I had the same problem,and i think i figured it out.in the connection string make sure that the connection string looks like this:
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnetdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
<add
name="NorthwindConnectionString1"
connectionString="Data Source=localhost;
Initial Catalog=Northwind;
Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Now, the first
<add
name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnetdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
is what appears by default in the web.config. Leave it unchanged,and add another connectionstring
<add
name="NorthwindConnectionString1"
connectionString="Data Source=localhost;
Initial Catalog=Northwind;
Integrated Security=True"
providerName="System.Data.SqlClient" />
with your parameters. This is working for me. Hope it helps.

Web Site Administration Tool ERRORS

I try to use Web Site Administration Tool to set up Roles in my website.
I receive an error testing "AspNetSqlProvider"
"Could not establish a connection to the database.
If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider."
I used aspnet_regsql command-line utility successfully and in Visual Studio I can see in Server Explorer the database and all the tables.
WebConf is empty
What the problem could be? thanks
I've hade the same problem as you before. If you check your web.config you need something like this:
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer"
connectionString='YOUR CONNECTIONSTRING HERE'
providerName="System.Data.SqlClient"/>
</connectionStrings>
The important part was the remove LocalSqlServer and that the new connectionString was named the same. Hope this helps.
If you have correctly set up the web.config and still get this error I almost guarantee it is because you have an open connection to it in visual studio which blocks the connection.
Solution:
In visual studio right click the connection to the database (which probably has a 'connected' icon) and click 'close connection'
Reattempt to access the membership administration tool.
et voila

Very slow response for Visual Studio 2005 Web Site Administration Tool

I am working on an ASP.NET application and am trying to add user authentication. As a first step, I am using the Web Site Administration tool (Website | ASP.NET Configuration) to manage users and permissions.
Accessing this website is incredibly slow. To load the main page takes 30 seconds. When navigating to the Security page (also 30 seconds), I am presented with this error:
I have authentication mode set to "Forms" in the web.config file.
There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store.
The following message may help in diagnosing the problem: Unable to connect to SQL Server database.
It asks me to run "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe", which also gives me an error message.
How do I fix these problems with speed and enabling security/users?
The issue that you are getting is due to an invalid SQL Server connection, you can setup the SQL Server connection in the web.config, once it is able to actually connect to the database, it will perform in the proper manner.
EDIT below is the code needed in web.config to setup the new connection
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="server=yourservername;database=somedatabasename;etc..." />
</connectionStrings>

Resources