Having issues reading/writing to App.config.
The code I have below I took from the MSDN article on (AppSettingsSection Class)
http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.100%29.aspx
I am successfully able to read the App.config file and get/use the values and it responds correctly if I change the App.config file to get the new values.
However, in this (from MS page) I add a new entry and change a value on one of my initial entries. It appears to change it, does not error in saving it, but does not write it to the file so the next time I run, I am back to my initial values in App.config.
Can someone show me my erroneous ways?
TIA!
Imports System
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Text
Imports System.IO
' IMPORTANT: To compile this example, you must add to the project
' a reference to the System.Configuration assembly.
'
Module Module1
Sub Main()
Dim KeypairHolder As String = Nothing
' Get Configuration File as config object
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' Create a unique key/value pair to add to the appSettings section.
Dim keyName As String = "DateTimeStamp Number " & config.AppSettings.Settings.Count + 1
Dim value As String = String.Concat(Date.Now.ToLongDateString(), " ", Date.Now.ToLongTimeString())
' Create appSettings as object
Dim appSettings As System.Configuration.AppSettingsSection = config.AppSettings
' add the new key and value
appSettings.Settings.Add(keyName, value)
' save and refresh the values
config.Save(ConfigurationSaveMode.Modified)
' Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings")
' Get keys
Dim kAll() As String = appSettings.Settings.AllKeys()
' Build string to display
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
'Display
MsgBox(KeypairHolder)
' Change a value
appSettings.Settings("CustomKey").Value = "Changed Value"
' Resave and get and display
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
kAll = appSettings.Settings.AllKeys()
KeypairHolder = Nothing
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
MsgBox(KeypairHolder)
End Sub
End Module
' appSettings Section of my App.Config file
' <appSettings>
' <add key="UsernamePassword" value="BobsUsername:BobsPassword"/>
' <add key="CustomKey" value="ConfigApp Value"/>
' </appSettings>
Right click on the app.config file in your solution explorer window and select the Properties option. Ensure that the Copy to Output Directory property is NOT set to Copy always.
Related
I have an Excel file (say xyz.xlsx) on my server but want to fetch that file and save locally on my desktop, when ever i press the "Move" Button present on my form.Please guide me on this, that how it can be done. i am right now using visual studio 2017
You have two easy options.
If you want to do this as a training exercise you look into the System.IO classes.
System.IO.File.Move(source$, destination$) will suffice.
You can improve this with some error checking such as
System.IO.Directory.Exists(sourcePath$)
System.IO.Directory.Exists(destPath$)
You can then play around with string formatting and error handling as you please.
If All you are doing is copy a file and that is your entire software, I would suggest doing it in CMD instead.
This same approach can be called from VB if needed.
Process.Start("ROBOCOPY " & source$ & " " & destination$ & " " & flags)
The advantage of doing this is it is a separate process to your main code, which means you can leave a very large file copying over a long period of time without hanging up your own code.
''' <summary>
''' Copies the file at destination Source to the folder DestinationPath (and creates the folder if it doesn't exist)
''' </summary>
''' <param name="Source">Format C:\Users\username\documents\randomstuff\unnecessaryfolder\newfolder\myfile.txt</param>
''' <param name="DestinationPath">Format (and Default path) C:\Users\username\Desktop\ </param>
Public Sub MoveFile(Source As String, DestinationPath As String)
If DestinationPath = "" Then
DestinationPath = "C:\Users\" & My.User.Name & "\Desktop\" 'default path
End If
Dim FileName
Dim src() As String = Source.Split("\")
FileName = src(src.Count - 1) 'returns the name of the file in the full path
Try
If Not IO.File.Exists(Source) Then Throw New Exception("Wrong file, you plonka!")
If Not IO.Directory.Exists(DestinationPath) Then IO.Directory.CreateDirectory(DestinationPath)
IO.File.Copy(Source, DestinationPath & FileName)
Catch ex As Exception
Throw ex
End Try
End Sub
I'm building some Word 2003 macro that have to be put in the %APPDATA%\Microsoft\Word\Startup folder.
I can't change the location of this folder (to a network share). How can I auto update this macros ?
I have tried to create a bootstrapper macro, with an AutoExec sub that copy newer version from a file share to this folder. But as Word is locking the file, I get a Denied Exception.
Any idea ?
FYI, I wrote this code. The code is working fine for update templates in templates directory, but not in startup directory :
' Bootstrapper module
Option Explicit
Sub AutoExec()
Update
End Sub
Sub Update()
MirrorDirectory MyPath.MyAppTemplatesPath, MyPath.WordTemplatesPath
MirrorDirectory MyPath.MyAppStartupTemplatesPath, MyPath.WordTemplatesStartupPath
End Sub
' IOUtilities Module
Option Explicit
Dim fso As New Scripting.FileSystemObject
Public Sub MirrorDirectory(sourceDir As String, targetDir As String)
Dim result As FoundFiles
Dim s As Variant
sourceDir = RemoveTrailingBackslash(sourceDir)
targetDir = RemoveTrailingBackslash(targetDir)
With Application.FileSearch
.NewSearch
.FileType = MsoFileType.msoFileTypeAllFiles
.LookIn = sourceDir
.SearchSubFolders = True
.Execute
Set result = .FoundFiles
End With
For Each s In result
Dim relativePath As String
relativePath = Mid(s, Len(sourceDir) + 1)
Dim targetPath As String
targetPath = targetDir + relativePath
CopyIfNewer CStr(s), targetPath
Next s
End Sub
Public Function RemoveTrailingBackslash(s As String)
If Right(s, 1) = "\" Then
RemoveTrailingBackslash = Left(s, Len(s) - 1)
Else
RemoveTrailingBackslash = s
End If
End Function
Public Sub CopyIfNewer(source As String, target As String)
Dim shouldCopy As Boolean
shouldCopy = False
If Not fso.FileExists(target) Then
shouldCopy = True
ElseIf FileDateTime(source) > FileDateTime(target) Then
shouldCopy = True
End If
If (shouldCopy) Then
If Not fso.FolderExists(fso.GetParentFolderName(target)) Then fso.CreateFolder (fso.GetParentFolderName(target))
fso.CopyFile source, target, True
Debug.Print "File copied : " + source + " to " + target
Else
Debug.Print "File not copied : " + source + " to " + target
End If
End Sub
' MyPath module
Property Get WordTemplatesStartupPath()
WordTemplatesStartupPath = "Path To Application Data\Microsoft\Word\STARTUP"
End Property
Property Get WordTemplatesPath()
WordTemplatesPath = "Path To Application Data\Microsoft\Templates\Myapp\"
End Property
Property Get MyAppTemplatesPath()
MyAppTemplatesPath = "p:\MyShare\templates"
End Property
Property Get XRefStartupTemplatesPath()
MyAppStartupTemplatesPath = "p:\MyShare\startup"
End Property
[Edit] I explored another way
Another way I'm thinking about, is to pilot the organizer :
Sub Macro1()
'
' Macro1 Macro
' Macro recorded 10/7/2011 by beauge
'
Application.OrganizerCopy source:="P:\MyShare\Startup\myapp_bootstrapper.dot", _
Destination:= _
"PathToApplication Data\Microsoft\Word\STARTUP\myapp_bootstrapper.dot" _
, Name:="MyModule", Object:=wdOrganizerObjectProjectItems
End Sub
This is working, but has limitations :
either I have to hard-code modules to organize
or I have to change the option "Trust VBA project" to autodiscover items like this (which is not acceptable as it requires to lower the security of the station) :
the code of the project enumeration is this one :
Public Sub EnumProjectItem()
Dim sourceProject As Document
Dim targetProject As Document
Set sourceProject = Application.Documents.Open("P:\MyShare\Startup\myapp_bootstrapper.dot", , , , , , , , , wdOpenFormatTemplate)
Set targetProject = Application.Documents.Open("PathToApplication Data\Microsoft\Word\STARTUP\myapp_bootstrapper.dot", , , , , , , , , wdOpenFormatTemplate)
Dim vbc As VBcomponent
For Each vbc In sourceProject.VBProject.VBComponents 'crash here
Application.ActiveDocument.Range.InsertAfter (vbc.Name + " / " + vbc.Type)
Application.ActiveDocument.Paragraphs.Add
Next vbc
End Sub
[Edit 2] Another unsuccessful try :
I put, in my network share, a .dot with all the logic.
In my STARTUP folder, I put a simple .Dot file, that references the former one, with a single "Call MyApp.MySub".
This is actually working, but as the target template is not in a trusted location, a security warning is popped up each time word is launched (even if not related to the current application macro)
At least, I succeed partially using these steps :
Create a setup package. I use a NSIS script
the package detect any instance of Winword.exe and ask the user to retry when word is closed
extract from the registry the word's option path
deploy the files into the word's startup folder
add an uninstaller in the local user add/remove programs
I put the package in the remote share. I also added a .ini file containing the last version of the package (in the form "1.0")
In the macro itself, I have a version number ("0.9" for example).
At the startup (AutoExec macro), I compare the local version to the remote version
I use shell exec to fire the setup if a newer version is found.
The setup will wait for Word to close
A bit tricky, but it works on Word 2K3 and Word 2K10.
I have an application where the user select configuration, I need to write to function one to save the configuration when the application is closed and other load the configuration when the application is loaded, i need to use registry would you able to help me by giving me 2 small example how to save and to load from the registry.
thank you
Jp
The "My" Class in VB contains almost everything you need.
To read data:
My.Computer.Registry.LocalMachine.GetValue("mykey")
To write data:
My.Computer.Registry.LocalMachine.SetValue("mykey", "myvalue")
Hope it helps.
Look into the Registry Class. The KEYS exposed by this class are
CurrentUser - Stores information about user preferences.
LocalMachine - Stores configuration information for the local machine.
ClassesRoot - Stores information about types (and classes) and their properties.
Users - Stores information about the default user configuration.
PerformanceData - Stores performance information for software components.
CurrentConfig - Stores non-user-specific hardware information.
It's important to understand the the use of these keys so information can be saved for user specific instances or machine.
I wasn't sure what version of .NET Framework you are using.
Sample data from MS
Imports Microsoft.VisualBasic
Imports System
Imports System.Security.Permissions
Imports Microsoft.Win32
Public Class RegKey
Shared Sub Main()
' Create a subkey named Test9999 under HKEY_CURRENT_USER.
Dim test9999 As RegistryKey = _
Registry.CurrentUser.CreateSubKey("Test9999")
' Create two subkeys under HKEY_CURRENT_USER\Test9999.
test9999.CreateSubKey("TestName").Close()
Dim testSettings As RegistryKey = _
test9999.CreateSubKey("TestSettings")
' Create data for the TestSettings subkey.
testSettings.SetValue("Language", "French")
testSettings.SetValue("Level", "Intermediate")
testSettings.SetValue("ID", 123)
testSettings.Close()
' Print the information from the Test9999 subkey.
Console.WriteLine("There are {0} subkeys under Test9999.", _
test9999.SubKeyCount.ToString())
For Each subKeyName As String In test9999.GetSubKeyNames()
Dim tempKey As RegistryKey = _
test9999.OpenSubKey(subKeyName)
Console.WriteLine(vbCrLf & "There are {0} values for " & _
"{1}.", tempKey.ValueCount.ToString(), tempKey.Name)
For Each valueName As String In tempKey.GetValueNames()
Console.WriteLine("{0,-8}: {1}", valueName, _
tempKey.GetValue(valueName).ToString())
Next
Next
' Delete the ID value.
testSettings = test9999.OpenSubKey("TestSettings", True)
testSettings.DeleteValue("id")
' Verify the deletion.
Console.WriteLine(CType(testSettings.GetValue( _
"id", "ID not found."), String))
testSettings.Close()
' Delete or close the new subkey.
Console.Write(vbCrLf & "Delete newly created " & _
"registry key? (Y/N) ")
If Char.ToUpper(Convert.ToChar(Console.Read())) = "Y"C Then
Registry.CurrentUser.DeleteSubKeyTree("Test9999")
Console.WriteLine(vbCrLf & "Registry key {0} deleted.", _
test9999.Name)
Else
Console.WriteLine(vbCrLf & "Registry key {0} closed.", _
test9999.ToString())
test9999.Close()
End If
End Sub
End Class
i have the following module and i would like to test connection. how do i test if the connection works? can you please be very specific with your answer:
Imports System.Data.SqlClient
Module Module1
Sub Main()
' Create a new SqlConnectionStringBuilder and
' initialize it with a few name/value pairs:
Dim builder As New SqlConnectionStringBuilder(GetConnectionString())
' The input connection string used the
' Server key, but the new connection string uses
' the well-known Data Source key instead.
Console.WriteLine(builder.ConnectionString)
' Pass the SqlConnectionStringBuilder an existing
' connection string, and you can retrieve and
' modify any of the elements.
builder.ConnectionString = _
"server=http://sql.example.com;user id=******;" & _
"password=***********;"
' Now that the connection string has been parsed,
' you can work with individual items.
Console.WriteLine(builder.Password)
builder.Password = "new#1Password"
builder.AsynchronousProcessing = True
' You can refer to connection keys using strings,
' as well. When you use this technique (the default
' Item property in Visual Basic, or the indexer in C#)
' you can specify any synonym for the connection string key
' name.
builder("Server") = "."
builder("Connect Timeout") = 1000
' The Item property is the default for the class,
' and setting the Item property adds the value to the
' dictionary, if necessary.
builder.Item("Trusted_Connection") = True
Console.WriteLine(builder.ConnectionString)
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Sub
Private Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "Server=(local);Integrated Security=SSPI;" & _
"Initial Catalog=AdventureWorks"
End Function
End Module
After you have the connection string, you can open the connection using Connection.Open().
You can do that within a try-catch block to catch any errors that occur when you attempt to open the connection.enter code here
At any point before you close the connection with Connection.Close(), you can check its state using Connection.State. That returns values in an enum, such as ConnectionState.Open.
create a connection object, and open it
How can I loop through a folder getting each file listed and when its date/time?
Use DirectoryInfo.GetFiles() and extract the data (Name, CreationTime, etc.) from the FileInfo class.
I've pasted some code from the MSDN page here.
Imports System
Imports System.IO
Public Class GetFilesTest
Public Shared Sub Main()
' Make a reference to a directory.
Dim di As New DirectoryInfo("c:\")
' Get a reference to each file in that directory.
Dim fiArr As FileInfo() = di.GetFiles()
' Display the names of the files.
Dim fri As FileInfo
For Each fri In fiArr
Console.WriteLine(fri.Name)
Next fri
End Sub 'Main
End Class 'GetFilesTest
For Each LogFile In Directory.GetFiles(Application.StartupPath & "\Txt\")
' do whatever wtih filename
Next
we have the chance to develop in VB.Net (not in Java) and some variable's definitions can be shortened.
I still use GetFiles() and I have added the code to display the DateTime infos.
Imports System
Imports System.IO
...
Dim dir As New DirectoryInfo(sFolderName)
For Each f In dir.GetFiles()
Console.WriteLine(">> FILE-NAME: [" & f.Name & "]")
Console.WriteLine(">> UPDATE-DATE: " & f.lastWriteTime.toString("yyyy-MM-dd"))
Console.WriteLine(">> CREATE-DATE: " & f.creationTime.toString("yyyy-MM-dd"))
Next