Solved

vb.net example of using windows mobile connection manager .net compact

Posted on 2010-08-26
2
2,534 Views
Last Modified: 2013-12-21
I'm trying to make an internet connection using the code below, the return from
Result = ConnMgrEstablishConnectionSync(ConnInfo, ConnHandle, 4000, FinalStatus)
is always -2147024809 which means invalid parameter.

I've spent way too long already trying to fix this,

All help appreciated.



    Private m_lngConnectionHandle As Long

    Private Const CONNMGR_PARAM_GUIDDESTNET As Integer = 1 ' @constdefine guidDestNet field is valid

    Private Const CONNMGR_PARAM_MAXCONNLATENCY As Integer = 8 ' @constdefine MaxConnLatency field is valid

    Private Const CONNMGR_PRIORITY_USERINTERACTIVE As Integer = &H8000

    Public Const CONNMGR_STATUS_UNKNOWN As Integer = &H0 ' @constdefine Unknown status
    Public Const CONNMGR_STATUS_CONNECTED As Integer = &H10 ' @constdefine Connection is up
    Public Const CONNMGR_STATUS_DISCONNECTED As Integer = &H20 ' @constdefine Connection is disconnected
    Public Const CONNMGR_STATUS_CONNECTIONFAILED As Integer = &H21 ' @constdefine Connection failed and cannot not be reestablished
    Public Const CONNMGR_STATUS_CONNECTIONCANCELED As Integer = &H22 ' @constdefine User aborted connection
    Public Const CONNMGR_STATUS_CONNECTIONDISABLED As Integer = &H23 ' @constdefine Connection is ready to connect but disabled
    Public Const CONNMGR_STATUS_NOPATHTODESTINATION As Integer = &H24 ' @constdefine No path could be found to destination
    Public Const CONNMGR_STATUS_WAITINGFORPATH As Integer = &H25 ' @constdefine Waiting for a path to the destination
    Public Const CONNMGR_STATUS_WAITINGFORPHONE As Integer = &H26 ' @constdefine Voice call is in progress
    Public Const CONNMGR_STATUS_WAITINGCONNECTION As Integer = &H40 ' @constdefine Attempting to connect
    Public Const CONNMGR_STATUS_WAITINGFORRESOURCE As Integer = &H41 ' @constdefine Resource is in use by another connection
    Public Const CONNMGR_STATUS_WAITINGFORNETWORK As Integer = &H42 ' @constdefine No path could be found to destination
    Public Const CONNMGR_STATUS_WAITINGDISCONNECTION As Integer = &H80 ' @constdefine Connection is being brought down
    Public Const CONNMGR_STATUS_WAITINGCONNECTIONABORT As Integer = &H81 ' @constdefine Aborting connection attempt

    Public Structure ConnMgr_ConnectionInfo
        Public Size As Int32
        Public Params As Int32
        Public Flags As Int32
        Public Priority As Int32

        Public Exclusive As Boolean
        Public Disabled As Boolean

        Public DestNetGuid As Guid

        Public hWnd As IntPtr
        Public Msg As Int32
        Public lParam As IntPtr

        Public MaxCost As Int32
        Public MinRcvBw As Int32
        Public MaxConnLatency As Int32
    End Structure

    Public Structure CONNMGR_DESTINATION_INFO
        Public guid As Guid
        Public szDescription As String
    End Structure





    '<DllImport("cellcore.dll")> Private Shared Function ConnMgrEnumDestinations(ByVal DestIndex As Integer, ByRef DestInfo As ConnMgr_DestinationInfo) As Integer
    'End Function

    <DllImport("cellcore.dll")> Private Shared Function ConnMgrEstablishConnection(ByRef ConnInfo As ConnMgr_ConnectionInfo, ByRef ConnHandle As Long) As Integer
    End Function

    <DllImport("cellcore.dll")> Private Shared Function ConnMgrEstablishConnectionSync(ByRef ConnInfo As ConnMgr_ConnectionInfo, ByRef ConnHandle As Long, ByVal Timeout As Long, ByRef FinalStatus As Long) As Integer
    End Function

    <DllImport("cellcore.dll")> Private Shared Function ConnMgrConnectionStatus(ByVal hConn As Long, ByRef iStatus As Long) As Integer
    End Function

    <DllImport("cellcore.dll")> Private Shared Function ConnMgrMapURL(ByVal URL As String, ByRef NetworkGuid As Guid, ByRef GuidIndex As Long) As Integer
    End Function

    <DllImport("cellcore.dll")> Private Shared Function ConnMgrReleaseConnection(ByVal ConnHandle As Long, ByVal AllowConnectionToBeCached As Boolean) As Integer
    End Function

    Public Function GetNetworkFromPath(ByVal URL As String) As Guid

        Dim NetworkGuid As New Guid
        Dim GuidIndex As Long
        Dim Result As Integer

        Result = ConnMgrMapURL(URL, NetworkGuid, GuidIndex)

        Return NetworkGuid

    End Function

    Public Sub MakeNetworkConnection()
        Dim ConnInfo As ConnMgr_ConnectionInfo



        Dim ConnHandle As Long
        Dim FinalStatus As Long
        Dim Result As Integer

        Try
            ConnInfo.Size = Marshal.SizeOf(ConnInfo)
            ConnInfo.Params = CONNMGR_PARAM_GUIDDESTNET Or CONNMGR_PARAM_MAXCONNLATENCY
            ConnInfo.Flags = 0
            ConnInfo.MaxConnLatency = 4000
            ConnInfo.Disabled = False
            ConnInfo.Priority = CONNMGR_PRIORITY_USERINTERACTIVE
            ConnInfo.DestNetGuid = New Guid
            ConnInfo.DestNetGuid = GetNetworkFromPath("http://www.google.co.uk")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Try
            Result = ConnMgrEstablishConnectionSync(ConnInfo, ConnHandle, 4000, FinalStatus)
            m_lngConnectionHandle = ConnHandle

            MsgBox("Connection handle = " & ConnHandle.ToString)

        Catch ex As System.NotSupportedException
            MsgBox("NotSupportedError in EstablishConnection")

        Catch ex As Exception
            MsgBox("Error in EstablishConnection (" & ex.Message & ")")

        End Try

    End Sub
0
Comment
Question by:SamSherwin
2 Comments
 
LVL 24

Expert Comment

by:alexey_gusev
Comment Utility
I'd advise using OpennetCF library and their ConnectionManager class - will save you a lot of bothering
0
 
LVL 42

Accepted Solution

by:
sedgwick earned 250 total points
Comment Utility
here's an example in C# http://www.koders.com/csharp/fid6C769602A4F3B13851696D5E4D967FC8BCF2EAD6.aspx?s=combobox.

posted below is the code converted to vb.net:
Imports System.Collections.Generic
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Imports System.Net
Imports System.Diagnostics
Imports agsXMPP
Imports NeboHodimo.IM.UI
Imports System.ComponentModel
Imports System.Threading

Namespace NeboHodimo.WindowsMobile
	Public Class NetworkConnection
		Implements IDisposable
		Private m_uri As String
		Private handle As IntPtr = IntPtr.Zero

		Private Const WELL_KNOWN_URI As String = "www.google.com"

		Public Sub New()
			Me.New(WELL_KNOWN_URI)
		End Sub

		Public Sub New(uri As String)
			m_uri = uri
		End Sub

		Public Property Destination() As String
			Get
				Return m_uri
			End Get
			Set
				If Active Then
					Throw New InvalidOperationException("Destination can't be changed while connection is active.")
				End If
				m_uri = value
			End Set
		End Property

		Public Sub Connect()
			ThreadPool.QueueUserWorkItem(AddressOf ConnectSync, m_uri)
		End Sub

		Private Sub ConnectSync(state As Object)
			FixStatus()
			If handle.Equals(IntPtr.Zero) Then
				Dim destination As Guid = GetDestination(String.Format("http://{0}/", m_uri))
				Try
					Dim status As CONNMGR_STATUS
					handle = EstablishConnectionSync(destination, 30, status)
					If status = CONNMGR_STATUS.CONNECTED Then
						RaiseEvent Connected(Nothing, EventArgs.Empty)
					Else
						RaiseEvent ConnectionFailure(Nothing, EventArgs.Empty)
					End If
				Catch ex As Win32Exception
					Debug.WriteLine(ex.Message)
					Debug.WriteLine(ex.NativeErrorCode)
					RaiseEvent ConnectionFailure(Nothing, EventArgs.Empty)
				End Try
			End If
		End Sub

		Public ReadOnly Property Active() As Boolean
			Get
				FixStatus()
				Return handle <> IntPtr.Zero
			End Get
		End Property

		Private Sub FixStatus()
			If Not handle.Equals(IntPtr.Zero) Then
				Try
					Dim status As CONNMGR_STATUS
					ConnMgrConnectionStatus(handle, status)
					Select Case status
						Case CONNMGR_STATUS.UNKNOWN, CONNMGR_STATUS.DISCONNECTED, CONNMGR_STATUS.CONNECTIONFAILED, CONNMGR_STATUS.CONNECTIONCANCELED, CONNMGR_STATUS.CONNECTIONDISABLED, CONNMGR_STATUS.NOPATHTODESTINATION
							handle = IntPtr.Zero
							Exit Select
					End Select
				Catch ex As Exception
					Debug.WriteLine(ex)
					Debug.WriteLine(ex.StackTrace)
					handle = IntPtr.Zero
				End Try
			End If
		End Sub

		Public Sub Disconnect()
			If Not handle.Equals(IntPtr.Zero) Then
				Try
					ReleaseConnection(handle)
					RaiseEvent Disconnected(Nothing, EventArgs.Empty)
				Catch ex As Win32Exception
					Debug.WriteLine(ex.Message)
					Debug.WriteLine(ex.NativeErrorCode)
				Finally
					handle = IntPtr.Zero
				End Try
			End If
		End Sub

		Public Sub Dispose() Implements IDisposable.Dispose
			Disconnect()
		End Sub

		Public Event Connected As EventHandler
		Public Event Disconnected As EventHandler
		Public Event ConnectionFailure As EventHandler

		#Region "P/Invoke enums"
		<Flags> _
		Private Enum CONNMGR_PARAM As Integer
			GUIDDESTNET = &H1
			MAXCOST = &H2
			MINRCVBW = &H4
			MAXCONNLATENCY = &H8
		End Enum

		<Flags> _
		Private Enum CONNMGR_FLAG As Integer
			PROXY_HTTP = &H1
			PROXY_WAP = &H2
			PROXY_SOCKS4 = &H4
			PROXY_SOCKS5 = &H8
		End Enum

		<Flags> _
		Private Enum CONNMGR_PRIORITY As Integer
			VOICE = &H20000
			USERINTERACTIVE = &H8000
			USERBACKGROUND = &H2000
			USERIDLE = &H800
			HIPRIBKGND = &H200
			IDLEBKGND = &H80
			EXTERNALINTERACTIVE = &H20
			LOWBKGND = &H8
			CACHED = &H2
		End Enum

		Private Enum CONNMGR_STATUS As Long
			UNKNOWN = &H0
			CONNECTED = &H10
			DISCONNECTED = &H20
			CONNECTIONFAILED = &H21
			CONNECTIONCANCELED = &H22
			CONNECTIONDISABLED = &H23
			NOPATHTODESTINATION = &H24
			WAITINGFORPATH = &H25
			WAITINGFORPHONE = &H26
			WAITINGCONNECTION = &H40
			WAITINGFORRESOURCE = &H41
			WAITINGFORNETWORK = &H42
			WAITINGDISCONNECTION = &H80
			WAITINGCONNECTIONABORT = &H81
		End Enum

		Private Enum CONNMGR_CONNECTION_TYPE
			CM_CONNTYPE_UNKNOWN
			'Unknown connection. 
			CM_CONNTYPE_CELLULAR
			'Cellular connection. 
			CM_CONNTYPE_NIC
			'Network interface card (NIC) connection. 
			CM_CONNTYPE_BLUETOOTH
			'Bluetooth connection. 
			CM_CONNTYPE_UNIMODEM
			'Unimodem connection. 
			CM_CONNTYPE_VPN
			'Virtual private network (VPN) connection. 
			CM_CONNTYPE_PROXY
			'Proxy connection. For more proxy constants, see Connection Manager Proxy Flag Constants. 
			CM_CONNTYPE_PC
			'PC connection. 
		End Enum
		#End Region

		#Region "P/Invoke structures"
		Private Class CONNMGR_CONNECTIONINFO
			Public cbSize As Integer = &H40
			Public dwParams As CONNMGR_PARAM = 0
			Public dwFlags As CONNMGR_FLAG = 0
			Public dwPriority As CONNMGR_PRIORITY = 0
			Public bExclusive As Integer = 0
			Public bDisabled As Integer = 0
			Public guidDestNet As Guid = Guid.Empty
			Public hWnd As IntPtr = IntPtr.Zero
			Public uMsg As Integer = 0
			Public lParam As Integer = 0
			Public ulMaxCost As Integer = 0
			Public ulMinRcvBw As Integer = 0
			Public ulMaxConnLatency As Integer = 0
		End Class

		Private Class CONNMGR_DESTINATION_INFO
			Public guid As Guid = Guid.Empty
			<MarshalAs(UnmanagedType.ByValTStr, SizeConst := 129)> _
			Public szDescription As String
		End Class

		#Pragma warning disable 0649
		Private Class CONNMGR_CONNECTION_DETAILED_STATUS
			Public pNext As CONNMGR_CONNECTION_DETAILED_STATUS
			Public dwVer As Integer
			Public dwParams As Integer
			Public dwType As CONNMGR_CONNECTION_TYPE
			Public dwSubtype As Integer
			Public dwFlags As Integer
			Public dwSecure As Integer
			Public guidDestNet As Guid
			Public guidSourceNet As Guid
			<MarshalAs(UnmanagedType.ByValTStr, SizeConst := 129)> _
			Public szDescription As String
			<MarshalAs(UnmanagedType.ByValTStr, SizeConst := 129)> _
			Public szAdapterName As String
			Public dwConnectionStatus As Integer
			Public LastConnectTime As DateTime
			Public dwSignalQuality As Integer
			Public pIPAddr As IntPtr
		End Class
		#Pragma warning restore 0649
		#End Region

		#Region "P/Invoke functions"
		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrEnumDestinations(nIndex As Integer, ByRef destinationInfo As CONNMGR_DESTINATION_INFO) As Integer
		End Function

		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrMapURL(url As String, ByRef guid As Guid, nIndex As IntPtr) As Integer
		End Function

		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrEstablishConnection(pConnInfo As CONNMGR_CONNECTIONINFO, hConnection As IntPtr) As Integer
		End Function

		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrEstablishConnectionSync(pConnInfo As CONNMGR_CONNECTIONINFO, hConn As IntPtr, timeout As UInteger, pdwStatus As CONNMGR_STATUS) As Integer
		End Function

		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrReleaseConnection(hConnection As IntPtr, bCache As Integer) As Integer
		End Function

		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrConnectionStatus(hConnection As IntPtr, pdwStatus As CONNMGR_STATUS) As Integer
		End Function

		<DllImport("cellcore.dll", CharSet := CharSet.Unicode, SetLastError := True)> _
		Private Shared Function ConnMgrQueryDetailedStatus(pStatusBuffer As CONNMGR_CONNECTION_DETAILED_STATUS, ByRef pcbBufferSize As Integer) As Integer
		End Function
		#End Region

		''' <summary>Get destination GUID</summary>
		''' <param name="nIndex">Connection index</param>
		Private Shared Function GetDestination(nIndex As Integer) As Guid
			Dim connMgrDestinationInfo As New CONNMGR_DESTINATION_INFO()
			Dim result As Integer = ConnMgrEnumDestinations(nIndex, connMgrDestinationInfo)
			If result <> 0 Then
				Throw New Win32Exception(result, "ConnMgrEnumDestinations")
			End If

			Return connMgrDestinationInfo.guid
		End Function

		''' <summary>Get destination GUID</summary>
		''' <param name="url">URL belonging to the destination</param>
		Private Shared Function GetDestination(url As String) As Guid
			Dim guid__1 As Guid = Guid.Empty
			Dim result As Integer = ConnMgrMapURL(url, guid__1, IntPtr.Zero)
			If result <> 0 Then
				Throw New Win32Exception(result, "ConnMgrMapURL")
			End If
			Return guid__1
		End Function

		Private Shared Function EstablishConnection(destination As Guid) As IntPtr
			Dim connectionInfo As New CONNMGR_CONNECTIONINFO()
			connectionInfo.dwParams = CONNMGR_PARAM.GUIDDESTNET
			connectionInfo.dwPriority = CONNMGR_PRIORITY.USERINTERACTIVE
			connectionInfo.guidDestNet = destination
			Dim hConnection As IntPtr
			Dim result As Integer = ConnMgrEstablishConnection(connectionInfo, hConnection)
			If result <> 0 Then
				Throw New Win32Exception(result, "ConnMgrEstablishConnection")
			End If
			Return hConnection
		End Function

		Private Shared Function EstablishConnectionSync(destination As Guid, timeout As Double, status As CONNMGR_STATUS) As IntPtr
			Dim connectionInfo As New CONNMGR_CONNECTIONINFO()
			connectionInfo.dwParams = CONNMGR_PARAM.GUIDDESTNET
			connectionInfo.dwPriority = CONNMGR_PRIORITY.USERINTERACTIVE
			connectionInfo.guidDestNet = destination
			Dim hConnection As IntPtr
			Dim tout As UInteger = CUInt(Math.Truncate(timeout * 1000 + 1))
			Dim result As Integer = ConnMgrEstablishConnectionSync(connectionInfo, hConnection, tout, status)
			If result <> 0 Then
				Throw New Win32Exception(result, "ConnMgrEstablishConnectionSync")
			End If
			Return hConnection
		End Function

		Private Shared Sub ReleaseConnection(hConnection As IntPtr)
			Dim result As Integer = ConnMgrReleaseConnection(hConnection, 0)
			If result <> 0 Then
				Throw New Win32Exception(result, "ConnMgrReleaseConnection()")
			End If
		End Sub
	End Class
End Namespace

Open in new window

0

Featured Post

Are your corporate email signatures appalling?

Is it scary how unprofessional your email signatures look? Do users create their own terrible designs and give themselves stupid job titles? You can make this a lot easier for yourself by choosing an email signature management solution from Exclaimer today.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
nmap scanner? 7 76
address book on outlook 2016 mac 7 45
pdf to word 13 54
Tabcontrol Caption? 1 21
Several part series to implement Internet Explorer 11 Enterprise Mode
Recently Microsoft released a brand new function called CONCAT. It's supposed to replace its predecessor CONCATENATE. But how does it work? And what's new? In this article, we take a closer look at all of this - we even included an exercise file for…
Windows 8 came with a dramatically different user interface known as Metro. Notably missing from that interface was a Start button and Start Menu. Microsoft responded to negative user feedback of the Metro interface, bringing back the Start button a…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now