This is form code for implementing SettingsXML class. The SettingsXML class is a simple class that can be included in a project and quickly used to modify user settings.
The button1_click event demonstrates how to use the class. It can obviously
be expanded and modified, but from postings I'd seen regarding the disappearance
of the appconfig in the properties portion in VS2005, and people suggesting how
to create a quick XML appsettings class, I decided to write this.
KB 8/162007
|
Imports System.IO Imports System.Xml Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim mySet As SettingsXML = New SettingsXML("test") 'for a new file, it will add 'defaultkey1' and 'defaultvalue1' rows ' so you can see contents in your file regardless 'adding a new row mySet.AddOrUpdtSetting("myNewKey1", "myNewValue1") 'adding another row mySet.AddOrUpdtSetting("myNewKey2", "myNewValue2") 'changing the value of the first row to ensure the search works, which it does mySet.AddOrUpdtSetting("mynewkey1", "ChangedValue1") End Sub End Class
Public Class SettingsXML Private fname As String Private xmldata As DataSet
Public Property filename() As String Get Return fname End Get Set(ByVal value As String) fname = value End Set End Property Public Sub New(ByVal filename As String) If Right(filename, 4) <> ".XML" Then filename = filename & ".XML" End If fname = filename xmldata = New DataSet If Not File.Exists(filename) Then xmldata.Tables.Add("AppSettings") xmldata.Tables(0).Columns.Add("Key") xmldata.Tables(0).Columns.Add("Value") Dim r1 As DataRow = xmldata.Tables(0).NewRow r1.Item(0) = "defaultkey1" r1.Item(1) = "defaultvalue1" xmldata.Tables(0).Rows.Add(r1) xmldata.WriteXmlSchema(filename) xmldata.WriteXml(filename) Else xmldata.ReadXmlSchema(filename) xmldata.ReadXml(filename) End If End Sub Private Sub AddNewRow(ByVal newkey As String, ByVal newvalue As String) Dim r1 As DataRow = xmldata.Tables(0).NewRow r1.Item(0) = newkey r1.Item(1) = newvalue xmldata.Tables(0).Rows.Add(r1) End Sub Public Sub AddOrUpdtSetting(ByVal searchkey As String, ByVal newvalue As String) xmldata.Tables(0).PrimaryKey = New DataColumn() {xmldata.Tables(0).Columns("Key")} Dim r1 As DataRow = xmldata.Tables(0).Rows.Find(searchkey) If Not r1 Is Nothing Then 'Console.WriteLine("Updated: " & searchkey & " with old value " & r1.Item(1) & " to new value " & newvalue) r1.Item(1) = newvalue Else 'Console.WriteLine("Inserted: " & searchkey & " value: " & newvalue) AddNewRow(searchkey, newvalue) End If xmldata.WriteXml(fname) End Sub
End Class
|
kurt bingham 2007