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
Related
The code of TDBACore.vb:
Imports System.ComponentModel
Imports System.Data
<EditorBrowsable(EditorBrowsableState.Never)> _
Public MustInherit Class TDBACore
Private Shared FRefCount As Integer
Friend Shared FIsBeginTran As Boolean = False
Friend Shared FConnection As IDbConnection
Friend Shared FTransaction As IDbTransaction
Private disposedValue As Boolean
Friend Shared iRecheckTimeout As Integer
Friend Shared iConnectionTimeOut As Integer
Friend MustOverride Function CreateConnection() As IDbConnection
Public Sub New()
Me.disposedValue = False
If TDBACore.FRefCount = 0 Then
TDBACore.FConnection = Me.CreateConnection()
End If
TDBACore.FRefCount += 1
End Sub
Friend Shared Sub OpenConnection(ByVal ConnectionString As String)
If TDBACore.FConnection.State = ConnectionState.Closed Then
TDBACore.FConnection.ConnectionString = ConnectionString
TDBACore.FConnection.Open()
End If
End Sub
End Class
The code of TDBOpener.vb:
Public NotInheritable Class TDBOpener
Inherits TDBACore
Public Shared ReadOnly _TDBOpener As New TDBOpener()
Friend Overrides Function CreateConnection() As IDbConnection
Return New NpgsqlConnection()
End Function
Public Shared Sub SetTimeoutValue(ByVal param_iRecheckTimeout As Integer, ByVal param_iConnectionTimeOut As Integer)
TDBACore.iConnectionTimeOut = param_iConnectionTimeOut
TDBACore.iRecheckTimeout = param_iRecheckTimeout
End Sub
Public Shared Sub Open(ByVal ConnectionString As String)
TDBACore.OpenConnection(ConnectionString)
End Sub
End Class
I test connect to postgresql by Npgsql.dll 3.2.2.0:
TDBOpener.Open("Server=192.168.1.10;Port=5434;UserId=postgres;Password=123456;Database=testdb;CommandTimeout=300;")
I using Win 10, 64bit, vs 2017 .Net Framework 4.6
If i run by mode [Debug]: it can run function New() of TDBACore and connect ok.
But if i run by mode [Release], it not go to function New() of TDBACore.
Why? thanks all.(Notes: I try on win 7, it is ok.)
Win 10, 64bit, vs 2017 .Net Framework 4.6:
If i run by mode [Release], it can't init Public Shared ReadOnly _TDBOpener As New TDBOpener()
My solution edit function Open of TDBOpener:
Public Shared Sub Open(ByVal ConnectionString As String)
If TDBACore.FConnection Is Nothing Then
Dim obOpen = _TDBOpener
End If
TDBACore.OpenConnection(ConnectionString)
End Sub
The reason you were having the problem, and the reason that the fix works, is because the compiler was optimizing out _TDBOpener since it wasn't being referenced. This question has more details.
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
I have a WebService defined as this:
<WebMethod(Description:="Retrieve a list of account profiles.")> _
<System.Web.Services.Protocols.SoapHeader("MyHeader")> _
Public Function RetrieveAccountProfile(<XmlElement(IsNullable:=True, Type:=GetType(WSRetrieveAccountProfile))> ByVal myAccount As WSRetrieveAccountProfile) As <XmlElement(IsNullable:=True)> WSResponseRetrieveAccountProfile
...
The class I am passing as an input parameter WSRetrieveAccountProfile is defined like this:
<Serializable()> _
<XmlType(Namespace:="http://mynamespace/", TypeName:="WSRetrieveAccountProfile")> _
Public Class WSRetrieveAccountProfile
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
Public Sub New()
End Sub
Public Function Validate() As Boolean
'Validations here
Return True
End Function
End Class
The issue: I consume web-service and I am working on the client side where I am trying to declare an object of type WSRetrieveAccountProfile so I can pass it as an input parameter when calling the web-service, but I get compilation error - it cannot recognize the type.
After checking Reference.vb I notice that an input parameter for the function is a plain array of Integer ByVal myAccount() As Integer. Now, if I add another variable to the WSRetrieveAccountProfile class definition the ByVal myAccount() As Integer suddenly changes to ByVal myAccount As WSRetrieveAccountProfile and problem is solved.
How do I solve this WITHOUT adding an unnecessary variable? I tried with XmlType attribute with no luck.
* UPDATE *
This definition works:
<Serializable()> _
<XmlType(Namespace:="http://mynamespace/", TypeName:="WSRetrieveAccountProfile")> _
Public Class WSRetrieveAccountProfile
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
<XmlElement(IsNullable:=True)> Public TEST As String
Public Sub New()
End Sub
Public Function Validate() As Boolean
'Validations here
Return True
End Function
End Class
* UPDATE - SOLUTION *
If I change
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
to
<XmlArray(IsNullable:=True)> Public accountNumber As List(Of Integer)
then the proxy is generated properly and I no longer have an issue.
Change
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
to
<XmlArray(IsNullable:=True)> Public accountNumber As List(Of Integer)
to fix proxy generation.
The code below works for the class that I hard coded "XCCustomers" in my RetrieveIDandName method where I use CType. However, I would like to be able to pass in various classes and property names to get the integer and string LIST returned. For example, in my code below, I would like to also pass in "XCEmployees" to my RetrieveIDandName method. I feel so close... I was hoping someone knew how to use CType where I can pass in the class name as a string variable.
Note, all the other examples I have seen and tried fail because we are using Option Strict On which disallows late binding. That is why I need to use CType.
I also studied the "Activator.CreateInstance" code examples to try to get the class reference instance by string name but I was unable to get CType to work with that.
When I use obj.GetType.Name or obj.GetType.FullName in place of the "XCCustomers" in CType(obj, XCCustomers)(i)
I get the error "Type 'obj.GetType.Name' is not defined" or "Type 'obj.GetType.FullName' is not defined"
Thanks for your help.
Rick
'+++++++++++++++++++++++++++++++
Imports DataLaasXC.Business
Imports DataLaasXC.Utilities
Public Class ucCustomerList
'Here is the calling method:
Public Sub CallingSub()
Dim customerList As New XCCustomers()
Dim customerIdAndName As New List(Of XCCustomer) = RetrieveIDandName(customerList, "CustomerId", " CustomerName")
'This code below fails because I had to hard code “XCCustomer” in the “Dim item...” section of my RetrieveEmployeesIDandName method.
Dim employeeList As New XCEmployees()
Dim employeeIdAndName As New List(Of XCEmployee) = RetrieveIDandName(employeeList, "EmployeeId", " EmployeeName")
'doing stuff here...
End Sub
'Here is the method where I would like to use the class name string when I use CType:
Private Function RetrieveIDandName(ByVal obj As Object, ByVal idPropName As String, ByVal namePropName As String) As List(Of IntStringPair)
Dim selectedItems As List(Of IntStringPair) = New List(Of IntStringPair)
Dim fullyQualifiedClassName As String = obj.GetType.FullName
Dim count As Integer = CInt(obj.GetType().GetProperty("Count").GetValue(obj, Nothing))
If (count > 0) Then
For i As Integer = 0 To count - 1
'Rather than hard coding “XCCustomer” below, I want to use something like “obj.GetType.Name”???
Dim Item As IntStringPair = New IntStringPair(CInt(CType(obj, XCCustomers)(i).GetType().GetProperty("CustomerId").GetValue(CType(obj, XCCustomers)(i), Nothing)), _
CStr(CType(obj, XCCustomers)(i).GetType().GetProperty("CustomerName").GetValue(CType(obj, XCCustomers)(i), Nothing)))
selectedItems.Add(Item)
Next
End If
Return selectedItems
End Function
End Class
'+++++++++++++++++++++++++++++++
' Below are the supporting classes if you need to see what else is happening:
Namespace DataLaasXC.Utilities
Public Class IntStringPair
Public Sub New(ByVal _Key As Integer, ByVal _Value As String)
Value = _Value
Key = _Key
End Sub
Public Property Value As String
Public Property Key As Integer
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCCustomer
Public Property CustomerId As Integer
Public Property CustomerName As String
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCCustomers
Inherits List(Of XCCustomer)
Public Sub New()
PopulateCustomersFromDatabase()
End Sub
Public Sub New(ByVal GetEmpty As Boolean)
End Sub
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCEmployee
Public Property EmployeeId As Integer
Public Property EmployeeName As String
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCEmployees
Inherits List(Of XCEmployee)
Public Sub New()
PopulateEmployeesFromDatabase()
End Sub
Public Sub New(ByVal GetEmpty As Boolean)
End Sub
End Class
End Namespace
From MSDN
CType(expression, typename)
. . .
typename : Any expression that is legal
within an As clause in a Dim
statement, that is, the name of any
data type, object, structure, class,
or interface.
This is basically saying you can't use CType dynamically, just statically. i.e. At the point where the code is compiled the compiler needs to know what typename is going to be.
You can't change this at runtime.
Hope this helps.
Since List(Of T) implements the non-generic IList interface, you could change your function declaration to:
Private Function RetrieveIDandName(ByVal obj As System.Collections.IList, ByVal idPropName As String, ByVal namePropName As String) As List(Of IntStringPair)
And then your troublesome line would become (with also using the property name parameters):
Dim Item As IntStringPair = New IntStringPair(CInt(obj(i).GetType().GetProperty(idPropName).GetValue(obj(i), Nothing)), _
CStr(obj(i).GetType().GetProperty(namePropName).GetValue(obj(i), Nothing)))
Of course, you could still have the first parameter by Object, and then attempt to cast to IList, but that's up to you.
ctype is used to convert in object type.
I am working on a ASP.NET MVC2 website. For learning. I am working with the Visual Basic language.
In a view I would like to do this:
<%: Html.EditorForEnumeracion(Function(v) v.combustible%>
So, I created an HtmlHelper extension method:
Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection
Public Module HtmlHelpers
<Extension()> _
Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
'My stuff goes here
End Function
End Module
The problem is that I do not know how to get the instance of the v.combustible object that I pass to the helper. I do not care about the v object. I need to work with the combustible attribute of the v object.
Here and here seems to be how to do this, but I do not understand. Also, I work with Visual Basic, not C#.
I think that I can get the instance of the Enumeracion object through the expression parameter, but I do not understand how.
More info now.
This is my "Vehiculo" class:
Namespace Models.Automovil
Public Class Vehiculo
Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
Public Property marca As String
Public Property modelo As String
Public Property numeroDePuertas As Integer
Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
Public Property potencia As Integer
Public Property fechaPrimeraMatriculacion As DateTime
Public Property version As String
Public Property precio As Decimal
Public Property descripcion As String
End Class
End Namespace
And this is my "Enumeracion" class:
Namespace Models
Public Class Enumeracion
Private bd As New tarificadorasegasaEntities
Private diccionario As New Dictionary(Of String, Integer)
Private _nombre As String
Private _clave As String
Private _valor As Integer
Public ReadOnly Property nombre As String
Get
Return _nombre
End Get
End Property
Public ReadOnly Property clave As String
Get
Return _clave
End Get
End Property
Public ReadOnly Property valor As Integer
Get
Return _valor
End Get
End Property
'More stuff here. Methods.
End Class
End Namespace
The model is the Vehiculo class.
Still not resolving this.
Thanks in advance.
You need to compile the expression into a Func(Of TModel, TValue), then call it on the model:
Dim func = expression.Compile()
Dim value = func(html.ViewData.Model)
Try like this:
<Extension()> _
Public Function EditorForMyCustomClassB(Of Vehiculo, Enumeracion)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of Vehiculo, Enumeracion))) As MvcHtmlString
Dim res = ModelMetadata.FromLambdaExpression(expression, html.ViewData)
Dim e As Enumeracion = DirectCast(res.Model, Enumeracion)
' use e here
End Function