locked
[Bluetooth RFComm] SocketStream.ConnectAsync(HostName,String) – SystemException Element Not Found

    Question

  • I am trying to create a Proof of Concept Bluetooth rfcomm client using the rfcomm chat example posted in the Dev Center (sorry can not post a link, it says my account is not verified) as a reference.  The application is running on a Windows 8.1 pro tablet and is connecting to a generic rfcomm Bluetooth server written in python.  From my client, I am able to find the server and get the attributes but when I try to connect the StreamSocket I get a “SystemException: Element not found (Exception from HRESULT: 0x80070490)” exception.  Further down in the exception it also says:  “System.NullReferenceException: Object reference not set to an instance of an object”

    Here is my code:

    private async void runButton_Click(object sender, RoutedEventArgs e)
            {
    
                serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(rfcommServiceUuid)));
                if (serviceInfoCollection.Count > 0)
                {
                    List<string> items = new List<string>();
                    var serviceInfo = serviceInfoCollection.First();
    
                    NotifyStatus("---Found " + serviceInfo.Name + ":  " + serviceInfo.Id + "\n");
                    try
                    {
                        service = await RfcommDeviceService.FromIdAsync(serviceInfo.Id);
                    }
                    catch (Exception ex)
                    {
                        NotifyError(ex); 
                    }
                   
                    if (service == null)
                    {
                        NotifyStatus("Error:  Access denied, application did not give permission");
                        return;
                    }
                    var attributes = await service.GetSdpRawAttributesAsync();
                    if (!attributes.ContainsKey(sdpServiceNameAttributeId))
                    {
                        NotifyStatus("Error:  Service is not advertising the Service Name attribute");
                        return;
                    }
                    var attributeReader = DataReader.FromBuffer(attributes[sdpServiceNameAttributeId]);
                    var attributeType = attributeReader.ReadByte();
                    if (attributeType != sdpServiceNameAttributeType)
                    {
                        NotifyStatus("Error:  Service is using an unexpected format for the Service Name Attribute");
                        return;
                    }
                    var serviceNameLength = attributeReader.ReadByte();
                    attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8;
                    var serviceName = attributeReader.ReadString(serviceNameLength);
                    NotifyStatus("Service Name:  " + serviceName + "\n");
    
                        try
                        {
                            lock (this)
                            {
                                socket = new StreamSocket();
                            }
                            NotifyStatus("3 " + service.ConnectionHostName + " - " + service.ConnectionServiceName +  " - " +service.ProtectionLevel+"\n");
                            await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
                            writer = new DataWriter(socket.OutputStream);
                        }
                        catch (Exception ex)
                        {
                            NotifyError(ex);
                        }
    
                    try
                    {
                        String sendingStr = "Hello from Windows 8.....";
                        writer.WriteUInt32((uint)sendingStr.Length);
                        writer.WriteString(sendingStr);
                        await writer.StoreAsync();
                    }
                    catch(Exception ex)
                    {
                        NotifyError(ex); 
                    }
                }
                else
                {
                    NotifyStatus("No services found");
                }
    
                NotifyStatus("This is the end of the list");
            }
    
            private void disconnect()
            {
                if (writer != null)
                {
                    writer.DetachStream();
                    writer = null;
                }
    
                lock (this)
                {
                    if (socket != null)
                    {
                        socket.Dispose();
                        socket = null;
                    }
    
                }
            }
    

    The exception is thrown at this line:  await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);

    I believe my permissions are set correctly:

      <Capabilities>
        <m2:DeviceCapability Name="bluetooth.rfcomm">
          <m2:Device Id="any">
            <m2:Function Type="serviceId:34B1CF4D-1069-4AD6-89B6-E161D79BE4D8"/>
          </m2:Device>
        </m2:DeviceCapability>
      </Capabilities>

     

    At this point I am kind of stuck on what to look at.  Any help or suggestion would be appreciated.

    Thanks,

    Tuesday, May 6, 2014 6:58 PM

All replies

  • If you have all three of these things:

    socket

    service.ConnectionHostName

    service.ConnectionServiceName

    You should not be getting an NRE.  Is there any chance you can share the app with us?


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Wednesday, May 7, 2014 1:39 PM
    Moderator
  • Sure, I can zip up the entire project and e-mail it directly to you if you could please send me an address to send it too.  I believe you should be able to get my e-mail address from my profile, if not what would be the best way to send you the project.

    Just as a FYI:  In the code I have this line:  NotifyStatus("3 " + service.ConnectionHostName + " - " + service.ConnectionServiceName +  " - " +service.ProtectionLevel+"\n");  and just before I get the exception printed to the screen, I see this:  "3 (0C:88:FD:E5:39:3A) - 1 - BluetoothEncryptionWithAuthentication" so I am pretty sure I have the service.ConnectionHostName and the service.ConnectionServiceName correctly.  Could that be something wrong with the way I am getting my socket prior to trying to connect?

    Thanks,

    Wednesday, May 7, 2014 2:18 PM
  • One other comment, I figured out that the Null Reference exception is coming later in my code when I try to access the DataWriter in this block of code:

     try
                    {
                        String sendingStr = "Hello from Windows 8.....";
                        writer.WriteUInt32((uint)sendingStr.Length);
                        writer.WriteString(sendingStr);
                        await writer.StoreAsync();
                    }
                    catch(Exception ex)
                    {
                        NotifyError(ex); 
                    }

    This is caused by the DataWriter never being initiated because of the exception with the StreamSocket ConnectAsync call in this block of code:

      try
                        {
                            lock (this)
                            {
                                socket = new StreamSocket();
                            }
                            NotifyStatus("3 " + service.ConnectionHostName + " - " + service.ConnectionServiceName +  " - " +service.ProtectionLevel+"\n");
                            await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
                            writer = new DataWriter(socket.OutputStream);
                        }
                        catch (Exception ex)
                        {
                            NotifyError(ex);
                        }

    So I think it may be safe to ignore the Null Reference at this point and my issue is coming from the System Exception:  Element not found exception when calling the ConnectAsync method.  Sorry for the confusion in my initial post, I am new to C# and Windows development, I come from a Java/C background.

    Wednesday, May 7, 2014 4:17 PM
  • Can you post your code to OneDrive and post a link here? 

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Wednesday, May 7, 2014 6:12 PM
    Moderator
  • I think I did it correctly (never used OneDrive before), if not please let me know:  https://onedrive.live.com/redir?resid=9AB1B05028A34CFF!108&authkey=!AMwI_j3zW3hu6E4&ithint=file%2c.zip

    I have been trying to find the issue so the code has changed a little from what I posted earlier but I still get the same issue.

    Thanks,

    Wednesday, May 7, 2014 7:00 PM
  • I was wondering if you have had a chance to look at the code that I posted last week and if you had any suggestions.

    Thanks,

    Monday, May 12, 2014 3:07 PM
  • The device could not be found if the Runtime Broker process is unable to locate the SDP record of the device. Can you disable firewall and try again?

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

    Regards,
    Jacky Wu
    Microsoft Online Community Support

    Monday, August 4, 2014 7:18 AM