Embedded RavenDB Logging in debug output - vb.net

I am currently investigating in RavenDB and set up this simple test
<TestFixtureSetUp()>
Public Sub Setup()
_embeddableDocumentStore = New EmbeddableDocumentStore With {.DataDirectory = "localdatabase"}
_embeddableDocumentStore.Initialize()
End Sub
<Test> Public Sub CreateDB()
Dim session = _embeddableDocumentStore.OpenSession()
Dim results = session.Query(Of testclass)().ToList()
For Each testclass In results
session.Delete(testclass)
Next
session.SaveChanges()
session.Store(New testclass With {.Id = 4, .Name = "177mdffarsdfdffds6t2in611"})
session.Store(New testclass With {.Id = 2, .Name = "17fd7martrsdfdffds6t2in611"})
session.Store(New testclass With {.Id = 3, .Name = "re177marsdfdfffdfds6t2in611"})
session.SaveChanges()
results = session.Query(Of testclass)().ToList()
For Each testclass In results
session.Delete(testclass)
Next
session.SaveChanges()
results = session.Query(Of testclass)().ToList()
Assert.AreEqual(0, results.Count())
End Sub
<TestFixtureTearDown()>
Public Sub TearDown()
_embeddableDocumentStore.Dispose()
_embeddableDocumentStore = Nothing
End Sub
But can I get the embedded RavenDB database to write debugging info to the visual studio Debug Output? I have tried adding a nlog.config in the bin\debug folder with this content, but when I debug I get no info about queries in the output... What am I doing wrong?
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.netfx35.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target xsi:type="Console" Name="Console" />
</targets>
<rules>
<logger name="Raven.Client.*" writeTo="Console"/>
</rules>
</nlog>

Forgive my poor VB translation, I usually develop in C#
Specifically regarding logging in unit tests - I find it much easier to use the abstraction layer and forget about NLog.
Imports Raven.Abstractions.Logging
...
<TestFixtureSetUp>
Public Sub Setup()
LogManager.RegisterTarget(Of DebugTarget)()
End Sub
Class DebugTarget
Inherits Target
Public Overrides Sub Write(logEvent As LogEventInfo)
' whatever you want to do
If logEvent.Level >= LogLevel.Info Then
Debug.WriteLine("{0} - {1} - {2}", _
logEvent.TimeStamp.ToLocalTime().ToString("hh:mm:ss.fff"), _
logEvent.Level, _
logEvent.FormattedMessage)
End If
End Sub
End Class
In regards to your test as a whole - there are a lot of problems:
Unit tests should not write to disk. Not only is there a performance cost, but multiple tests could step on each other. Run in memory instead.
Don't use test setup/teardown for the document store. Each test should get its own in-memory document store. Put it in a Using statement block to dispose on test completion.
Don't try to manage your own cleanup by deleting records. Just start clean each time.
Sessions should always go in a Using statement block. Whether testing or in real code.
When testing, it's good practice to create separate sessions for the Arrange/Act portion of your test and the Assert portion. Otherwise, you aren't necessarily checking what's in the database - you might just be checking what's tracked in the session.
Unit tests should always use the WaitForNonStaleResults customization on any queries. Otherwise you may be testing stale results. Read here for more information about stale results.
Here is a complete example of your test written properly.

Related

Using <DataTestMethod>, <DataRow....> with vb.net . Only one <DataRow> gets executed

I'm trying to set up an automated unit test using MSTest. I have single tests working, and am now trying to set up parameterised tests using < DataTestMethod> and < DataRow(...)>. I'm following the examples here
When I debug the test sequence below, the ParseTestData( ) is only called once, with the first <DataRow ..> parameter. It is not called a second time.
Can anyone see where I'm going wrong?
(Note: I found some articles indicating DataTestMethod is obsolete, and TestMethod works just the same. I tried and got identical results)
[edit] - from #Mark Seemann 's suggestion, I've simplified this from the original post. Same problem.
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace TestDecoder.Tests
<TestClass>
Public Class DecoderTests
Private DecoderInstance
<DataTestMethod>
<DataRow(New Byte() {&H41})>
<DataRow(New Byte() {&H42})>
Public Sub ParseTestData(Frame() As Byte)
Dim result As Boolean
DecoderInstance = New Decoder()
result = DecoderInstance.parse(Frame(0))
Assert.IsTrue(result, "Failed the dummy test")
End Sub
End Class
End Namespace
I'm not sure if this will provide any more insight, but here is the Decoder code (Edited for Brevity).
Imports Microsoft.VisualBasic
Public Class Decoder
Function parse(rxchar As Byte) As Boolean
Return rxchar = &H41
End Function
End Class

windows mobile .net CF 3.5 Multiple Async Web Service Calls = Timeout

I'm developing an App for Windows Mobile 6.5, Compact Framework 3.5. The application starts by loading a simple login form. While the login form is created and opening, a new thread is created for retrieving some setup data from a Web Service. 3 Separate calls are made to the same Web Service asynchronously within this thread.
The first call retrieves a list of Companies
The second retrieves a list of Locations that belong to a Company
The third retrieves a list of Users and their Login ID's that belong to a Location & Company
Each Web Service OnGet***Completed event then saves the returned data to a local SQLite Database
When I compile and run that logic through the Visual Studio debugger, everything runs great. The app starts, the form is shown, the three web service calls are created and finish. I can login as a user and carry on. Ok all is good!
EXCEPT, when I build my CAB file and install the application on the exact same device I use for debugging... the application sits for 60 seconds and I get 3 WebException "The operation has timed-out" errors and the application is forced closed.
I've been playing and researching this issue for a couple of days now. I read a lot about setting the Max Connection in the config of the Web Service and I have also set the bindings to be large values as shown below:
<add address="*" maxconnection="324"/>
and
<binding name="BasicHttpBinding_IGenericContract" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
I have also set the Default Connection Limit to 22 before I start the Web Service calls in the Windows Mobile application.
Here is my code that starts all three asynchronous Web Service calls by creating new instances of each class (class structure shown below)
'Currently Inside of Initial Synchronize Thread
System.Net.ServicePointManager.DefaultConnectionLimit = 22
Dim syncCompanies As New SyncCompanies(True)
Dim syncLocations As New SyncLocations(True)
Dim syncUsers As New SyncUsers(True)
Here is the SyncCompanies class The New method accepts a "Asynchronous" boolean parameter which tells the class to Execute the Web Service call asynchronously or synchronously. I would like to run all three web services asynchronously.
Public Class SyncCompanies
Private service As New RDScanService.BasicHttpBinding_IGenericContract
'Method that Retrieves the Companies data from the server
Public Sub New(ByVal Asynchronous As Boolean)
DoAsynchronously = Asynchronous
NewCompanies = New Companies(False, False)
Try
IsBusy = True
If DoAsynchronously Then
'Begin the Asynchronous Call
Dim cb As New AsyncCallback(AddressOf onGetCompaniesComplete)
service.BeginGetCompanies(currentSetup.LastCompaniesSync, True, cb, Nothing)
Else
'Perform the Synchronous Call, create a list of Companies and pass to the Execute function for saving
For Each company In service.GetCompanies(currentSetup.LastCompaniesSync, True)
Dim newCompany As New Company(False, False, "")
newCompany.Code = company.Code
newCompany.ReportName = company.ReportName
NewCompanies.Companies.Add(newCompany)
Next
Execute()
IsBusy = False
End If
Catch ex As Exception
service.Abort()
IsBusy = False
Success = False
ErrorVerb = "retrieving companies from server"
ErrorMessage = ex.Message
Finally
Dispose()
End Try
End Sub
Private Sub onGetCompaniesComplete(ByVal ar As IAsyncResult)
'End the Asynchronous Web Service Call and start the Asynchronous Processing
For Each company In service.EndGetCompanies(ar)
Dim newCompany As New Company(False, False, "")
newCompany.Code = company.Code
newCompany.ReportName = company.ReportName
NewCompanies.Companies.Add(newCompany)
Next
ExecuteAsync()
End Sub
Public Sub ExecuteAsync()
'Run the Synchronous method on a new ThreadPool thread
ThreadPool.QueueUserWorkItem(AddressOf DoExecute)
End Sub
Public Sub Execute()
'First determine if the Web Service returned any Companies to save...
If NewCompanies.Companies.Count > 0 Then
NewCompanies.SubmitToDB(True)
If NewCompanies.Success Then
Success = True
Else
Success = False
ErrorVerb = "syncing companies"
ErrorMessage = NewCompanies.Message
End If
End If
IsBusy = False
End Sub
Private Sub DoExecute(ByVal stateInfo As Object)
'Call the Synchronous method on this ThreadPool thread
Execute()
End Sub
Private _newCompanies As Companies
Public Property NewCompanies() As Companies
Get
Return (_newCompanies)
End Get
Set(ByVal value As Companies)
_newCompanies = value
End Set
End Property
Private _success As Boolean
Public Property Success() As Boolean
Get
Return (_success)
End Get
Set(ByVal value As Boolean)
_success = value
End Set
End Property
Private _errVerb As String
Public Property ErrorVerb() As String
Get
Return (_errVerb)
End Get
Set(ByVal value As String)
_errVerb = value
End Set
End Property
Private _errMessage As String
Public Property ErrorMessage() As String
Get
Return (_errMessage)
End Get
Set(ByVal value As String)
_errMessage = value
End Set
End Property
Private _isBusy As Boolean
Public Property IsBusy() As Boolean
Get
Return (_isBusy)
End Get
Set(ByVal value As Boolean)
_isBusy = value
End Set
End Property
Private _doAsynchronously As Boolean
Public Property DoAsynchronously() As Boolean
Get
Return (_doAsynchronously)
End Get
Set(ByVal value As Boolean)
_doAsynchronously = value
End Set
End Property
Protected Sub Dispose()
service.Dispose()
End Sub
End Class
For the life of me, can't figure out why my application runs smoothly through the Visual Studio Debugger, but when installed on the MC55A Motorola device, it crashes. The application also runs fine in the emulator.
I have tried removing 1 of the Asynchronous Web Service calls and it worked perfectly fine installed, but when I try 3 or more, it fails. It is almost like when the application is installed on the device, the Default Connection Limit is ignored and set back to 2.
Sorry for the novel, just wanted to make sure I gave enough information since I have seen similar issues on Stackoverflow, but nothing exactly like this one. I do realize that I could perform these calls Synchronously with only 1 Web Service connection open at a time, but we are in a crunch to make this application the fastest for our customers. Even though I can perform this Initial Sync operation synchronously, I know there will be places down the road where I need more than 2 web service connections running at once.
I see you are catching and storing the Error Message. Did your novel happen to say what that error message was?
I also notice that your ErrorMessage string value is only 1 item, so it could be getting overwritten. You may try List(Of String) and add error messages... at least until you have had a chance to catch some of those errors.
Before going too far into this, can your device browse to the web service? If your device can not browse there, then the code in your app will not be able to get to it either.
I aggree with jp2code, before trying to adopt the code you should ensure that the device can connect to the web service.
So what is the diff between running in debugger/emulator and stand-alone on the device: the device is connected to your PC's network.
Can your device connect to the server or the web service? If not, how should your code ever success?
Check the devices network settings. Is it connected to work (windows sharing) or internet (web browsing, web services)? Do you use WLAN or GSM? What address is your web service? Is your network blocking access off WLAN or public internet (GSM)?
As said, first ensure the connection is OK before changing your working code.
BWT: If device is WLAN connected to same network as development PC you may use remote debugging via TCP/IP: VS2008 remotely connect to Win Mobile 6.1 Device
Using this you have the same environment when you disconnect the ActiveSync/WMDC connection to the device.
I ended up creating a new Smart Device Application and tried calling the web service 3 times in a row asynchronously. Surprisingly it worked when I deployed the new app to the device. I slowly brought in the code from my previous app into the new one and so far I have not been able to find why the other app wasn't working. :s They are now the exact same applications except the new one works as expected.
Thanks for the responses, those were definitely good starting points to see if the device was sharing the same connection when not connected to active sync. I will post up further information if I find out why the other App isn't working, but as of now the new one is working fine.

Context issue in IHttpHandler

Sorry, this can be a basic question for advanced VB.NET programmers but I am a beginner in VB.NET so I need your advice.
I have a web application and the login is required for some specific pages. To check if the user is logged in, the old programmer used this technique:
Dim sv As New WL.SessionVariables(Me.Context)
If Not (sv.IsLoggedIn) Then
Response.Redirect(WL.SiteMap.GetLoginURL())
End If
Well, I have to use this Logged In checking in a handler done by me and I tried this:
Public Class CustomHandler
Implements System.Web.IHttpHandler, IReadOnlySessionState
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim sv As New WL.SessionVariables(context)
If Not (sv.IsLoggedIn) Then
context.Response.Write("No access unless you're the CEO!!!" & sv.IsLoggedIn)
ElseIf sv.IsLoggedIn Then
DownloadFile(context)
Else
End If
End Sub
//other code
End Class
Well, the "is logged in" checking is always false (even after I login) and I think it's an issue with the context. So all the other pages works fine with logging checking but this handler have this specific issue.
Can you guys give a helping hand?
UPDATE:
The logged in is done trough this method:
Public Sub SetCreditialCookie(ByVal accountID As Integer)
Me.AccountID = accountID
m_context.Session.Item("loggedInAccount") = accountID
m_context.Response.Cookies.Add(New System.Web.HttpCookie("account_id", CStr(m_context.Session.Item("account_id"))))
m_context.Response.Cookies("account_id").Expires = DateTime.Now.AddDays(5)
End Sub
and to check it it's logged in, this method is called:
Public Function IsLoggedIn() As Boolean
If Not m_context.Session.Item("loggedInAccount") Is Nothing And Me.AccountID = m_context.Session.Item("loggedInAccount") Then
Return True
Else
Return False
End If
End Function
UPDATE 2:
- debugging the code shown that there were multiple kind of logins and I was checking the wrong one with the session.
Due to the use of IReadOnlySessionState, is it possible that the SessionVariables class attempts in some way to modify the Session, which in turn causes an error (possibly handled and not visible to you).
If this is the case it could mean that the IsLoggedIn property is not correctly initialised, or does not function as expected?
Do you have access to the code for the class. If so, try debugging it to see what is happening.

Castle Automatic Transaction Management Facility persist issues

Regarding the Castle Automatic Transaction Management Facility; I'm having some difficulties getting operations to actually save to the database without flushing the session.
I'm using the following components
* NHibernate.dll v3.1.0.4000
* Castle.Core.dll v2.5.2.0
* Castle.Windsor.dll v2.5.3.0
* Castle.Facilities.NHibernateIntegration.dll v1.1.0.0
* Castle.Services.Transaction.dll v2.5.0.0
* Castle.Facilities.AutoTx.dll v2.5.1.0
I have followed the Castle documentation very closely and have not been able to resolve my issue.
My (web-)application follows the MVP pattern. The key parts of the (transactional) presenter-service are shown below:
<Transactional()> _
Public Class CampusEditPresenter
Inherits BasePresenter(Of ICampusEditView)
Public Sub New(ByVal view As ICampusEditView)
MyBase.New(view)
End Sub
...
<Transaction(TransactionMode.Requires)> _
Public Overridable Sub Save() Implements ICampusEditPresenter.Save
' Simplified
Using session As ISession = _sessionManager.OpenSession()
Dim campus As New Campus()
campus.Code = _view.Code
campus.ShortDescription = _view.ShortDescription
campus.LongDescription = _view.LongDescription
campus.StartDate = _view.StartDate
campus.EndDate = _view.EndDate
session.Save(campus)
End Using
End Sub
End Class
This presenter-service is registered in an installer:
container.Register( _
Component.For(Of CampusEditPresenter) _
.Interceptors(Of DebugLoggingInterceptor) _
.LifeStyle.Transient)
and resolved by the view (in the base):
Public Class BasePage(Of TPresenter)
Inherits Page
Protected _presenter As TPresenter
...
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
_presenter = _container.Resolve(Of TPresenter)(New With {Key .view = Me})
End Sub
...
End Class
Public Class CampusEdit
Inherits BasePage(Of CampusEditPresenter)
Implements ICampusEditView
...
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
_presenter.Save()
End Sub
...
End Class
I have registered the NHibernate and Transaction facilities in an XML configuration file as follows:
<facility id="transaction" type="Castle.Facilities.AutoTx.TransactionFacility, Castle.Facilities.AutoTx" />
<facility id="nhibernate" type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration" isWeb="true" configurationBuilder="[removed].AutoConfigurationBuilder, [removed]">
<factory id="nhibernate.factory">
<settings>
<item key="connection.driver_class">NHibernate.Driver.OracleClientDriver, NHibernate</item>
<item key="connection.connection_string">[removed]</item>
<item key="show_sql">false</item>
<item key="dialect">NHibernate.Dialect.Oracle10gDialect, NHibernate</item>
<item key="query.substitutions">true 1, false 0, yes 'Y', no 'N'</item>
<item key="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</item>
<item key="current_session_context_class">web</item>
<item key="hbm2ddl.keywords">auto-quote</item>
</settings>
</factory>
</facility>
and I have registered the SessionWebModule Http module in my Web.config:
<httpModules>
<add name="NHibernateSessionWebModule" type="Castle.Facilities.NHibernateIntegration.Components.Web.SessionWebModule, Castle.Facilities.NHibernateIntegration"/>
...
</httpModules>
Any ideas as to why this may not be working?
I can get everything working when I a) instansiate my own transactions from the ISession instance and maually commit these transactions, or if I b) use the Automatic Transaction Management AOP-mechanism AND manuall flush the session instance (though I shouldn't have to manually do this).
I would have also thought that SessionWebModule IHttpModule (which follows the open-session-per-request pattern) would cause my entities to be persisted, but this doesnt seem to be happening...
So I worked out the TransactionInterceptor was not getting registerd on my components.
After downloading the Castle.Facilities.AutomaticTransactionManagement source from github and stepping through, I found my issue and managed to resolve it.
Basically the TransactionFacility adds a contributor, TransactionComponentInspector, to the ComponentModelBuilder, which allows for some additional configuration contribution whilst building the component. In the case of the TransactionComponentInspector, it looks for a "Transactional" class attribute on the component and if it exists it will register a TransactionInterceptor on the component. However, my components were never getting contributed to by the TransactionComponentInspector.
To configure/register my components on the container, I use Installers. I configure the container itself using XML, which references these installers as well as any facilities (e.g. NHibernate-integration/logging etc.). Anyways, I believe it may have been some kind of ordering issue whereby my components might have been getting registered before the transaction facility. As such components registered before the TransactionFacility were not getting contributed-to by the TransactionComponentInspector and were therefore not getting a TransactionInterceptor registered on the component. Once I realised this I manually configured the container (with the correct order of things) and everything seemed to work!!!
Now I've got to try and work out how to do this in my XML configuration. If I can't, I guess I'll dump this and go for fluent configuration of the container (e.g. in the global HttpApplication).
[edit] see below:
_container = New WindsorContainer()
' TransactionFacility must be registered before components.
_container.AddFacility(Of TransactionFacility)()
_container.Install(Configuration.FromXmlFile("Configs\services.xml"))
I was experiencing very similar behavior. It turned out that I was creating a Logging Aspect Interceptor. I had created a Default Interceptor Selector so that I could apply logging where needed. In doing this, I was messing up the TransactionalInterceptor. Once I removed the Default Interceptor Selector, the Transactions started working.
Try SwampyFox's suggestion, then also try the nuget of 3.0.x of Tx, AutoTx and NHibFac, if that doesn't solve your problems. New development (if it's a bug) is going into those. Tell is the result of trying Foxy's suggestion.

How can I write to my own app.config using a strongly typed object?

The following code has two flaws, I can't figure out if they are bugs or by design. From what I have seen it should be possible to write back to the app.config file using the Configuration.Save and according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx the code should work.
The bugs are shown in the source below and appear when you try to set the property or save the config back out.
Imports System.Configuration
Public Class ConfigTest
Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
Get
Return CStr(Me("JunkProperty"))
End Get
Set(ByVal value As String)
' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
Me("JunkProperty") = value
End Set
End Property
Public Sub Save()
Dim ConfigManager As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' The add / remove is according to http://www.codeproject.com/KB/cs/SystemConfiguration.aspx
ConfigManager.Sections.Remove("ConfigTest")
' *** Bug 2, exception InvalidOperationException thrown with message "Cannot add a ConfigurationSection that already belongs to the Configuration."
ConfigManager.Sections.Add("ConfigTest", Me)
ConfigManager.Save(ConfigurationSaveMode.Full, True)
End Sub
Public Shared Sub Main()
Dim AppConfig As ConfigTest = TryCast(ConfigurationManager.GetSection("ConfigTest"), ConfigTest)
AppConfig.JunkProperty = "Some test data"
AppConfig.Save()
End Sub
' App.Config should be:
' <?xml version="1.0" encoding="utf-8" ?>
'<configuration>
' <configSections>
' <section name="ConfigTest" type="ConsoleApp.ConfigTest, ConsoleApp" />
' </configSections>
' <ConfigTest JunkProperty="" />
'</configuration>
End Class
I'd like to do it this way so that on the first run of the app I check for the properties and then tell the user to run as admin if they need to be set, where the UI would help them with the settings. I've already 'run as admin' to no effect.
Your code doesn't really make any sense. I took your example code and turned it into a simple example that works. Please note this is not best practise code, merely an example to aid you on your journey of learning the configuration API.
Public Class ConfigTest
Inherits ConfigurationSection
<ConfigurationProperty("JunkProperty", IsRequired:=True)> _
Public Property JunkProperty() As String
Get
Return CStr(Me("JunkProperty"))
End Get
Set(ByVal value As String)
' *** Bug 1, exception ConfigurationErrorsException with message "The configuration is read only." thrown on the following line.
Me("JunkProperty") = value
End Set
End Property
Public Overrides Function IsReadOnly() As Boolean
Return False
End Function
Public Shared Sub Main()
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim AppConfig As ConfigTest = config.GetSection("ConfigTest")
AppConfig.JunkProperty = "Some test data"
config.Save()
End Sub
End Class
This code will open the config file, modify the attribute JunkProperty and persist it back it the executable's configuration file. Hopefully this will get you started- it looks like you need to read about the configuration API a bit more.
I've used the API to create configuration sections for large scale enterprise apps, with several 1000 of lines of custom hierarchical config (my config was readonly though). The configuration API is very powerful once you've learnt it. One way I found out more about its capabilities was to use Reflector to see how the .NET framework uses the API internally.
Maybe you don't know Portuguese or c# but this is you want http://www.linhadecodigo.com.br/Artigo.aspx?id=1613
using BuildProvider from asp.net
After loading a configuration it is readonly by default, principally because you have not overriden the IsReadOnly property. Try to override it.
¿Is there something that prevents you from using a setting?
Looks like it is not possible by design. App.config is normally protected as it resides along with the app in the Program Files directory so must be amended at installation time by the installer.
Pity really, I'd like the app to have settings that an admin can set.
Sorry if I didn't understand your case, but yes, you can change App.config at runtime.
Actually, you will need to change YourApp.exe.config, because once your app is compiled, App.config contents are copied into YourApp.exe.config and your application never looks back at App.config.
So here's what I do (C# code - sorry, I still haven't learnt VB.Net)
public void UpdateAppSettings(string key, string value)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement item in xmlDoc.DocumentElement)
{
foreach (XmlNode node in item.ChildNodes)
{
if (node.Name == key)
{
node.Attributes[0].Value = value;
break;
}
}
}
using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile))
{
xmlDoc.Save(sw);
}