I've effectively copied the first step I would use to connect to our DB from a C# project into VB.NET but VB 2010 Express is getting upset.
I have a winForms with an empty DataGridView. Behind this form I have added the following code:
In the App.config file I have the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="WH" connectionString="USER ID=xxx;PASSWORD=xxx;PERSIST SECURITY INFO=True;Data Source=xxx;Initial Catalog=WH" />
</connectionStrings>
</configuration>
At this point I thought I'd debug and I'm already getting an error:
What is the likely cause of this bug?
As an alternative, you could try creating a new settings file rather than using the ConfigurationManager class.
Say you create a file called ConnectionStrings.settings with a setting named WH, you can access the value via ConnectionStrings.Default.WH.
Related
I have done a windows application using vb.net and have set the connection string to be read from the app.config file. everything works fine, but when I try to change the connection string in the app.config file ( for example to change the database location) the application can't find the database anymore.
is there a problem or am I missing something related the connection strings. thank you
If you use MS Access database, you have to specify every database.
`<connectionStrings>`
<add name="ConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=|DataDirectory|\DatabaseName1.mdb;Persist Security Info=True"
providerName="System.Data.OleDb" />
</connectionStrings>
<connectionStrings>
<add name="ConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DatabaseName2.mdb;Persist Security Info=True"
providerName="System.Data.OleDb" />
Also, there is a specific path to every database. The best way is to use the asp.net database folder App_Data and put all databases in this folder.
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'm trying to parameterize an appSettings entry in my Web.config. Since this is a part of a quite long build process, I'd like to verify that my parameterization actually works before trying it out on our CI server (i.e. trial and error is not a good idea).
So, if I run MSBuild with /T:Package to create my package, I expect that the .zip file created would contain a Web.config with my appSetting entry tokenized, just like a connection string is tokenized.
But, so far I do not get my expected result. Is my assumption wrong?
Is it maybe that the tokenization/replacing happens first in the actually deploy-step?
Here's the tokenized web.config. Notice how my appSetting isn't tokenized:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<lots of stuff here...>
<connectionStrings>
<add name="DefaultConnection" connectionString="$(ReplacableToken_DefaultConnection-Web.config Connection String_0)" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="mySetting" value="monkey"/> <!-- Shouldn't monkey this be tokenized? -->
</appSettings>
<rest of web config here ...>
The con string tokenization is taken care of in the web publishing MSBuild targets. It's not a part of Web Deploy itself. In your scenario I'd expect that the package was created and app settings are not modified.
When the package is created there are two ways you can see the parameters:
Use msdeploy.exe and pass GetParamters - http://technet.microsoft.com/en-us/library/dd569044(v=ws.10).aspx
You can crack open the .zip file and look at the parameters file inside of it
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.