Not able to connect to SQL Server using configuration manager - sql

I am trying to connect to a SQL Server database using the configuration manager.
The config file code:
<connectionStrings>
<add name="DBCS"
connectionString="data source =.\\SQLEXPRESS; database = Sample2; integrated security = SSPI;"
providerName ="System.Data.SqlClient" />
</connectionStrings>
The C# code below:
string SC = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//string SC = ("data source =.\\SQLEXPRESS; database = Sample2; Integrated Security = SSPI;");
SqlConnection con = new SqlConnection(SC);
SqlCommand cmd = new SqlCommand("Select * from tblemployee", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
When I try to run the application I get an error at
con.Open();
Error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Instance failure.
Please help.

You need only one \ before SQLExpress in your connection string:
<add name="DBCS"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS; database = Sample2;Integrated Security=SSPI"/>
Check the documentation for further details

Related

how to set connectionString for connect Database inside App_Data in Asp.net Core

Old Project
Web.config
Following ConnectionString use for App_Data Database Connection
<add name="MaContext" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|MaintenanceDB.mdf;Integrated
Security=True;User Instance=True" providerName="System.Data.SqlClient" />
Now I am using Asp.net Core With .NET 5
appsettings.json
"ConnectionStrings": {
"BCAContext": "Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MaintenanceDB.mdf;
Integrated Security=True;User Instance=True;"
}
Error

what would be the connection string for below in web.config?

I have written something like this but i am getting error as invalid username.
any suggestions?
You can simply set Connection String in the Web Config file and just reference it based on your requirements.. see below
Web Config:
<connectionStrings>
<add name="SQLDBConnectionString" connectionString="Data Source=<SERVER NAME>;Initial Catalog=<DATABASE NAME>;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then to get reference with the connections:
public string SQLServerDBConnstring()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["SQLDBConnectionString"].ToString();
}

How to debug this database connection string?

SqlConnection con = new SqlConnection("Server=ACER-PC/SQLEXPRESS;Database=coupon;Integrated Security=true");
What's wrong in this?
A connection string for SQL Server should look more like: "Server= localhost; Database= employeedetails; Integrated Security=True;"
If you have a named instance of SQL Server, you'll need to add that as well, e.g., "Server=localhost\sqlexpress".
If it is not windows authentication then connection string will look like this,
Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
try this
add this code in web config file
<connectionStrings>
<add name="ProjectConnectionString" connectionString="Data Source=ACER-PC/SQLEXPRESS OR Your system ip address;Initial Catalog=coupon;Integrated Security=false;user=username;password=password"/>
</connectionStrings>
then initialize your connection string like
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());

How to Manage sessions in SQL Server in Asp.net MVC

I have one solution, which has multiple projects in it, in which some
projects are developed using web form, MVC.
I need to share the session data between these projects. For this, i have
used SQLServer Mode in session state. I am able to store the session data
into database, but i am not able to retrieve the sessions data. So any
help will be appriciated.
Thanks in advance.
This is what i have tried to fetch data from ASPState database
public ActionResult Home()
{
ViewBag.Result =Session["username"].ToString();
SqlCommand cmd = new SqlCommand("select SessionId from
ASPStateTempSessions", con);
byte[] bytdata = new byte[50];
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
var list = new List<LoginUser>();
if(dr.HasRows)
{
while(dr.Read())
{
//obj=dr["SessionId"];
string obj = dr["SessionId"].ToString();
bytdata = System.Text.Encoding.UTF8.GetBytes(obj);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytdata);
BinaryFormatter bin = new BinaryFormatter();
//bin.Serialize(ms, bytdata);
//list = (List<LoginUser>)bin.Deserialize(ms);
string session = Convert.ToString(bin.Deserialize(ms));
}
}
ViewBag.Data = list;
return View();
}
This is what i have configured ion Web.config
<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="SessionSqlCon" cookieless="false" timeout="10" />
</providers>
</sessionState>

How to connect to OLEDB and ODBC in VB.net without using multiple objects

When using ADODB I was able to use a connection string that was either an OLEDB provider or an ODBC connection and use the same connection object. After converting over to ADO.NET and using the OleDB.OleDBConnection I found that you cannot specify an ODBC connection string because the .NET Framework Data Provider for OLE DB does not support the OLE DB Provider for ODBC (MSDASQL). I don't want to use multiple connection objects (System.Data.OLEDB and System.Data.ODBC) for data access because our program has data access in hundreds of places. How are people allowing connections to databases without using multiple connection objects? Thanks!
You can use the DbProviderFactory to abstract the data access. It allows you to obtain an instance of the correct connection type for each connection string object you throw at it.
Given the following connection string config:
<configuration>
<connectionStrings>
<clear/>
<add name="NorthwindSQL"
providerName="System.Data.SqlClient"
connectionString=
"Data Source=MSSQL1;Initial Catalog=Northwind;Integrated Security=true"
/>
<add name="NorthwindAccess"
providerName="System.Data.OleDb"
connectionString=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Northwind.mdb;"
/>
<add name="NorthwindODBC"
providerName="System.Data.Odbc"
connectionString="Driver=ODBCDriver;server=ODBCServer;"
</connectionStrings>
</configuration>
This will give you the appropriate connection:
//Read connection string
ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["NorthwindAccess"];
//Create connection
DbProviderFactory factory = DbProviderFactories.GetFactory(setting.ProviderName);
using(DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = setting.ConnectionString;
// Use the connection ...
DbCommand command = connection.CreateCommand();
// ...
}