How to resolve database connection string problems in asp.net? - asp.net-mvc

I am developing an asp.net mvc3 application using Visual Studio 2010.I need to access the database.
I wrote the connection string as
SqlConnection conn = new SqlConnection("Data Source=./App_Data/Abcd.mdf;Integrated Security=True;User Instance=True");
But, when I run the code, I get an error: 40 - Could not open a connection to SQL Server.
From the SQL Server Configuration Manager, I enabled TCP/IP but I still get the same exception.
I also tried changing the connection string to
SqlConnection conn = new SqlConnection("System.Configuration.ConfigurationManager.ConnectionStrings.ConnectionString");
But I got an exception that said "Format of the initialization string does not conform to specification starting at index 0."
How do I overcome this problem?
Thank you in advance for your help.

This will depend on the type of database you are using: SQL Express or SQL Developer/Standard. If you use SQL Express you may take a look at the following article illustrating different connection strings. For example:
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Abcd.mdf;Integrated Security=True;User Instance=True
If you are using the full version of SQL Server, your database is no longer stored in the App_Data folder. It is managed by SQL Server. Checkout the following site for connection strings in this case depending on your scenario.
Example:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

SqlConnection conn = new SqlConnection("Data Source=.\sqlexpress;database=dbname;AttachDbFilename=|DataDirectory|\Abcd.mdf;Integrated Security=True;User Instance=True");
or
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("webconfigconnectionname").ConnectionString);

In VS click on server explorer and add the connection
when the connection has been setup right click on the established connection and select properties
you will get the properties window open. In that window select the connection string, which you can use in the sqlconnection

Related

Web API in ASP.net C#

I want to create a web API controller that returns product details with id. Using stored procedure calls from a database class, not DB context. Sending Request with ID & getting a response with Jason's values.
I saw many examples but they are directly using stored procedures from the DB context. But I want to introduce a connection string & call that method in business class than a business class call to the controller with the response return.
Please help with a small example
Here is one example. You can choose between using SQL Command or SQL Adapter, try searching a little bit more about it.
Programming isn't only writing a code it's also googling for solutions.
// Setup connection string to access local SQL Server 2000
string connectionString = "server=localhost;" +
"database=Northwind;uid=sa;pwd=manager";
// Instantiate the connection, passing the
// connection string into the constructor
SqlConnection con = new SqlConnection(connectionString);
// Open the connection
con.Open();
// Create and execute the query
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers",con);
SqlDataReader reader = cmd.ExecuteReader();
// Iterate through the DataReader and display row
while(reader.Read()) {
Console.WriteLine("{0} - {1}",
reader.GetString(0), reader.GetString(1));
}
Source

Connection string not working in ASP.NET Core

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=ABC; Trusted_Connection=True; MultipleActiveResultSets=true"}
I am working with ASP.NET Core MVC. I have this connection string in my appsettings.json file but it doesn't seem to work. While running "dotnet ef database update" from cmd, I am getting this error keyword not supported: 'server.'. What's wrong with it?
Apologies! In my ConfigureServices method in Startup.cs, I was using SQLite database provider
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")))
I changed it to the following, and it worked with my connection string.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))
The connection string should start of with Data Source=.
In Visual Studio if you open the SQL Server Object Explorer and click on the database you are wanting to connect to. The connection string will be displayed in the Properties window. The connections string should look something like this for localDb
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DbName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=Fals

Sybase iAnywhere.Data.SQLAnywhere.SAException : DSN database name does not exist

My Application is in MVC 4 with Sql Anywhere 16 ODBC using Entity framework. I used Visual studio 2010. requirement is multi tenant so i created connection string dynamic on my Global.asax and once main database has been connected i create connection string of user based database on my Account controller.
Application run well when i run by visual studio. but when i publish this application on IIS 8.5 and load application on browser it shows below error.
<ErrorType>System.Data.EntityException: The underlying provider failed
on Open. ---> iAnywhere.Data.SQLAnywhere.SAException: DSN 'MainDB'
does not exist at iAnywhere.Data.SQLAnywhere.SAConnection.Open()
at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure) --- End of inner
exception stack trace --- at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure) at
System.Data.EntityClient.EntityConnection.Open() at
PDMSReporter.Controllers.AccountController.Login(LoginModel Login) in
E:\Projects\Triforce_PDM
Reporter\Latest_PDMSReporter\PDMSReporter\PDMSReporter\Controllers\AccountController.cs:line
56</ErrorType>
<ErrorDesc>The underlying provider failed on Open.</ErrorDesc>
I tried a lot to fix this issue. but didn't find any proper solution for it.
Please help me to fix this issue or suggest post where I can solve it.
The error message tells you: "DSN 'MainDB' does not exist". Your connection string is using a DSN that the client cannot find. This could be because you are creating a user DSN rather than a system DSN - if your client is running as a service (i.e. in IIS), it can't read user DSNs.
If you're creating the DSN using the dbdsn utility, make sure you use the -ws switch instead of -w.

Cannot drop database because it is currently in use MVC

I'm brand new to using MVC, and I'm trying to use an initializer to initialize data into my DB when the application is first started. Here is what I've got in Global.asax.cs:
System.Data.Entity.Database.SetInitializer(new MyAppInitializer());
MyAppContext db = new MyAppContext();
db.Database.Initialize(true);
In Web.config, here is my connection string:
<connectionStrings>
<add name="MyAppContext"
connectionString="data source= MyServer; Integrated Security=True; database=MyDatabase"
providerName="System.Data.SqlClient"/>
This is using MS SQL 2008 R2. My Initializer looks like this:
public class MyAppInitializer : DropCreateDatabaseAlways<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
var organizations = new List<Organizations>
{
new Organizations { OrgName = "AT", OrgPhone = 5093333433, OrgOfficeLocation = "ITB", OrgPointOfContact = "Tony", OrgIsActive = 1 },
new Organizations { OrgName = "Libraries", OrgPhone = 5093331122, OrgOfficeLocation = "Holland-Terrell", OrgPointOfContact = "Herald", OrgIsActive = 1 }
};
organizations.ForEach(s => context.Organizations.Add(s));
context.SaveChanges();
I made sure I closed my connection to the server and database in SQL Server Management Studio, but multiple people have access to this DB, although none should be using it right now. How can I get it so I can initialize this data in my DB? Thanks!
Edit: I've already got the DB created on the server, but it is completely empty (no tables, procedures, etc). Would this cause an issue?
I faced a similar issue today when using MVC codefirst. After 20 mins of trying out various stuff I noticed that, the "Server Explorer" tab in Visual Studio had a connection open to my database. After I "closed" the connection in the server explorer tab of visual studio, the code was able to run and automatically recreate the database.
In SSMS run something like this...
USE master -- be sure that you're not on MYDB
ALTER DATABASE MYDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE MYDB;
As described by Vardhini... close DB connection in Server Explorer.
In the SSMS "Delete" window make sure that "Close existing connections" is checked.
Closing all existing connections of the database in visual studio server explorer and SQLManagement studio solved the problem for me.
My observations are:
Cannot be logged in to application
Cannot be connected to db with Server Explorer
Cannot be connected with SSMS
Then the application rebuild DB even when Database.SetInitializer<DbContext>(new DbInitializer()); is in public DbContext(); - NOT as other answears stand to put it into Application_Start();

How do I connect to a local Microsoft Sql server 2012 Express database from a C# program?

Can someone please help me fix my connection string? I am an absolute beginner using the MS SQL Management Studio but I am an experienced C# programmer. I am trying to figure out how to connect to a local database on my PC. I just installed SQL server 2012 Express today and I created a table with one row of data. I am trying to access that table from a C# program. I've been looking for help calling a stored procedure (with no parameters) and it seems like I am doing everything right, but I get an exception error "Could not find stored procedure 'GetCustomers'." I have also tried changing my the procedure name to "dbo.GetCustomers" and also "SqlTest.dbo.GetCustomers" and also "SqlTest.GetCustomers", but nothing seems to work. Clearly I am not connecting to my database correctly. I've been working on this for 4 hours now so it's time for me to stop and find help. I think all I need is a good connection string and the proper syntax for the procedure.
Connect c = new Connect();
if(c.MakeConnection())
{
try
{
DataSet data = new DataSet();
SqlDataAdapter adaptor = new SqlDataAdapter();
//changed to use stored procedure
adaptor.SelectCommand = new SqlCommand("GetCustomers", c.MyConnect);
adaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
//adaptor.SelectCommand.ExecuteNonQuery();//this throws an exception.
adaptor.Fill(data);//this throws an exception.
}
catch (Exception e)
{
Logger.WriteMessage(e.Message);
}
finally
{
c.CloseConnection();
}
My connection class contains the following:
string connection = Properties.Settings.Default.DatabaseConnectString;
sqlConnection = new SqlConnection(connection);
sqlConnection.Open();
Connection string I have tried which seem to connect OK:
Server=(localdb)\v11.0;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Integrated Security=true;
My Database name is SqlTest. I have tried several variations in my connection string, but most of them throw a logon failed exception error. I verified that my windows user ID has admin privileges for the database.
Connection strings I have tried which cive me logon errors:
Server=(localdb)\v11.0;Initial Catalog=SqlTest;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Initial Catalog=dbo;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Integrated Security=true;
I guess all I needed was some sleep. ;-)
I needed to set all of my SQL server services to Automatic. For some reason, they were set to manual, and so they were not started.
Then, I also needed to set the correct server name in my connection string. This is the same server name that is used to logon when starting SQL Server Management Studio. Here is a connection string that connects and accesses the correct database and table:
Server=RAPHAEL\SQLEXPRESS;Database=SqlTest;Trusted_Connection=Yes;

Resources