| 1 | Public MustInherit Class SettingBase(Of T As {Class, New})
|
|---|
| 2 |
|
|---|
| 3 | Protected Shared Function LoadSettings(ByVal FileId As String) As T
|
|---|
| 4 | Try
|
|---|
| 5 | Using fs As New IO.FileStream(GetSettingFilePath(FileId), IO.FileMode.Open, IO.FileAccess.Read)
|
|---|
| 6 | Dim xs As New Xml.Serialization.XmlSerializer(GetType(T))
|
|---|
| 7 | Return DirectCast(xs.Deserialize(fs), T)
|
|---|
| 8 | End Using
|
|---|
| 9 | Catch ex As System.IO.FileNotFoundException
|
|---|
| 10 | Return New T()
|
|---|
| 11 | Catch ex As Exception
|
|---|
| 12 | Throw
|
|---|
| 13 | End Try
|
|---|
| 14 | End Function
|
|---|
| 15 |
|
|---|
| 16 | Protected Shared Function LoadSettings() As T
|
|---|
| 17 | Return LoadSettings("")
|
|---|
| 18 | End Function
|
|---|
| 19 |
|
|---|
| 20 | Protected Shared Sub SaveSettings(ByVal Instance As T, ByVal FileId As String)
|
|---|
| 21 | Dim cnt As Integer = 0
|
|---|
| 22 | Do
|
|---|
| 23 | cnt += 1
|
|---|
| 24 | Using fs As New IO.FileStream(GetSettingFilePath(FileId), IO.FileMode.Create, IO.FileAccess.Write)
|
|---|
| 25 | Dim xs As New Xml.Serialization.XmlSerializer(GetType(T))
|
|---|
| 26 | xs.Serialize(fs, Instance)
|
|---|
| 27 | End Using
|
|---|
| 28 | If cnt > 3 Then Throw New System.InvalidOperationException("Can't write setting XML.")
|
|---|
| 29 | Loop Until ValidateXml(GetSettingFilePath(FileId))
|
|---|
| 30 | End Sub
|
|---|
| 31 |
|
|---|
| 32 | Private Shared Function ValidateXml(ByVal fileName As String) As Boolean
|
|---|
| 33 | Try
|
|---|
| 34 | Dim xdoc As New Xml.XmlDocument()
|
|---|
| 35 | xdoc.Load(fileName)
|
|---|
| 36 | Return True
|
|---|
| 37 | Catch ex As Exception
|
|---|
| 38 | Threading.Thread.Sleep(0)
|
|---|
| 39 | Return False
|
|---|
| 40 | End Try
|
|---|
| 41 | End Function
|
|---|
| 42 |
|
|---|
| 43 | Protected Shared Sub SaveSettings(ByVal Instance As T)
|
|---|
| 44 | SaveSettings(Instance, "")
|
|---|
| 45 | End Sub
|
|---|
| 46 |
|
|---|
| 47 | Public Shared Function GetSettingFilePath(ByVal FileId As String) As String
|
|---|
| 48 | Return IO.Path.Combine(My.Application.Info.DirectoryPath, GetType(T).Name + FileId + ".xml")
|
|---|
| 49 | End Function
|
|---|
| 50 | End Class
|
|---|