What's the difference between app.config's connection string and c# connection string - connection-string

Is there any difference between the following two lines of code in c# and app.config file.
C# connectionString declaration.
string conn = "/server = test/ DB = test_dev/ env = dev"
and
app.config declartion
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=test_dev;" providerName="System.Data.SqlClient" />
</connectionStrings>
How can I declare c# connection string to the format in the app.config file so that I can read from the app.config file.

There's no real difference between hard coding a connection string and pulling one out of the app.config file.
The advantage of using app.config is that you can use that same connection string in multiple places in your application, and then if you need to change it (for testing purposes or anything else really), you only have to change it in one spot that is nicely contained in a configuration file.
As mentioned in the comments, to read a connection string directly from your app.config, you can use this:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Test"];
although there are many different ways to access the connection string (DataSet, etc.)

To read connectionString values in your C# code, you can access System.Configuration.ConnectionStringSettingsCollection
System.Configuration.ConfigurationManager.ConnectionStrings
will return collection of all connection strings defined in <connectionStrings></connectionStrings> section
You can access connection strings by name using
string conn =
System.Configuration.ConfigurationManager.ConnectionStrings["Test"];

Related

SQL Server connection string in Appsettings.json + .net Core 3.1

I'm trying to setup and connect to my remote development SQL Server (SQL 2017) in appsettings.json within .NET Core 3.1, I have tried the following approaches yet without any success.
"ConnectionStrings": {
//"DefaultConnection1": "DATA SOURCE=[servername];UID=[username];PWD=[password];DATABASE=[databasename]",
//"DefaultConnection2": "Data Source=[servername]; Initial Catalog=[databasename];User ID=[username];Password=[password]",
//"DefaultConnection3": "DataSource=[servername];Initial Catalog=[databasename];User Id=[username];password=[password]",
"DefaultConnection4": "Server=[servername];Database=[databasename];User Id=[username];password=[password];Trusted_Connection=False;MultipleActiveResultSets=true;"
},
Error of DefaultConnection1:
ArgumentException: Keyword not supported: 'uid'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword))
Error of DefaultConnection2:
ArgumentException: Keyword not supported: 'initial catalog'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword)
Error of DefaultConnection3:
ArgumentException: Keyword not supported: 'initial catalog'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword)
Error of DefaultConnection4:
ArgumentException: Keyword not supported: 'server'.
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder.GetIndex(string
keyword)
Any ideas, pointers or help is much appreciated.
thanks for your help and advice, i might have just found the solution and am able to connection the SQL database successfully now, the problem was as following:
The following package was installed on the solution:
Microsoft.Data.Sqlite.SqliteConnectionStringBuilder
in Startup.cs the following line was used in the ConfigureServices(IServiceCollection services):
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlLite(Configuration.GetConnectionString("DefaultConnection")));
However after research i found out that i should rather use the following line:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Which was not accessible due the following package missing:
Microsoft.EntityFrameworkCore.SqlServer
After installing this package via package Manager using the following command:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
I was able to access the SQL server using the following connection string:
"ConnectionStrings": {
"DefaultConnection": "Server=[servername];Database=[databasename];Persist Security Info=True;User ID=[username];Password=[password];MultipleActiveResultSets=True;"
},
For safety, as Christian pointed out, I removed also the other connectionstring references.
Probably it's just because you're not supposed to put comments (//) in JSON as JSON is a data format and doesn't support comments. So try actually removing the lines starting with // from your config.
Your setup in appsettings.json is fine.
Suppose the model in your cs file is mytestModel.
Here is the code to read the connection string:
public class mytestModel : PageModel
{
public string connectstring = "";
private IConfiguration MyConfiguration;
public mytestModel (IConfiguration _configuration)
{
MyConfiguration = _configuration;
}
public void OnGet()
{
connectstring = this.MyConfiguration.GetConnectionString("DefaultConnection4");
}
}
It should be noted that the type of model (eg. PageModel) does not matter. The name of the model is what matters.

ArgumentException was unhandled by user code: (System.ArguementException) occurred in System. Data.dll

I was following an online Tutorial and i am very new to programming.
Additional information: Keyword not supported: 'server: xxxxx;database
Here's my Code:
Dim sqlCon As New SqlConnection With {
.ConnectionString = " Server= xxxx;Database = ist2gx;User= Ist2gx;Password=hnu91p;Trusted_Connection= True;ProviderName=SqlClient"
}
Please can someone help me out.
ConnectionString does not have a property named ProviderName in it. ProviderName is different from provider property in ConnectionStrings string.
You should change ProviderName=SqlClient with Provider=sqloledb for OLEDB connection strings.
Sql ConnectionString for a standard connection with username and password:
`"Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;Provider=sqloledb"`
Sql ConnectionString for a trusted connection:
`"Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;Provider=sqloledb"`
For more info take a look at Connection Strings for different providers and SQL Server connection strings.

How to Dapper & AseClient

Unable to connect to Sybase, not getting error.
I have referenced Sybase.AdoNet4.AseClient.dll from C:\Sybase\DataAccess\ADONET\dll to my MVC 5 project, running in .NET 4.5
Web.Config Connections string
<add name="MyASEServer" connectionString="Data Source=127.0.0.20:12000;Initial Catalog=MyDB;User Id=USer1;Password=Password1;"
providerName="Sybase.Data.AseClient"/>
My code
string constr = ConfigurationManager.ConnectionStrings["MyASEServer"].ConnectionString;
IDbConnection aseDB = new AseConnection(constr );
var myCustomer = aseDB.Query<Customer>("select * fromdbo.customer");
When the debugger reaches aseDB.Query...., it never return and not receiving any error.
What am I missing.
In this case, Application Insights is on in visual studio and all the exceptions are captured in it. So the application screen is not showing the exception.

SSRS 2014 invalid namespace

I am trying to set up forms authentication on Reporting Server 2014. So far I was able to get rid of most of the errors but when trying to log in on reportserver/logon.aspx I get the following error:
An error occurred while attempting to get the ReportServer Url. Invalid namespace
I applied the following in web.config:
<add key="ReportServer" value="localhost"/>
<add key="ReportServerInstance" value="RS_SKOREPORTS"/>
The following is from my reportingservices.mof:
#pragma namespace ("\\\\.\\root\\Microsoft\\SqlServer\\ReportServer\\RS_SKOREPORTS\\V12")
I've tried several things like removing the RS_ prefix but the error remains.
EDIT:
Ok, I have come to the point where I know what's wrong by debugging everything, I just don't know how to fix it. My wmiNamespace string is adjusted for report server 2014 as follows: private const string wmiNamespace = #"\\{0}\root\Microsoft\SqlServer\ReportServer\RS_{1}\v12";
The weird thing is that when I debug the login process and put a watch on fullWmiNamespace the value it returns is:
"\\\\localhost\\root\\Microsoft\\SqlServer\\ReportServer\\RS_SKOREPORTS\\v10"
It looks like report server ignores the changes I made in AuthenticationUtilities.cs and just uses the unmodified version.
Fixed by hardcoding the wmiNamespace string. For some reason the FullWmiNamespace string didn't format the string properly..

NServiceBus with Sql Server Transport Error

I have configured NServiceBus to use Sql Server.
Configure.With()
.AutofacBuilder(container)
.UseTransport<SqlServer>("aureus")
.InMemorySubscriptionStorage()
.UnicastBus()
.DisableTimeoutManager()
.CreateBus()
.Start();
When I send a message in the controller.
this._bus.Send(new BillClient { Value = "testing." });
I get the error.
Failed to send message to address: [queue]
Invalid object name 'queue'.
My configuration is as follows:
<UnicastBusConfig>
<MessageEndpointMappings>
<add Assembly="Aureus.Messages" Namespace="Aureus.Messages" Endpoint="queue"/>
</MessageEndpointMappings>
</UnicastBusConfig>
What have I missed? I can't find out if I need to run scripts / or initialise the queues?
Instead of
.Start()
You need
.Start(() => Configure.Instance.ForInstallationOn<Windows>().Install());
To kick off the initialization of the queues.
I'm no expert but I had to use the ConnectionString definition as the argument to .UseTransport() as shown below. In your post it's not clear what "aureus" will mean to NServiceBus software.
.UseTransport<SqlServer>(ConnectionString())
string ConnectionString()
{
return "NServiceBus/Transport\" connectionString=\"Data Source=.\\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True";
}
I was not able to use the ConnectionString name from my config file as an argument either. Here's the section of my config file fyi:
<connectionStrings>
<!-- Message Bus ********************************************** -->
<add name="NServiceBus/Transport" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True" />
<!-- Message Bus ********************************************** -->
</connectionStrings>
Also, for Endpoint in my config file, I had to use the namespace of my NServiceBus message handler class. Here's the endpoint section of my config file:
<UnicastBusConfig ForwardReceivedMessagesTo="audit">
<MessageEndpointMappings>
<!--Note - Endpoint must specify the Namespace of the server-->
<add Assembly="My.Messages.Assemblyname" Namespace="My.Messages.AssemblyNamespace" Endpoint="MyMessageHandlerAssy.Namespace" />
</MessageEndpointMappings>
</UnicastBusConfig>
Hope that helps you a bit.

Resources