Save into app.config appSettings value - vb.net

I have following app.config. I would like save into ConnectionString key value - my text from serialized xml.
Private Shared strcon As String = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value=""/>
</appSettings>
<system.diagnostics>
<sources>
...
So far i got this code but i am receiving error: "Object reference not set to an instance of an object."
on the line: config.AppSettings.Settings("ConnectionString").Value = "myconn"
' Get the configuration file.
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' Update the setting.
config.AppSettings.Settings("ConnectionString").Value = "myconn"
' Save the configuration file.
config.Save(ConfigurationSaveMode.Modified)
' Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings")

Related

unable to retrieve value from app.config

Issue
I just want to be able to retrieve a value inside my App.Config file but it just does not seem to work.
The code to retrieve the value is:
Dim email As String = ConfigurationManager.AppSettings("stmpFromEmail")
My App.Config:
<configuration>
<applicationSettings>
<DataImport.DataImport.My.MySettings>
<setting name="stmpFromEmail" serializeAs="String">
<value>AgilityDataImport#agilitylogistics.com</value>
</setting>
</DataImport.DataImport.My.MySettings>
</applicationSettings>
</configuration>
I cannot seem to get the value back, help anyone?
Okay, you would have to change your app.config file to be like the below.
<configuration>
<appSettings>
<add key="stmpFromEmail" value="AgilityDataImport#agilitylogistics.com"/>
<appSettings>
</configuration>
Then you can call it like the below.
Dim email As String = ConfigurationManager.AppSettings("stmpFromEmail")

Unity Container Vb.net LoadConfiguration Exception

I'm currently using Vb.net in connection with the Unity Container model. But I can't get it to work.
My code is always failing in the Factory.
unity.config:
<unity>
<containers>
<container>
<types>
<type type="TestApplication.Interfaces.IBuilder, TestApplication.Interfaces" mapTo="TestApplication.Classes.Builder, TestApplication.Classes">
<lifetime type="singleton" />
</type>
</types>
</container>
</containers>
</unity>
I'm using a custom config source referenced in my App.config file.
The app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity configSource="unity.config" />
</configuration>
My Factory.vb looks like this:
Imports Microsoft.Practices.Unity
Imports Microsoft.Practices.Unity.Configuration
Imports System.Configuration
Public NotInheritable Class Factory
Private Shared registeredTypes As New Dictionary(Of Type, Object)
Public Shared Function GetInstance(Of T)(Optional asSingleton As Boolean = False) As T
Using container As UnityContainer = Factory.GetConfiguredUnityContainer()
Dim instance = container.Resolve(Of T)()
If (asSingleton = True And Not Factory.registeredTypes.ContainsKey(GetType(T))) Then
Factory.Register(Of T)(instance)
End If
Return instance
End Using
End Function
Private Shared Function GetConfiguredUnityContainer() As UnityContainer
Dim container As New UnityContainer
container.LoadConfiguration()
For Each item In registeredTypes
container.RegisterInstance(item.Key, item.Value)
Next
Return container
End Function
Private Shared Sub Register(Of T)(instance As T)
registeredTypes(GetType(T)) = instance
End Sub
End Class
The Factory fails at the line:
container.LoadConfiguration() in the GetConfiguredUnityContainer method.
A first chance exception of type System.Configuration.ConfigurationsErrorsException occured in System.Configuration.dll
I do have references to the mapped assembly. TestApplication.Classes also to the TestApplication.Interfaces
The interface is named IBuilder.vb and the class is named Builder.vb
References in the project:
Microsoft.Practices.Unity
Microsoft.Practices.Unity.Configuration
PresentationCore
PresentationFramework
System.Configuration
Please suggest me any chances, I'd be happy.
Greets.
So, after I checked some things over the weekend, I came to the conclusion that vb.net doesn't support an external unity configSource.
You could parse the config file with an xml parser and read each value. But I'm too lazy for that.
I edited my:
app.Config like that:
Inserted the container from the unity.config to my app.config
Code:
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<container>
<register type="TestApplication.Interfaces.IBuilder, TestApplication.Interfaces" mapTo="TestApplication.Classes.Builder, TestApplication.Classes" />
</container>
</unity>
I registered the type/s inside the App.config, after that I can read the container with my Factory, and can work with the unity container.

How to declare ConfigurationManager.ConnectionStrings?

hello i'm using visual studio 2008, vb.net and oracle as my db.
this is what i save in my apps.config
<appSettings/>
<add key="SMSDW_connection" value="server=abc;database=efg;User ID=**;Password=**;"/>
and this is my code for calling the apps.config file :
Dim connectionString = System.Configuration.ConfigurationManager.AppSettings("SMSDW_connection")
Dim sqlConnection As OracleClient.OracleConnection = New OracleClient.OracleConnection(connectionString)
but still i got an error which is :
The ConnectionString property has not been initialized.
i have add reference System.Configuration and Imports System.Configuration
The <appSettings> node has the closing tag "/" so the <add is outside of it.
it should read:
<appSettings>
<add ...
</appSettings>

How to add Application name to <appSettings/>?

This is my app.config file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Application Name" value="/MyApplication" />
</appSettings>
<connectionStrings>
<add name="frmStartup.My.MySettings.HDIMembershipProviderConnectionString"
connectionString="Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<membership defaultProvider="HDIMembershipProvider">
<providers>
<clear/>
<add name="HDIMembershipProvider" type="MyApplication.HDIMembershipProvider, MyApplication"/>
</providers>
</membership>
</system.web>
<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>
I am trying to use HDI membership provider and this is my Users table structure:
And in my recent question asked here Oded helped me out trying to figure the problem with my Insert statement and I re-modified it and I have an ApplicationName column in my database structure I need to specify it.(As it should not be null value)
Now I need to add my application name by default to enter to database as we do it for web.config.
This is what I mean.
I need to add that MyApplication to my app.config file.
So How do I do that?
This is how I'm trying to enter user details to database but it is not enetering a single value
Try
Dim connectionString As String = "Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
Using cn As New SqlConnection(connectionString)
cn.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Users ( Username, Password, Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"
Dim param1 As New SqlParameter()
param1.ParameterName = "#Username"
param1.Value = txtUsername.Text.Trim()
cmd.Parameters.Add(param1)
Dim param2 As New SqlParameter()
param2.ParameterName = "#Password"
param2.Value = txtPassword.Text.Trim()
cmd.Parameters.Add(param2)
Dim param3 As New SqlParameter()
param3.ParameterName = "#Email"
param3.Value = txtEmail.Text.Trim()
cmd.Parameters.Add(param3)
Dim param4 As New SqlParameter()
param4.ParameterName = "#PasswordQuestion"
param4.Value = txtSecurityQuestion.Text.Trim()
cmd.Parameters.Add(param4)
Dim param5 As New SqlParameter()
param5.ParameterName = "#PasswordAnswer"
param5.Value = txtSecurityAnswer.Text.Trim()
cmd.Parameters.Add(param5)
cmd.Connection = cn
cmd.ExecuteNonQuery()
cn.Close()
End Using
Successlbl.show
Successlbl.show.Text = "Regisration Success."
Catch
Errolbl.Show()
Errolbl.Text = "Your account was not created.Please try again."
End Try
Can anyone point me out where I'm making mistake.
And this is the final result I'm getting while entering to database:
To be more short and clear I need to enter the above shown User details to my database using the HDI membership provider.
There is a better way by using the following steps:
1) Add a reference to System.Configuration to your application.
2) Add the following block to your app.config file, within the configuration section:
<appSettings>
<add key="ApplicationName" value="/MyApplication" />
</appSettings>
3) Retrieve the value and use it where needed with the following code (example from your answer shown):
param6.Value = System.Configuration.ConfigurationManager.AppSettings("ApplicationName")
Add a AppSettings section to your web.config
<appSettings>
<add key="ApplicationName" value="/website1" />
</appSettings>
I have figured out the problem Myself after a lot of hair pulling and found the solution that I have changed my code in this way:
cmd.CommandText = "INSERT INTO Users ( Username,ApplicationName,Password,
Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#ApplicationName,#Password,
#Email,#PasswordQuestion,#PasswordAnswer)"
And add another Param this way:
Dim param6 As New SqlParameter()
param6.ParameterName = "#ApplicationName"
param6.Value = txtApplicationName.Text.Trim()
cmd.Parameters.Add(param6)
I know this not the best way If anyone found any other best solution let me know.

Add Interceptors through the web.config? NHibernate

I can't seem to find an example where someone added an interceptor via web.config - is this possible?
And yes I know about event listeners and will be using them on another project - but I wanted to see if I could get around having to inject the interceptor in code - thank you
I don't think it's supported but you can easily fetch and instantiate interceptors from a custom config section:
NHibernate.Cfg.Configuration cfg = ...
var interceptors = (NameValueCollection) ConfigurationManager.GetSection("nhibernate.interceptors");
foreach (string k in interceptors)
cfg.SetInterceptor((IInterceptor) Activator.CreateInstance(Type.GetType(k)));
web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nhibernate.interceptors" type="System.Configuration.NameValueSectionHandler, System" />
</configSections>
<nhibernate.interceptors>
<add key="MyApp.Interceptors.SomeInterceptor, MyApp" value=""/>
<add key="MyApp.Interceptors.AnotherInterceptor, MyApp" value=""/>
</nhibernate.interceptors>
</configuration>