What am I doing wrong, calling a rest api - vb.net

I am new to .Net (any help will be greatly appreciated) and I am trying to implement this class to write to a rest api. All it does is pass in some data and does a postAsJsonAsync to the service.
It was written in C# and converted to VB.net to be added into a VB.net application solution.
It works once and then fails on the second call to it, when it initialises another instance of Uri.
Exception thrown: 'System.InvalidOperationException' in System.Net.Http.dllequest."}{"This instance has already started one or more requests. Properties can only be modified before sending the first request."}
Code here:
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Net.Http
Imports System.Net.Http.Headers
Namespace Logging
Public Class LogMessage
Public Property Application As String
Public Property Area As String
Public Property Activity As String
Public Property Description As String
Public Property User As String
End Class
Public Class ActionLogging
Public Shared Client As New HttpClient()
Public Shared Function AddToActionLog(Activity As String, Description As String, User As String)
Dim message = New LogMessage() With { _
.Activity = Activity, _
.Description = Description, _
.User = User, _
.Application = ConfigurationManager.AppSettings("Application"), _
.Area = ConfigurationManager.AppSettings("Area") _
}
If Run(message) IsNot Nothing
Run(message).Wait()
End If
End Function
Public Shared Function CreateMessage(message As LogMessage) As Uri
Dim task = Client.PostAsJsonAsync("Action", message)
task.Wait()
Dim response As HttpResponseMessage = task.Result
response.EnsureSuccessStatusCode()
Return response.Headers.Location
End Function
Public Shared Function Run(message As LogMessage) As Task
Client.BaseAddress = new Uri(ConfigurationManager.AppSettings("RestAPIServer"))
Client.DefaultRequestHeaders.Accept.Clear()
Client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
CreateMessage(message)
End Function
End Class
End Namespace

Imports System.Configuration
Imports System.Threading.Tasks
Imports System.Net.Http
Imports System.Net.Http.Headers
Namespace Logging
Public Class LogMessage
Public Property Application As String
Public Property Area As String
Public Property Activity As String
Public Property Description As String
Public Property User As String
End Class
Public Class ActionLogging
Private ReadOnly Shared Client As New HttpClient() With {.BaseAddress = new Uri(ConfigurationManager.AppSettings("RestAPIServer"))}
public Sub New()
Client.DefaultRequestHeaders.Accept.Clear()
Client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
End Sub
Public Shared Function AddToActionLog(activity As String, description As String, user As String)
Dim message = New LogMessage() With { _
.Activity = Activity, _
.Description = Description, _
.User = User, _
.Application = ConfigurationManager.AppSettings("Application"), _
.Area = ConfigurationManager.AppSettings("Area") _
}
SendMessage(message)
End Function
Private Shared Sub SendMessage(message As LogMessage)
Dim task = Client.PostAsJsonAsync("Action", message)
task.Wait()
Dim response As HttpResponseMessage = task.Result
response.EnsureSuccessStatusCode()
End Sub
End Class
End Namespace

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

VB.Net Function overload resolution issue in VS2017

while migrating the vb.net project from VS2010 to VS 2017 we are getting missing reference error due to incorrect function overload resolution
JS
**************************Project 1 *******************************
Imports Microsoft.Practices
Imports Microsoft.Practices.EnterpriseLibrary.Data
Public MustInherit Class DataLayerSQLBase
Private m_factory As EnterpriseLibrary.Data.DatabaseProviderFactory
Private m_database As Microsoft.Practices.EnterpriseLibrary.Data.Database
Public Function ExecuteReader(ByVal spName As String) As IDataReader
m_database = m_factory.CreateDefault
Return ExecuteReader(m_database, spName)
End Function
Public Function ExecuteReader(ByVal spName As String, ByVal secondparam As String) As IDataReader
m_database = m_factory.CreateDefault
Return ExecuteReader(m_database, spName)
End Function
Public Function ExecuteReader(ByVal database As EnterpriseLibrary.Data.Database, ByVal spName As String) As IDataReader
Dim m_Command = database.GetStoredProcCommand(spName)
m_Command.CommandTimeout = 300
Return m_Command.ExecuteReader
End Function
End Class
**************************Project 1 *******************************
**************************Project 2 *******************************
This project refers project 1 and doesn't have Enterprise.Library.Data.dll reference, this fails to compile in VS2017 asking for adding reference but works in VS2010 without adding reference
Imports ClassLibrary1
Public Class Class3
Inherits DataLayerSQLBase
Public Sub Test()
MyBase.ExecuteReader("aaaa", "aaaaa")
End Sub
End Class

VB.Net WCF Pass an array of class as a parameter to Client side

I have a WCF single channel implementation on the Server side and Client side. I have a custom class on the Server side that i am trying to pass to the client side. I am trying to pass an array (collection) of custom class to the client side.
Following is an example of the code implementation i have.
ServerSide class structure:
'Module name ServerModule.dll
Public Class ServerChildClass
Public m_Integer As Integer
Public Property mInteger As Integer
Get
Return m_Integer
End Get
Set(value As Integer)
m_Integer = value
End Set
End Property
End Class
Public Class ServerChildClass2
Public m_Integer As Integer
Public Property mInteger As Integer
Get
Return m_Integer
End Get
Set(value As Integer)
m_Integer = value
End Set
End Property
End Class
Public Class ServerChildClass3
Public m_Integer As Integer
Public Property mInteger As Integer
Get
Return m_Integer
End Get
Set(value As Integer)
m_Integer = value
End Set
End Property
End Class
WCF DataContract:
Imports System.ServiceModel
Imports System.Runtime.Serialization
Imports ServerModule
<DataContract(Name:="Transaction")> <Serializable()>
<KnownType(GetType(List(Of Object)))>
<KnownType(GetType(Integer))>
<KnownType(GetType(ServerChildClass))>
<KnownType(GetType(ServerChildClass2))>
<KnownType(GetType(ServerChildClass3))>
Public Class Transaction
Implements ICloneable
Implements IExtensibleDataObject
Public Sub New()
End Sub
'Add <DataMember()> here
Public Function Clone() As Object Implements System.ICloneable.Clone 'client uses this to define query
Dim newObject As New IHermesEngineServiceDataContract
Return newObject
End Function
Public Property ExtensionData As ExtensionDataObject Implements IExtensibleDataObject.ExtensionData
<DataMember()>
Public Property Command As Integer
<DataMember()>
Public Property Client As Integer
'A list of Integer, or a list of ServerChildClass or ServerChildClass2 or ServerChildClass3. Basically a list of objects
<DataMember()>
Public Property Parameters As System.Object()
End Class
WCF contract and class definition:
'Service contract
<ServiceContract()> _
Public Interface IControlContract
<OperationContract()>
Function GetUpdates(ByVal RequestType As Integer, ByRef Info As Transaction()) As Boolean
End Interface
'Service contract class implementation
Public Class ControlClass
Implements IControlContract
Function GetUpdates(ByVal RequestType As Integer, ByRef Info As Transaction()) As Boolean Implements IControlContract.GetUpdates
Return MyBase.Channel.GetUpdates(RequestType, Info)
End Function
End Class
WCF Server Side Implementation:
Imports ServerModule
Public Class WCFClass
Implements IControlContract
Public Function GetUpdates(ByVal RequestType As Integer, ByRef Info As Transaction()) As Boolean Implements IControlContract.GetUpdates
ReDim Info(2)
'Array of ServerChildClass of length x
Dim ClassArray As ArrayList
'Array of ServerChildClass2 of length x
Dim Class2Array As ArrayList
If (RequestType = 1) Then
Info(0) = New Transaction
Info(0).Command = RequestType
Info(0).Client = RequestType
Info(0).Parameters = ClassArray.ToArray()
Info(1) = New Transaction
Info(1).Command = RequestType
Info(1).Client = RequestType
Info(1).Parameters = Class2Array.ToArray()
Info(2) = New Transaction
Info(2).Command = RequestType
Info(2).Client = RequestType
Info(2).Parameters = "Test String"
End
Return True
End Function
End Class
When i send the following structure from the Server side to the client side, i receive the following error. "An error occurred while receiving the HTTP response to http://localhost/xyz. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details."
Please let me know where the issue is happening. How do i successfully send an array of class references as a parameter to the client side? Any help would be appreciated.
In Visual Studio, on your client project, Connected Services, right click on your WCF name, select "Configure Reference Service", on "Collection Type" select "System.Collections.Generic.List", click OK. Test again.

Inherited class not being returned from WCF Service

I have a Class2 and a Class1 in a project shared between service and client.
<DataContract> _
Public Class Class1
<DataMember> _
Public Property Test
End Class
<DataContract()> _
Public Class Class2(Of ReturnType)
<DataMember> _
Public Property Test As String
<DataMember()> _
Public Property Items() As ReturnType()
End Class
This is my service interface:
<ServiceContract(Name:="Service")> _
Public Interface IService
<OperationContract()> _
Function GetStuff() As Class2(Of Class1)
End Interface
And my service implementation:
Public Class Service
Implements IService
Public Function GetStuff() As Class2(Of Class1) Implements IService.GetStuff
Dim results As Class2(Of Class1) = New Class2(Of Class1)
Dim oClass1 As New Class1
results.Test = "test"
oClass1.Test = "test"
results.Items = {oClass1}
Return results
End Function
End Class
In my service project I also have a Class1 which inherits from the shared class:
Public Class Class1
Inherits [Shared].Entities.Class1
End Class
My client code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oEndpoint As New System.ServiceModel.EndpointAddress(New Uri("net.tcp://localhost/service"), _
System.ServiceModel.EndpointIdentity.CreateUpnIdentity(""))
Dim oClient As New ServiceClient("IService", oEndpoint)
Dim oList As Class2(Of Class1) = oClient.GetStuff()
MessageBox.Show(oList.Test)
MessageBox.Show(oList.Items.Length.ToString)
End Sub
Public Class ServiceClient
Inherits System.ServiceModel.ClientBase(Of IService)
Implements IService
Public Sub New(ByVal endpointConfigurationName As String, _
ByVal endpoint As System.ServiceModel.EndpointAddress)
MyBase.New(endpointConfigurationName, endpoint)
End Sub
Public Function GetStuff() As Class2(Of Class1) Implements IService.GetStuff
Dim oRet As Class2(Of Class1) = MyBase.Channel.GetStuff()
Return oRet
End Function
End Class
Running the button click results in two message boxes one with the string "Test" (expected) and one with the string 0 (I expected 1). As soon as I exclude the inherited Class1 from my service project it works as expected.
The thing is this project has been working for years like this and it is only when I recently made a change and rebuilt it that it has stopped working. How can I get this to work? Obviously in my real project, the Class1 in the service project contains some additional functionality I want to use.
What solved it for me was to add the Namespace to the derived class DataContract attribute. This was already present on the base class.

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