Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to make version independent InfoMessage event handling for SQL Server CE?

I have an input connection as DbConnection.
Also the project includes SQL Server CE 4.0.1 assemblies as private deployment.

The following code:
ByVal connection As DbConnection

With CType(connection, SqlCeConnection)
    RemoveHandler .InfoMessage, AddressOf SqlCeInfoMessageHandler
    AddHandler .InfoMessage, AddressOf SqlCeInfoMessageHandler
End With

raises exception:
[A]System.Data.SqlServerCe.SqlCeConnection cannot be cast to [B]System.Data.SqlServerCe.SqlCeConnection. Type A originates from 'System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' in the context 'Default' at location 'C:\Windows\assembly\GAC_MSIL\System.Data.SqlServerCe\3.5.1.0__89845dcd8080cc91\System.Data.SqlServerCe.dll'. Type B originates from 'System.Data.SqlServerCe, Version=4.0.0.1, Culture=neutral, PublicKeyToken=89845dcd8080cc91' in the context 'Default' at location 'C:\Users\...\System.Data.SqlServerCe.dll'.


DbConnection has no InfoMessage event. So the SqlCeConnection class must be used.
Posted

1 solution

I've solved the task.
VB
Imports System.Reflection

Dim eventInfo As EventInfo = connection.GetType.GetEvent("InfoMessage")

Dim eventType As Type = eventInfo.EventHandlerType

Dim handlerInfo As MethodInfo = Me.GetType.GetMethod("InfoMessageHandler")

Dim handler As [Delegate] = [Delegate].CreateDelegate(eventType, Me, handlerInfo)

eventInfo.RemoveEventHandler(connection, handler)
eventInfo.AddEventHandler(connection, handler)

This code do not require importing the System.Data.SqlServerCe.SqlCeConnection namespace and works with any SQL Server Compact version.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900