Class marked for Deliminted but error says not - vb.net

I have the dubious task of upgrading an old vb app which is using file helpers but for some reason, it appears to be ignoring the fact that I have marked it as a delimited record.
In the form it is using the following to attach the csv file to the record which is simlar to how c# does it.
Private Sub browseButton_Click(sender As System.Object, e As System.EventArgs) _
Handles browseButton.Click
Try
Dim file = GetFile()
'' Errors
Dim errors As New Dictionary(Of Integer, String)
If IO.File.Exists(file) Then
Dim engine As New FileHelperEngine(Of AveryOrderCsv)
_records = CType(engine.ReadFile(file), AveryOrderCsv()).ToList()
Dim count As Integer = 0
Dim success As Integer = 0
For Each averyOrderCsv As AveryOrderCsv In _records
Try
ImportProgressBar.Value = count
ImportProgressLabel.Text = String.Format("Importing {0} of {1} dockets",
count + 1, _records.Count())
System.Windows.Forms.Application.DoEvents()
If CreateSop(averyOrderCsv) Then
success = success + 1
End If
Catch ex As Exception
errors.Add(count, ex.Message)
End Try
count = count + 1
Next
End If
Catch ex As Exception
ExceptionManager.HandleUnexpectedException(ex)
End Try
The Class
Imports AveryIntegration.Common.CSV
Imports FileHelpers
Imports System
Imports System.Diagnostics
Namespace AveryIntegration.Common.CSV.Records
<DelimitedRecord(",")>
Public Class AveryOrderCsv
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String2 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String3 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String4 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String5 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String10 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String15 As String
Public Decimal1 As Decimal
Public Decimal5 As Decimal
Public Decimal8 As Decimal
Public Decimal9 As Decimal
Public Decimal10 As Decimal
Public Date1 As DateTime
Public Ticket2 As Integer
<DebuggerNonUserCode>
Public Sub New()
MyBase.New()
End Sub
End Class
End Namespace
The error that I am getting is the following but as you see from above i have declared it as a delimited record and imported the imports FileHelpers

In VB the attribute must be on the same logical line.
<DelimitedRecord(",")> Public Class AveryOrderCsv
or
<DelimitedRecord(",")> _
Public Class AveryOrderCsv
Same thing for the properties.
The article Applying Attributes says:
In Visual Basic, the attribute is surrounded by angle brackets and must be on the same logical line; the line continuation character can be used if a line break is desired.

Related

getting errore parsing a json file

i'm trying to extract data from a json file received from a web.i used newtonsoft library
i'm using this code :
Dim JSONtxt As String = File.ReadAllText("c:\temp\prova.json")
Dim account As Person = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Person)(JSONtxt)
the class is :
Public Class Person
Public Property validationType As String
Public Property lastName As String
Public Property firstName As String
End Class
unfortunately account does not get any value....
how can be ??
thanks for you help
this is my json :
{"listReservationReport":[{"validationType":"PRESENTE","bookingId":"xxxxx","travelId":null,"travelSolutionId":null,"couponId":"xxxxxx","transportMeanName":"aereo","transportClassification":"az","transportMeanDate":"16-01-2020","couponServiceType":"Posto a sedere","materializationType":"NON MATERIALIZZATO","fila":"6","seat":"2A","pnrCode":"xxxxxx","departureLocationName":"NAPOLI capodichino","arrivalLocationName":"ROMA fiumicino","cpCode":"xxxxxxx","offerName":"Super Economy","serviceLevel":"2° Premium","amount":"109,90","adults":1,"teens":0,"alreadyPaied":"--","alreadyCached":"--","ci204":"PRESENTE","firstName":"xxxxxxxx","lastName":"xxxxxx","channelName":"Internet B2C","gender":"Non disponibile","saleSystem":"galileo","travellerInfo":null,"validation":null},{"validationType":"PRESENTE","bookingId":"xxxxx","travelId":null,"travelSolutionId":null,"couponId":"xxxxxx","transportMeanName":"aereo","transportClassification":"az","transportMeanDate":"16-01-2020","couponServiceType":"Posto a sedere","materializationType":"NON MATERIALIZZATO","fila":"6","seat":"2A","pnrCode":"xxxxxx","departureLocationName":"NAPOLI capodichino","arrivalLocationName":"ROMA fiumicino","cpCode":"xxxxxxx","offerName":"Super Economy","serviceLevel":"2° Premium","amount":"109,90","adults":1,"teens":0,"alreadyPaied":"--","alreadyCached":"--","ci204":"PRESENTE","firstName":"xxxxxxxx","lastName":"xxxxxx","channelName":"Internet B2C","gender":"Non disponibile","saleSystem":"galileo","travellerInfo":null,"validation":null},{"validationType":"PRESENTE","bookingId":"xxxxx","travelId":null,"travelSolutionId":null,"couponId":"xxxxxx","transportMeanName":"aereo","transportClassification":"az","transportMeanDate":"16-01-2020","couponServiceType":"Posto a sedere","materializationType":"NON MATERIALIZZATO","fila":"6","seat":"2A","pnrCode":"xxxxxx","departureLocationName":"NAPOLI capodichino","arrivalLocationName":"ROMA fiumicino","cpCode":"xxxxxxx","offerName":"Super Economy","serviceLevel":"2° Premium","amount":"109,90","adults":1,"teens":0,"alreadyPaied":"--","alreadyCached":"--","ci204":"PRESENTE","firstName":"xxxxxxxx","lastName":"xxxxxx","channelName":"Internet B2C","gender":"Non disponibile","saleSystem":"galileo","travellerInfo":null,"validation":null}],"validatorList":[{"firstName":"xxxxx","lastName":"xxxx","roleId":"USR","enterpriseRoleType":"CST"},{"firstName":"xxxx ","lastName":"xxxx ","roleId":"xxx","enterpriseRoleType":"CT"},{"firstName":"x","lastName":"xxxx ","roleId":"USR","enterpriseRoleType":"CPV"},{"firstName":"xxx","lastName":"xxx","roleId":"USR","enterpriseRoleType":"CT"}],"materializedStatus":[{"onboard":30,"absent":0,"none":1,"defect":0,"undo":0}],"notMaterializedStatus":[{"onboard":522,"absent":0,"none":110,"defect":0,"undo":0}]}
Alright, give this a try....
Imports System.Linq
Imports BVSoftware.Bvc5.Core
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.IO
Imports System.Collections.ObjectModel
Partial Class _testPW22
Inherits System.Web.UI.Page
Private Class Person
Public Property validationType As String
Public Property lastName As String
Public Property firstName As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim JSONtxt As String = File.ReadAllText("c:\temp\prova.json")
Dim ob As JObject = JObject.Parse(JSONtxt)
Dim persons As New Collection(Of Person)()
For Each item As JObject In ob.SelectToken("listReservationReport")
Dim test As Person = JsonConvert.DeserializeObject(Of Person)(item.ToString())
persons.Add(test)
Next
End Sub
End Class

Cannot access lines based of header poco class

I am having the weirdest of errors.
Dim lines As List(Of NewOrderCsv) = (From record In _records Where record.Ticket2 = orderHeaderRow.Ticket2)
Their error is happening here on my declaration of the lines object
For Each line As NewOrderCsv In lines
CreateSopOrderLine(orderHeaderRow, newMcsOrder, newMcsOrder.AnalysisCode1, orderHeaderRow.String15, newMcsOrder.AnalysisCode1, newMcsOrder.ContactName, orderHeaderRow.String3, line)
Next
I am mostly a c# programer so forgive me if this is easy in vb.net
{"Unable to cast object of type
'WhereListIterator1[AveryIntegration.Common.CSV.Records.NewOrderCsv]'
to type
'System.Collections.Generic.List1[AveryIntegration.Common.CSV.Records.NewOrderCsv]'."}
The class for the NewOrderCSV is a file helpers
Namespace CSV.Records
<DelimitedRecord(",")>
Public Class NewOrderCsv
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String2 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String3 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String4 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String5 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String10 As String
<FieldConverter(GetType(CustomStringConvertor))>
<FieldQuoted>
Public String15 As String
Public Decimal1 As Decimal
Public Decimal5 As Decimal
Public Decimal8 As Decimal
Public Decimal9 As Decimal
Public Decimal10 As Decimal
Public Date1 As DateTime
Public Ticket2 As Integer
<DebuggerNonUserCode>
Public Sub New()
MyBase.New()
End Sub
End Class
My method was returning a single item I replaced the line with when it should been cast as a list cant believe I didn't see that.
Dim lines As List(Of NewOrderCsv) = (From record In _records Where record.Ticket2 = orderHeaderRow.Ticket2).ToList()

How to support contextual implicit conversions of custom object in Visual Basic .NET?

I want to use named error codes within my app. This should ensure, that every developer does not confuse numeric-only error codes with other codes, and also reduces the time a developer needs to realize what the error code should represent.
Compare this example:
Function New() As Integer
Return 0
End Function
with this example:
Function New() As Integer
Return ErrorCodes.ERROR_SUCCESS
End Function
Of course, I could let the developers write like the following:
Function New() As Integer
Return 0 ' ERROR_SUCCESS
End Function
However, the code above raises a pitfall when a developer updates the actual return code but forgets about the comment. Some developer look at the actual return code and some at the comment. I want to mitigate that confusion.
I come up the following class (extract):
Public Class ErrorCodes
Private msName As String = Nothing
Private miValue As Integer = 0
Public Shared ReadOnly ERROR_SUCCESS As ErrorCodes = New ErrorCodes("ERROR_SUCCESS", 0)
Private Sub New(ByVal psName As String, ByVal piValue As Integer)
msName = psName
miValue = piValue
End Sub
Public ReadOnly Property [Name] As String
Get
Return msName
End Get
End Property
Public ReadOnly Property [Value] As Integer
Get
Return miValue
End Get
End Property
Public Overrides Function ToString() As String
Return String.Format("[{0}]{1}", msName, miValue)
End Function
End Class
Now I want to use this ErrorCodes class like in the following example:
Function New() As Integer
Return ErrorCodes.ERROR_SUCCESS
End Function
As expected, I will produce an exception (type conversion) since the actual value I return is a instance of the class ErrorCodes instead of the generic data type Integer.
As you can see with the ToString() function, I let the class automatically/implicitly converts the instanced object into the generic data type String, when the class instance is assigned to a String typed variable.
Is there a way to do the same with the generic data type Integer like I did with ToString()?
I am using the .NET Framework 4.0, as for compatibility reasons with Windows XP SP3.
Another way to say what I want:
Dim stringVariable As String = ErrorCodes.ERROR_SUCCESS ' should be "[0]ERROR_SUCCESS".
Dim integerVariable As Integer = ErrorCodes.ERROR_SUCCESS ' should be 0.
I do not want to trigger implicit conversion warnings/errors, or to force the developer to typecast explicitly.
Yes you can do that with the use of Conversion Operators.
Here is the code:
Public Class Form1
Public Class ErrorCodes
Private msName As String = Nothing
Private miValue As Integer = 0
Public Shared Widening Operator CType(ByVal ec As ErrorCodes) As String
Return ec.ToString
End Operator
Public Shared Narrowing Operator CType(ByVal ec As ErrorCodes) As Integer
Return ec.Value
End Operator
Public Shared ReadOnly ERROR_SUCCESS As ErrorCodes = New ErrorCodes("ERROR_SUCCESS", 0)
Public Shared ReadOnly ERROR_FAILED As ErrorCodes = New ErrorCodes("ERROR_FAILED", 1)
Private Sub New(ByVal psName As String, ByVal piValue As Integer)
msName = psName
miValue = piValue
End Sub
Public ReadOnly Property [Name] As String
Get
Return msName
End Get
End Property
Public ReadOnly Property [Value] As Integer
Get
Return miValue
End Get
End Property
Public Overrides Function ToString() As String
Return String.Format("[{0}]{1}", msName, miValue)
End Function
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim em As String = ErrorCodes.ERROR_SUCCESS
Dim ev As Integer = ErrorCodes.ERROR_SUCCESS
Dim mm As String = String.Format("String: {0}, Value: {1}", em, ev)
MsgBox(mm)
End Sub
End Class
More info here
Hope this helps.
This, as jmcilhinney pointed out, uses Enums and the Description attribute.
Here is the class
'requires
' Imports System.Reflection
' Imports System.ComponentModel
Public Class ErrorCodes
Public Enum ErrCode 'these are the error codes
'note that the codes should be unique
<Description("Success")> ERROR_SUCCESS = 0
<Description("Error A")> ERROR_A = 1
End Enum
Public Class InfoForErrCode
Public TheDescription As String
Public TheValue As Integer
Public AsString As String
End Class
Public Shared Function Info(TheError As ErrCode) As InfoForErrCode
Dim rv As New InfoForErrCode
rv.TheDescription = GetDescription(TheError)
rv.TheValue = TheError
rv.AsString = TheError.ToString
Return rv
End Function
Private Shared Function GetDescription(TheError As ErrCode) As String
Dim rv As String = ""
Dim fi As FieldInfo = TheError.GetType().GetField(TheError.ToString())
Dim attr() As DescriptionAttribute
attr = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute),
False), DescriptionAttribute())
If attr.Length > 0 Then
rv = attr(0).Description
Else
rv = TheError.ToString()
End If
Return rv
End Function
End Class
And here is how it can be used
Dim foo As ErrorCodes.ErrCode = ErrorCodes.ErrCode.ERROR_SUCCESS
Dim inf As ErrorCodes.InfoForErrCode = ErrorCodes.Info(foo)
Stop 'examine inf
foo = ErrorCodes.ErrCode.ERROR_A
inf = ErrorCodes.Info(foo)
Stop 'examine inf

(De)Serializing in VB.Net

I have written a class (containing only properties). The code is shortened, here is only the part of the code what I want to do:
Public Class test
Public Overrides Function ToString() As String
'Das Objekt lebensmittel serialisieren
Dim ser As New Xml.Serialization.XmlSerializer(Me.GetType)
Dim sw As New IO.StringWriter
ser.Serialize(sw, Me)
Return sw.tostring
End Function
Public Sub New()
End Sub
Public Sub New(ByVal t As String)
Dim deser As New Xml.Serialization.XmlSerializer(Me.GetType)
Dim ms As New IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(t))
Me = CType(deser.Deserialize(ms), test) 'This throws an error
End Sub
End Class
What I want to do is to overload the New() operator and deserialize the string to this class, like:
Dim x As New test(string)
How can I do this? The marked line throws an error in Sub New.

Entity Framework : Error when trying to Deep clone an object

I'm using Entity Framework 6 , with Database First. The model is created using wizard from existing Sql server database.
I'm using this code to do a deep clone :
Imports System.ComponentModel
Imports System.Collections
Imports System.Data.Entity.Core.Objects.DataClasses
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Reflection
Imports System.Runtime.CompilerServices
Module Extensions
Private Function ClearEntityObject(Of T As Class)(ByVal source As T, ByVal bCheckHierarchy As Boolean) As T
If (source Is Nothing) Then
Throw New Exception("Null Object cannot be cloned")
End If
Dim tObj As Type = source.GetType
If (Not tObj.GetProperty("EntityKey") Is Nothing) Then
tObj.GetProperty("EntityKey").SetValue(source, Nothing, Nothing)
End If
If bCheckHierarchy Then
Dim PropertyList As List(Of PropertyInfo) = Enumerable.ToList(Of PropertyInfo)((From a In source.GetType.GetProperties
Where a.PropertyType.Name.Equals("ENTITYCOLLECTION`1", StringComparison.OrdinalIgnoreCase)
Select a))
Dim prop As PropertyInfo
For Each prop In PropertyList
Dim keys As IEnumerable = DirectCast(tObj.GetProperty(prop.Name).GetValue(source, Nothing), IEnumerable)
Dim key As Object
For Each key In keys
Dim childProp As EntityReference = Enumerable.SingleOrDefault(Of PropertyInfo)((From a In key.GetType.GetProperties
Where (a.PropertyType.Name.Equals("EntityReference`1", StringComparison.OrdinalIgnoreCase))
Select a)).GetValue(key, Nothing)
ClearEntityObject(childProp, False)
ClearEntityObject(key, True)
Next
Next
End If
Return source
End Function
<Extension()> _
Public Function ClearEntityReference(ByVal source As Object, ByVal bCheckHierarchy As Boolean) As Object
Return ClearEntityObject(source, bCheckHierarchy)
End Function
<Extension()> _
Public Function Clone(Of T)(ByVal source As T) As T
Dim ser As New DataContractSerializer(GetType(T))
Using stream As MemoryStream = New MemoryStream
ser.WriteObject(stream, source)
stream.Seek(0, SeekOrigin.Begin)
Return DirectCast(ser.ReadObject(stream), T)
End Using
End Function
End module
Now , I try to use this code like this :
Private Sub DoClone
Dim litm, newitm As MyObject
litm = context.MyObjects.FirstOrDefault
newitm = litm.Clone()
newitm.ClearEntityReference(True)
context.MyObjects.Add(newitm)
context.SaveChanges()
End Sub
I get an error :
An unhandled exception of type
'System.Runtime.Serialization.SerializationException' occurred in
System.Runtime.Serialization.dll
Additional information:Type
'System.Data.Entity.DynamicProxies.MyObject_F2FFE64DA472EB2B2BDF7E143DE887D3845AD9D1731FD3107937062AC0C2E4BB'
with data contract name
'MyObject_F2FFE64DA472EB2B2BDF7E143DE887D3845AD9D1731FD3107937062AC0C2E4BB:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected.
Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
This is my model that I use :
Partial Public Class Myobject
Public Property id As Integer
Public property name as string
Public Overridable Property chld As ICollection(Of chld) = New HashSet(Of chld)
Public Overridable Property chld1 As ICollection(Of chld1) = New HashSet(Of chld1)
End Class
Partial Public Class chld
Public Property id As Integer
Public Property date1 as DateTime
Public Property quantity as Integer
Public Property ParentID as integer
Public Overridable Property MyObj1 As MyObject
End Class
Partial Public Class chld1
Public Property id As Integer
Public Property nm as string
Public Property ParentID as integer
Public Overridable Property MyObj1 As MyObject
End Class