Windows 10 universal app. VB
I have the class below which I want to save to file and read from file, Saving works but when I attempt to load I get the error.
Message=Error in line 1 position 249. Element 'http://schemas.datacontract.org/2004/07/KoW_Universal_v2:MagicItem' contains data of the 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfKeyValueOfstringMagicItemyoeMIiQz' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'ArrayOfKeyValueOfstringMagicItemyoeMIiQz' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.
Source=System.Private.DataContractSerialization
Imports System.Runtime.Serialization
Imports Windows.Storage
Public Class MagicItem
Property MagicItemName As String
Property MagicItemCost As Integer
Property MagicItemDescripyion As String
Property LimitToHero As Boolean
Property LimitToSpecialRule As String 'key to the special rule
End Class
Public Class clsMagicItems
Private MagicItems As New Dictionary(Of String, MagicItem)
Async Sub SaveMagicItems()
' StorageFile File = Await openPicker.PickSingleFileAsync();
Dim myfile As StorageFile
myfile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("MagicItems.dat", CreationCollisionOption.ReplaceExisting)
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(clsMagicItems))
KnownTypeList.Add(GetType(MagicItem))
Dim r As Streams.IRandomAccessStream
r = Await myfile.OpenAsync(FileAccessMode.ReadWrite)
Using outStream As Streams.IOutputStream = r.GetOutputStreamAt(0)
Dim serializer As New DataContractSerializer(GetType(clsMagicItems), KnownTypeList)
serializer.WriteObject(outStream.AsStreamForWrite(), MagicItems)
Await outStream.FlushAsync()
outStream.Dispose()
r.Dispose()
End Using
End Sub
Async Sub LoadMagicItems()
Try
Dim myfile As Stream
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(clsMagicItems))
KnownTypeList.Add(GetType(MagicItem))
Dim serializer As New DataContractSerializer(GetType(clsMagicItems), KnownTypeList)
myfile = Await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("MagicItems.dat")
'LINE BELOW RAISE ERROR
MagicItems = serializer.ReadObject(myfile)
Catch
'failed to load the file
End Try
End Sub
End Class
Fixed it, should have had the following code
KnownTypeList.Add(GetType(Dictionary(Of String, MagicItem)))
...
Dim serializer As New DataContractSerializer(GetType(Dictionary(Of String, MagicItem)), KnownTypeList)
Related
Receiving below error on deserializing json to dataset.
Unexpected JSON token when reading DataTable. Expected StartArray, got Integer. Path 'id', line 1, position 9
Json Retrieved : {"id":130,"type":"general","setup":"test?","punchline":"test."}
My Code
Dim wc As New WebClient
Try
Dim res As String
For i = 0 To 5
res = wc.DownloadString("https://official-joke-api.appspot.com/random_joke")
Dim jObject = JsonConvert.DeserializeObject(res)
Dim ds As New DataSet
ds = JsonConvert.DeserializeObject(Of DataSet)(res)
MsgBox(ds.Tables.Count)
Next
Catch ex As Exception
MsgBox(ex)
End Try
As user Akshay Gaonkar commented, you can give Newtonsoft.Json a class, named, say, Joke, to deserialise with. You can get around the mismatch of uppercase/lowercase initial letter naming conventions by decorating the properties with <JsonProperty("nameInTheJson")>.
Instead of deserializing the data into a datatable inside a dataset, you could keep it simple and create a List(Of Joke).
This is for a console application:
Imports System.Net
Imports Newtonsoft.Json
Module Program
Class Joke
<JsonProperty("id")>
Property Id As Integer
<JsonProperty("type")>
Property Type As String
<JsonProperty("setup")>
Property Setup As String
<JsonProperty("punchline")>
Property Punchline As String
End Class
Sub Main(args As String())
Dim jokes As New List(Of Joke)
Using wc As New WebClient()
For i = 1 To 5
Dim jokeInfo = wc.DownloadString("https://official-joke-api.appspot.com/random_joke")
jokes.Add(JsonConvert.DeserializeObject(Of Joke)(jokeInfo))
Next
End Using
' Alternative which fetches ten jokes in one go - note the use of (Of List(Of Joke))
'Using wc As New WebClient()
' Dim jokeInfo = wc.DownloadString("https://official-joke-api.appspot.com/jokes/ten")
' jokes = JsonConvert.DeserializeObject(Of List(Of Joke))(jokeInfo)
'End Using
For Each jk In jokes
Console.WriteLine($"{jk.Setup}{vbCrLf}{jk.Punchline}{vbCrLf}")
Next
End Sub
End Module
The Using statement is needed because a WebClient should be disposed of after use to clear up system resources. (You could use the equivalent Try...Finally with wc.Dispose() instead.)
The JSON you showed is invalid. Datatable is expecting array of Object , so the JSON should look like below :
[{"id":130,"type":"general","setup":"test?","punchline":"test."}]
I'm trying to import a CSV file into a DataGridView but I'm running in some issues when I try to import multiline text.
What I'm trying to import is this:
ID;RW;Name;Description;Def;Unit;Min;Max
0;R;REG_INFO;"state of the
machine";0;ms;0;0xFFFF
1;R/W;REG_NUMBER;current number;0;days;0;65,535
This is what it should like when imported:
What I've implemented till now:
Private Sub btnOpen_Click(sender As Object, e As EventArgs) Handles btnOpen.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "Text file|*.csv"}
If ofd.ShowDialog() = DialogResult.OK Then
Dim lines As List(Of String) = File.ReadAllLines(ofd.FileName).ToList()
Dim list As List(Of Register) = New List(Of Register)
For i As Integer = 1 To lines.Count - 1
Dim data As String() = lines(i).Split(";")
list.Add(New Register() With {
.ID = data(0),
.RW = data(1),
.Name = data(2),
.Description = data(3),
.Def = data(4),
.Unit = data(5),
.Min = data(6),
.Max = data(7)
})
Next
DataGridView1.DataSource = list
End If
End Using
End Sub
But I run in some problems with multiline text when I try to load the CSV, as "state of the machine" in the example.
An example, using the TextFieldParser class.
(This class is available in .Net 5)
The TextFieldParser object provides methods and properties for parsing
structured text files. Parsing a text file with the TextFieldParser is
similar to iterating over a text file, while using the ReadFields
method to extract fields of text is similar to splitting the strings
Your source of data is a delimited (not fixed-length) structure, the header/fields values are separated by a symbol, so you can specify TextFieldType = FieldType.Delimited
The delimiter is not a comma (the C in CSV), so you need to pass the delimiter symbol(s) to the SetDelimiters() method.
Call the ReadFields() to extract each line as an array of String, representing the Fields' values (=> here, no conversion is performed, all values are returned as strings. Make your own Type converter in case it's needed.)
Imports Microsoft.VisualBasic.FileIO
Public Class RegisterParser
Private m_FilePath As String = String.Empty
Private m_delimiters As String() = Nothing
Public Sub New(sourceFile As String, delimiters As String())
m_FilePath = sourceFile
m_delimiters = delimiters
End Sub
Public Function ReadData() As List(Of Register)
Dim result As New List(Of Register)
Using tfp As New TextFieldParser(m_FilePath)
tfp.TextFieldType = FieldType.Delimited
tfp.SetDelimiters(m_delimiters)
tfp.ReadFields()
Try
While Not tfp.EndOfData
result.Add(New Register(tfp.ReadFields()))
End While
Catch fnfEx As FileNotFoundException
MessageBox.Show($"File not found: {fnfEx.Message}")
Catch exIDX As IndexOutOfRangeException
MessageBox.Show($"Invalid Data format: {exIDX.Message}")
Catch exIO As MalformedLineException
MessageBox.Show($"Invalid Data format at line {exIO.Message}")
End Try
End Using
Return result
End Function
End Class
Pass the path of the CSV file and the set of delimiters to use (here, just ;).
The ReadData() method returns a List(Of Register) objects, to assign to the DataGridView.DataSource.
DefaultCellStyle.WrapMode is set to True, so multiline text can actually wrap in the Cell (otherwise it would be clipped).
After that, call AutoResizeRows(), so the wrapped text can be seen.
Dim csvPath = [The CSV Path]
Dim csvParser = New RegisterParser(csvPath, {";"})
DataGridView1.DataSource = csvParser.ReadData()
DataGridView1.Columns("Description").DefaultCellStyle.WrapMode = DataGridViewTriState.True
DataGridView1.AutoResizeRows()
Register class:
Added a constructor that accepts an array of strings. You could change it to Object(), then add a converter to the class to parse and convert the values to another Type.
Public Class Register
Public Sub New(ParamArray values As String())
ID = values(0)
RW = values(1)
Name = values(2)
Description = values(3)
Def = values(4)
Unit = values(5)
Min = values(6)
Max = values(7)
End Sub
Public Property ID As String
Public Property RW As String
Public Property Name As String
Public Property Description As String
Public Property Def As String
Public Property Unit As String
Public Property Min As String
Public Property Max As String
End Class
I'm trying to implement functionality to allow the user to select his favorite forms. Favorite forms are forms he/she needs quick access to. To avoid browsing for too long through the ToolStripMenu's.
I try to save a reference to a form in the application configuration. But I'm getting the error
Value of type 'System.Windows.Forms.Form' cannot be converted to
'String'.
Public Sub SetSetting(ByVal pstrKey As String, ByVal frmFavorite As Form)
Dim keyExists As Boolean = False
For Each strKey As String In configuration.AppSettings.Settings.AllKeys
If strKey.Equals(pstrKey) Then
configuration.AppSettings.Settings.Item(pstrKey).Value = frmFavorite
keyExists = True
End If
Next
If Not keyExists Then
configuration.AppSettings.Settings.Add(pstrKey, frmFavorite)
End If
configuration.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
End Sub
You can only store string values in the application config file, no objects.
But just store the name of the Form in the config file.
When starting your application create the form via reflection like shown in this Object Factory example.
Public Class ObjectFactory
Public Shared Function CreateAnObject(ByVal ObjectName As String) As Object
Dim Assem = [Assembly].GetExecutingAssembly()
Dim myType As Type = Assem.GetType(ObjectName.Trim)
Dim o As Object = Nothing
Try
o = Activator.CreateInstance(myType)
Catch oEx As TargetInvocationException
MessageBox.Show(oEx.ToString)
End Try
Return o
End Function
End Class
...
Dim formName as String = configuration.AppSettings.Settings.Item(<YourSettingKey>)
Dim oForm As Form = _
ObjectFactory.CreateAnObject(formName)
I have a collection of objects which also contain collections, and I would like to save them to a file and read later. This is Windows 10 UNIVERSAL app .net 4.5 and in VB
I've this, but it gives the error "Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run."}
Public Sub SaveSpRules(FileName As String)
Dim fs As New FileStream(FileName, FileMode.OpenOrCreate)
Dim serializer As New XmlSerializer(GetType(Rule))
Dim writer As New StreamWriter(fs)
serializer.Serialize(writer, r)
End Sub
Rule is class and the collection is called SpecialRulesCollection, this code does compile but doesn't work
Any help is gratefully received. PLEASE note this for Windows 10 Universal app, I can't get BinaryWriter to compile as this isn't include in the Universal app.
Thanks Oyiwai I found the answer
Public Async Sub SaveSpRules(FileName As String, t As Object)
Dim myfile As StorageFile
myfile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("test.dat", CreationCollisionOption.ReplaceExisting)
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(Rules))
KnownTypeList.Add(GetType(Rule))
Dim r As Streams.IRandomAccessStream
r = Await myfile.OpenAsync(FileAccessMode.ReadWrite)
Using outStream As Streams.IOutputStream = r.GetOutputStreamAt(0)
Dim serializer As New DataContractSerializer(GetType(Rules), KnownTypeList)
serializer.WriteObject(outStream.AsStreamForWrite(), t)
Await outStream.FlushAsync()
outStream.Dispose()
r.Dispose()
End Using
End Sub
Public Async Sub ReadFile()
Dim t As New Collection(Of Rule)
Dim myfile As Stream
Dim r As New Rules
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(Rules))
Dim serializer As New DataContractSerializer(GetType(Rules), KnownTypeList)
myfile = Await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("test.dat")
r = serializer.ReadObject(myfile)
End Sub
I am trying to write some code that will allow me to dynamically load DLLs into my application, depending on an application setting. The idea is that the database to be accessed is set in the application settings and then this loads the appropriate DLL and assigns it to an instance of an interface for my application to access.
This is my code at the moment:
Dim SQLDataSource As ICRDataLayer
Dim ass As Assembly = Assembly. _
LoadFrom("M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\SQLServer.dll")
Dim obj As Object = ass.CreateInstance(GetType(ICRDataLayer).ToString, True)
SQLDataSource = DirectCast(obj, ICRDataLayer)
MsgBox(SQLDataSource.ModuleName & vbNewLine & SQLDataSource.ModuleDescription)
I have my interface (ICRDataLayer) and the SQLServer.dll contains an implementation of this interface. I just want to load the assembly and assign it to the SQLDataSource object.
The above code just doesn't work. There are no exceptions thrown, even the Msgbox doesn't appear.
I would've expected at least the messagebox appearing with nothing in it, but even this doesn't happen!
Is there a way to determine if the loaded assembly implements a specific interface. I tried the below but this also doesn't seem to do anything!
For Each loadedType As Type In ass.GetTypes
If GetType(ICRDataLayer).IsAssignableFrom(loadedType) Then
Dim obj1 As Object = ass.CreateInstance(GetType(ICRDataLayer).ToString, True)
SQLDataSource = DirectCast(obj1, ICRDataLayer)
End If
Next
EDIT: New code from Vlad's examples:
Module CRDataLayerFactory
Sub New()
End Sub
' class name is a contract,
' should be the same for all plugins
Private Function Create() As ICRDataLayer
Return New SQLServer()
End Function
End Module
Above is Module in each DLL, converted from Vlad's C# example.
Below is my code to bring in the DLL:
Dim SQLDataSource As ICRDataLayer
Dim ass As Assembly = Assembly. _
LoadFrom("M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\SQLServer.dll")
Dim factory As Object = ass.CreateInstance("CRDataLayerFactory", True)
Dim t As Type = factory.GetType
Dim method As MethodInfo = t.GetMethod("Create")
Dim obj As Object = method.Invoke(factory, Nothing)
SQLDataSource = DirectCast(obj, ICRDataLayer)
EDIT: Implementation based on Paul Kohler's code
Dim file As String
For Each file In Directory.GetFiles(baseDir, searchPattern, SearchOption.TopDirectoryOnly)
Dim assemblyType As System.Type
For Each assemblyType In Assembly.LoadFrom(file).GetTypes
Dim s As System.Type() = assemblyType.GetInterfaces
For Each ty As System.Type In s
If ty.Name.Contains("ICRDataLayer") Then
MsgBox(ty.Name)
plugin = DirectCast(Activator.CreateInstance(assemblyType), ICRDataLayer)
MessageBox.Show(plugin.ModuleName)
End If
Next
I get the following error with this code:
Unable to cast object of type 'SQLServer.CRDataSource.SQLServer' to type 'DynamicAssemblyLoading.ICRDataLayer'.
The actual DLL is in a different project called SQLServer in the same solution as my implementation code. CRDataSource is a namespace and SQLServer is the actual class name of the DLL.
The SQLServer class implements ICRDataLayer, so I don't understand why it wouldn't be able to cast it.
Is the naming significant here, I wouldn't have thought it would be.
Final Working code
Contents of PluginUtility:
enter code here Public Shared Function GetInstances1(Of Type)(ByVal baseDir As String, ByVal searchPattern As String) As System.Type()
Dim tmpInstances As New List(Of Type)
Try
Dim file As String
For Each file In Directory.GetFiles(baseDir, searchPattern, SearchOption.TopDirectoryOnly)
Dim assemblyType As System.Type
For Each assemblyType In Assembly.LoadFrom(file).GetTypes
Dim s As System.Type() = assemblyType.GetInterfaces
Return s.ToArray()
Next
Next
Catch exp As TargetInvocationException
If (Not exp.InnerException Is Nothing) Then
Throw exp.InnerException
End If
End Try
End Function
Code to load the DLL:
enter code here
Dim basedir As String = "M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\"
Dim searchPattern As String = "*SQL*.dll"
Dim plugin As CRDataLayer.ICRDataLayer
Try
Dim file As String
For Each file In Directory.GetFiles(baseDir, searchPattern, SearchOption.TopDirectoryOnly)
Dim assemblyType As System.Type
For Each assemblyType In Assembly.LoadFrom(file).GetExportedTypes
If assemblyType.GetInterface("CRDataLayer.ICRDataLayer") IsNot Nothing Then
plugin = DirectCast(Activator.CreateInstance(assemblyType), CRDataLayer.ICRDataLayer)
MessageBox.Show(plugin.ModuleDescription)
End If
Next
Next
Catch exp As TargetInvocationException
If (Not exp.InnerException Is Nothing) Then
Throw exp.InnerException
End If
Catch ex As Exception
MsgBox(ex.Message)
Clipboard.SetText(ex.Message)
End Try
Version 2 - This sample loads up a DLL from it current directory.
There are 2 projects, 1 console application project and a "module" project (the module 'coppies' its DLL to the working directory of the console app).
The sample below simply demonstrates dynamically loading a DLL that implements an interface. The IModule interface just reports its name. PlugInUtility.GetInstances(Of IModule)(Environment.CurrentDirectory, "*.Module.dll") will create an instance of any IModule instance found in a DLL within the current directory ending with ".Module.dll". It's a reflected VB.NET version straight out of Mini SQL Query.
With that in mind something like:
Dim modules As IModule() = PlugInUtility.GetInstances(Of ICRDataLayer)(Environment.CurrentDirectory, "*.Server.dll")
Should satisfy your requirement. Then you just need to chose which one to execute!
The code:
In "VB.LoaderDemo Colsole App"
' IModule.vb
Public Interface IModule
Property ModuleName() As String
End Interface
' PlugInUtility.vb
Imports System.IO
Imports System.Reflection
Public Class PlugInUtility
Public Shared Function GetInstances(Of T)(ByVal baseDir As String, ByVal searchPattern As String) As T()
Dim tmpInstances As New List(Of T)
Try
Dim file As String
For Each file In Directory.GetFiles(baseDir, searchPattern, SearchOption.TopDirectoryOnly)
Dim assemblyType As Type
For Each assemblyType In Assembly.LoadFrom(file).GetTypes()
If (Not assemblyType.GetInterface(GetType(T).FullName) Is Nothing) Then
tmpInstances.Add(DirectCast(Activator.CreateInstance(assemblyType), T))
End If
Next
Next
Catch exp As TargetInvocationException
If (Not exp.InnerException Is Nothing) Then
Throw exp.InnerException
End If
End Try
Return tmpInstances.ToArray()
End Function
End Class
' MainModule.vb
Module MainModule
Sub Main()
Dim plugins As IModule() = PlugInUtility.GetInstances(Of IModule)(Environment.CurrentDirectory, "*.Module.dll")
Dim m As IModule
For Each m In plugins
Console.WriteLine(m.ModuleName)
Next
End Sub
End Module
In "Sample1 DLL" (references 'VB.LoaderDemo' for IModule)
Imports VB.LoaderDemo
Public Class MyModule1
Implements IModule
Dim _name As String
Public Sub New()
_name = "Sample 1, Module 1"
End Sub
Public Property ModuleName() As String Implements IModule.ModuleName
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
The output is:
> Sample 1, Module 1
Is the type ICRDataLayer defined in the DLL you are going to load? If so, you seem to already reference the DLL in your project settings.
You need to work with just reflection:
Dim obj As Object = ass.CreateInstance("ICRDataLayer", True)
Dim t as Type = obj.GetType()
Dim method as MethodInfo = t.GetMethod("DoSomething")
method.Invoke(obj, ...)
Edit: If ICRDataLayer is implemented in the application, and the plugin just implements the interface, you need the plugin to provide a factory for you: (sorry for C# code, I am not familiar with VB.NET's syntax)
// in each of plugins:
static class CRDataLayerFactory // class name is a contract,
{ // should be the same for all plugins
static ICRDataLayer Create()
{
return new CRDataLayerImplementation();
}
}
The application's code should look like this:
Dim factory As Object = ass.CreateInstance("CRDataLayerFactory", True)
Dim t as Type = factory.GetType()
Dim method as MethodInfo = t.GetMethod("Create")
Dim obj as Object = method.Invoke(factory, null)
SQLDataSource = DirectCast(obj, ICRDataLayer)
A few things to look for in your code
Debug through and check that the
assembly is loaded correctly, in case
it fails due to dependency checking
Instead of using GetType, use GetExportedType so you have smaller subset to iterate through
The CreateInstance should use your loadedType rather than the interface (you cant create object from an interface)
Personally, I dont like naming my variable ass, I would shorten it to assem instead :)