I used to work only with asp.net websites before. I know that in ASP.NET website, the connection string is found in the web.config file.
My problem is now I have started working with VB.NET applications which needed to be interfaced to a database. How is a connection string created and where should I put it?
Thanks!
Here's the whole app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbAsthmaConnectionString" connectionString="Data Source=9300-00\SQLEXPRESS;Initial Catalog=dbStore;Persist Security Info=True;User ID=johnsmith;Password=1234" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
Ok here is an axample :
1- Your app.config should look like this :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Amlakconn" connectionString ="Data Source=KHASHAYAR-PC\SQLEXPRESS;Initial Catalog=Amlak;Integrated Security=True"/>
</connectionStrings>
</configuration>
2- and in your code you can access the connectionsttring this way :
private string conn = ConfigurationManager.ConnectionStrings["Amlakconn"].ConnectionString;
go try It ;)
The other answers tell you where to put the connection string: http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx
This is the easiest way to create a Connection String.
a) Create a Text file, rename the extension from TXT to UDL, press enter.
b) Double click the UDL file and choose OLEDB Provider For SQL Server > Next > type the Database Server name > Select the database and click Test Connection.
c) When the Test passes, close the UDL file and open it with notepad, the bold lines are the connection string:
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YourDatabase;Data Source=SQLEXPRESS
If you are working on a webapp project It's the same ! you can put that in the web.config file , and if you project is win app you can add an app.config file to your project and pu the connection string in there !
Non ASP.NET application can also use config file, it is just not named web.config. This file has exactly the same structure you know from ASP.NET including ConnectionStrings section. You can copy content from web.config and paste sections you need into app.config. In project it will show as app.config but in the bin folder it is named after the executable file name (with exe extension) plus ".config".
To create this file, go to project's Add -> New Item and select Application Configuration File. To get access to your connection strings create/copy <ConnectionString> section into <configuration> section and then use this code:
string conStr = ConfigurationManager.ConnectionStrings["ConStringName"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Users", conStr);
You need to add reference to `System.Configuration' assembly.
Related
I have followed Microsoft's instructions here in order to encrypt my connection strings for my application. I have opted to move my connection strings to their own configuration file, connections.config. My code is as posted below (bottom of page) - nearly identical to the snippets provided by Microsoft. After performing the operations, the command: MessageBox.Show(String.Format("Protected={0}", connectionStringsSection.SectionInformation.IsProtected)) prints True, indicating the operation was successful.
However, Microsoft states that "The following configuration file fragment shows the connectionStrings section after it has been encrypted:"
configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAH2... </CipherValue>
</CipherData>
</EncryptedData>
This does not appear to be true in my case. Despite printing True when asking if my sectionInformation.IsProtected, Both my app.config and my connections.config files remain unchanged when visually inspecting them. This leads me to my questions:
Does the description of my problem indicate that in fact my section is not protected after all?
Why is sectionInformation.IsProtected printing True, but no <EncryptedData> attributes have been added to my sectionInformation?
If you carefully read Microsoft's instructions in the link above, they provide explanations for creating both your own connections.config file outside of app.config, as well as encrypting your connections section. However, they do not explicitly say that following their instructions for encrypting connectionStrings section will do so in the external configuration file, connections.config as well. Is the attribute tag in app.config, <connectionStrings configSource="connections.config" />, sufficient to ensure this behavior?
How do I test that my application's connection strings are indeed encrypted correctly, other than a MessageBox printing the IsProtected property?
NOTE
This is NOT an ASP.Net application, this is a Winforms application
I have tested the above with my connectionStrings in both their own connections.config file, as well as within app.config file, and the result is the same.
The relevant sections of my code are posted below:
*app.config*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- ... -->
</configSections>
<system.diagnostics>
<!-- ... -->
</system.diagnostics>
<userSettings>
<!-- ... -->
</userSettings>
<connectionStrings configSource="connections.config" />
</configuration>
*connections.config*
<connectionStrings>
<!--Manhattan Connection-->
<add name="MANHATTAN"
connectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=False;Integrated Security=False" />
<add name="DENVER"
connectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=False;Integrated Security=False" />
<add name="DESMOINES"
connectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=False;Integrated Security=False" />
</connectionStrings>
*The connection source code*
Private Sub ToggleConfigurationEncryption(ByVal executableName As String)
Try
Dim configManager = ConfigurationManager.OpenExeConfiguration(executableName)
Dim connectionStringsSection = configManager.GetSection("connectionStrings")
If connectionStringsSection.SectionInformation.IsProtected Then
connectionStringsSection.SectionInformation.UnprotectSection()
Else
connectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
End If
configManager.Save()
MessageBox.Show(String.Format("Protected={0}", connectionStringsSection.SectionInformation.IsProtected))
Catch ex As Exception
ExceptionController.LogException(ex)
ExceptionController.DisplayException(ex)
End Try
End Sub
Your issue is happening in your if statement.
If connectionStringsSection.SectionInformation.IsProtected Then
connectionStringsSection.SectionInformation.UnprotectSection()
...
This example shows how to toggle between encrypting and decrypting. In the code posted by you, you're simply decrypting the file if it's already encrypted. Your code should be something like this:
If (Not connectionStringsSection.SectionInformation.IsProtected) Then
connectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
End If
You only want to encrypt if the file has not been encrypted. Don't worry about decrypting the file and trying to read. It will automatically decrypt it for you.
I don't see the how you're calling the ToggleConfigurationEncryption method. You need to pass the correct name of the output config file. After you launch your app (if in debug mode) you can go to project directory in bin\debug folder and look for your connections.config file. When you open it you'll see that it's encrypted.
I have a app.config xml file to save entity framework's connection strings as the following example:
<configuration>
<connectionStrings>
<add name="MyEntities" connectionString="metadata=res://*/EntityFramework.MyEntities.csdl|res://*/EntityFramework.MyEntities.ssdl|res://*/EntityFramework.MyEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=myserver;initial catalog=Example;persist security info=True;user id=myId;password=myPassword;multipleactiveresultsets=false;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
But I'm using ASP.NET Core, I manage multiple servers with an enviroment variable. so I need to save this connection string in my appsettings.{enviroment}.json, read this connection and set to the property entity framework context.
I think you are looking for something like the following construction.
"ConnectionStrings": {
"MyEntities": "metadata=res://*/EntityFramework.MyEntities.csdl|res://*/EntityFramework.MyEntities.ssdl|res://*/EntityFramework.MyEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=myserver;initial catalog=Example;persist security info=True;user id=myId;password=myPassword;multipleactiveresultsets=false;application name=EntityFramework"
}
Not sure if this is the correct way to do this, but this may be a good starting point for you. I've added the configuration settings into the file named app.config. It appears that the contents in the files are written into the exe's config file. When the exe is executed the config settings are also loaded. I have just starting experimenting with .NET Core, so this may not be the recommended or correct way.
<configuration>
<runtime>
<gcServer enabled="true"/>
</runtime>
<connectionStrings>
<add name="TestName" connectionString="data source=MyServer;initial catalog=MyDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I have an application that runs on SQL 2005 database
I m trying to use same application on another machine same network,
I managed to log in on SQL 2005 using IP
Now I need to configure applications app.config file (found in visual studio solution) to allow connection
soo far I tried this connection string which isn't worked
this is what my config file looks like
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=ipaddress,1433;Initial Catalog=sample;User ID=sample;Password=sample;Trusted_Connection=True;" />
</appSettings>
</configuration>
Any help would be appreciated
Add this to your config file. Rather then using an appSetting use the actual connectionStrings section.
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=00.000.0.00,1433;Initial Catalog=taxi;Persist Security Info=True;User ID=sample;Password=sample; providerName="System.Data.SqlClient" />
</connectionStrings>
This string should work if anyone else got the same problem
thanks everyone for looking and trying to figure it out with me
<add key="ConnectionString" value="Data Source=00.00.000.000;Initial Catalog=sample;User ID=sample;Password=sample;" />
I am working with the existing structures used by the dev team at my current company. In order to change connection strings within the application, the team creates an XML node called "defaultDatabase" (see below):
</configSections>
<dataConfiguration defaultDatabase="Development" />
<connectionStrings>
<add name="Development" connectionString="Data source=DVHQSQL01; Initial Catalog=db; User ID=id; Password=password"/>
</connectionStrings>
...there will be more connection strings in the XML for different server environments (not shown here, but "Testing", "Staging", "Production", etc)
I am creating a class with different functions that use the default connection. I know one route is through ConfigurationManager as shown here:
https://social.msdn.microsoft.com/Forums/en-US/9a8c9f5a-092e-4c4a-87bb-9f35d8f55da1/get-connection-string-from-appconfig-file?forum=adodotnetdataproviders
This is great if you can change the connection string name in code, but we use the defaultDatabase node to be able to change from different environments without rebuilding.
Does anyone have experience with this methodology? How do I get the correct connection string using the defaultDatabase node?
Just set the default connection in the connection strings area:
<connectionStrings>
<add name="default" connectionString="..."/>
</connectionStrings>
If you have further connections you can add them in the same way:
<connectionStrings>
<add name="default" connectionString="..."/>
<add name="special1" connectionString="..."/>
<add name="special2" connectionString="..."/>
</connectionStrings>
You can have as many connectionStrings as you want in your config, all you have to do is give them different names.
<connectionStrings>
<add name="default" connectionString=""/>
<add name="anotherOne" connectionString=""/>
...
</connectionStrings>
I am developing asp.net mvc2 application and I use asp.net membership provider which uses ASPNETDB.mdf database. I have also my own database and now I wonder how to upload these 2 databases to server? Should I upload them as .mdf file or should I use SQL server? I prefer using SQL server and if someone knows the shortest way to convert and upload these 2 databases it would help me a lot.
Thanks in advance,
Ilija
Funny I just finished doing the same thing. The basic steps are as follows:
From Visual Studio, load your .mdf and choose "publish to provider" to make a .sql file.
Open SQL Management Studio, open a connection to your database and load the sql file. Add a "use yourdbname;" on top to have it output the tables to your database, then run it.
Now you should have the full table structure. What's left is to modify web.config to read the new tables:
First the membership provider:
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a "
connectionStringName="ConnectionStringLoginInfo"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="/"
/>
</providers>
</membership>
Now the role provider:
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a "
connectionStringName="ConnectionStringLoginInfo"
applicationName="/"
/>
</providers>
</roleManager>
And lastly the WebPart provider, if you use it:
<webParts>
<personalization defaultProvider="SqlDatabaseProviderDRDBLoginInfo">
<providers>
<clear/>
<add connectionStringName="ConnectionStringLoginInfo"
type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"
name="SqlDatabaseProviderDRDBLoginInfo"/>
</providers>
</personalization>
</webParts>
In this example I called the connection string ConnectionStringLoginInfo, but whatever you name it, make sure you set it in the connection strings part. Not gonna paste that too :)
This all took me way more than I care to say, but when I saw my app working flawlessly with the App_Data folder deleted, that was quite the moment!
Your simplest option for a hosted solution (i.e. your hosting plan is not a Virtual Private Server) is to generate SQL scripts of your database, exporting these to *.sql files and then run them in your hosted SQL connection.
I would normally connect to my web host's SQL instance using SQL Server Management Studio and either open or paste in the scripts generated by my local copy.
Depending on whether or not your web host provides the service, you might also be able to use the "Publish to provider..." option in Visual Studio.
As a supplement to Blindy's answer I wanted to mention that another way to configure the providers is to change the connection string settings of the default ConnectionString used by most of the providers, which is LocalSqlServer. To do this you just override that particular ConnectionString in your web.config like so:
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="change this to be the details of your host database" providerName="System.Data.SqlClient" />
</connectionStrings>
Also, if you don't want to clear the entire connectionStrings section you can just remove the particular connection string like this:
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="change this to be the details of your host database" providerName="System.Data.SqlClient" />
</connectionStrings>
This works, because all providers that default to using Sql Server for their Data Store - such as the membership provider - use the "LocalSqlServer" connection string by default. Thus, if you override it, you don't have to change each provider to point to a different Connection String.
Also, for security reasons, you might want to look into encrypting the connectionString section of your web.config file. The following two articles provide more info.
Encrypting and Decrypting Configuration Sections
How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA