Frederic GIRARDIN
Я должен написать расширение защищенной функции для набора данных в моей программе.
Он должен принимать во внимание символ "_" в dataset.getttype.name чтобы разделить информацию. Тогда у меня должно быть достаточно информации, чтобы вычислить мое собственное имя переменной connnectionString :
dataset.gettype.name = {ExtentionFormat_dataset_versionnumber} (пример : ESTX_DataSet_1)
так индекса estx-это набор данных.метод gettype.имя.сплит("_")(0) значение 1 и есть набор данных.метод gettype.имя.сплит("_")(2) Значение.
Согласно моей собственной работе, имя переменной Connectionstring должно быть ESTX_ConnectionString_1.
Тогда это легко создать некоторое расширение поднабора данных, например Set_ConnectionString и Get_ConnectionString, основанное на GetConnectionStringName.
Imports System.Runtime.CompilerServices
Module DataSetExtentions
<Extension()>
Protected function GetConnectionStringName(MyDataset as dataset) as string
dim _szextention as string = MyDataSet.GetType.Name.Split("_")(0)
dim _szVersion as string = MyDataSet.GetType.Name.Split("_")(2)
Return _szextention & "_ConnectionString_" & _szVersion
end function
<Extension()>
Protected function Get_ConnectionString(MyDataSet as dataSet) as string
return My.Settings(MyDataSet.GetConnectionStringName)
end function
<Extension()>
Protected sub Set_ConnectionString(myDataSet as dataset, Myvalue as string)
My.Settings(MyDataSet.GetConnectionStringName) = myValue
end sub
end module
Поэтому использование кода должно быть :
imports System.Reflection
imports System.oledb
public Class DataLayer
Private ds as dataset
Private _connectionString as string
Private _connection as oledbConnection
Private _TableManager As Object
Public sub New(File as string)
'read file extention to set the Dataset Type
dim _szExtension as string = system.io.file.getExtention(File)
'set the connection string for the whole use
_connectionstring = "Provider=...;DataSource=" & File & ";" & ...
'set the connection
_connection = new oledbconnection(_connectionstring)
'now a pre process to open a minimalist dataset with only one intengible table, to read format version
SyncLock my.setting(ds.GetConnectionStringName)
ds = new intangible_dataset(_conn)
ds.Set_ConnectionString = _connectionstring
'load TableAdapterManager
_classname = System.Reflection.Assembly.GetExecutingAssembly().GetName.Name _
.Replace(" ", "_") & "." & DataSet.GetType.Name & _
"TableAdapters.TableAdapterManager"
_TableManager = System.Reflection.Assembly.GetExecutingAssembly.CreateInstance(_classname)
InitTableManager()
'open connection
_connection.open
'read Version format
dim dtConfig as datatable = loadTable("CONFIG")
dim szVersion as string = dtConfig.Rows(0)("Version")
'close connection
_connection.close
ds.Dispose
ds = nothing
CType(_TableManager, IDisposable).Dispose()
_TableManager = nothing
'create a variable to store dataset type
dim tDs as system.type
'compute type name of Dataset
dim _className as string ' = ...
'create dynamic instance of tDS
ds = System.Reflection.Assembly.GetExecutingAssembly.CreateInstance(_classname)
ds.Set_ConnectionString = _connectionstring
'Dynamic load of _tableAdapterManager
_classname = System.Reflection.Assembly.GetExecutingAssembly().GetName.Name _
.Replace(" ", "_") & "." & DataSet.GetType.Name & _
"TableAdapters.TableAdapterManager"
_TableManager = System.Reflection.Assembly.GetExecutingAssembly.CreateInstance(_classname)
InitTableManager()
End SyncLock
'ready to use : open, close, loadtable
end sub
Private Sub InitTableManager()
'give the connection
_TableManager.Connection = _Connection
'set every tableAdapter for each property
For Each _table As DataTable In _Dataset.Tables
Dim _Adapter As Object = Nothing
Try
Dim _classname As String = Assembly.GetExecutingAssembly() _
.GetName.Name.Replace(" ", "_") & "." &
_Dataset.GetType.Name & "TableAdapters." &
_table.TableName & "TableAdapter"
_Adapter = Assembly.GetExecutingAssembly.CreateInstance(_classname)
CallByName(_TableManager, _table.TableName & "TableAdapter", CallType.Set, _Adapter)
'this part is no more needed because we are able to set the connectionstring used by the the current dataset
#if false then
Dim pinfo As PropertyInfo =
_Adapter.GetType.GetProperties(BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance).Where(Function(w) w.Name = "Connection").FirstOrDefault
If pinfo IsNot Nothing Then
pinfo.SetValue(_Adapter, _TableManager.Connection)
Else
Stop
End If
#End if
Catch ex As Exception
Debug.Print(ex.Message)
stop
End Try
Next
End Sub
Public function LoadTable(aTableName as string, optional clone as boolean = false) as datatable
dim _Adapter as object
'if connection is close then open it
if _connection.state = close then _connection.Open()
'dynamically tableAdapterproperty for _tableAdapter Classname
dim _propertyName as string = aTableName & "TableAdapter"
'get adapter from TableAdapterManager
_Adapter = CallByName(_TableManager, _propertyName, CallType.Get)
Dim dt As DataTable = Nothing
If clone Then
dt = _ds.Tables(aTableName).Clone
Else
dt = _ds.Tables(aTableName)
End If
SyncLock dt
_Adapter.Fill(dt)
End SyncLock
return dt
end function
Public readonly DataSet as Dataset
get
return _ds
end get
end property
End class
Frederic GIRARDIN
обратите внимание : все, что нам нужно, - это сохранить значение connectionstring измененным во время создания экземпляра _TableAdapterManager. Затем устанавливается ConnectionString для всего использования класса DataLayer.