Example #1
0
        private Guid GetRecordService(ServiceRecord m_record)
        {
            ServiceAttribute attr    = m_record.GetAttributeById(UniversalAttributeId.ServiceClassIdList);
            ServiceElement   element = (ServiceElement)attr.Value.GetValueAsElementList()[0];
            Guid             uuid128 = (Guid)element.Value;

            return(uuid128);
        }
Example #2
0
        public ServiceElement[] GetValueAsElementArray()
        {
            IList_ServiceElement list = GetValueAsElementList();

            ServiceElement[] arr = new ServiceElement[list.Count];
            GetValueAsElementList().CopyTo(arr, 0);
            return(arr);
        }
        /// <exclude/>
        protected virtual int CreateAttrId(ServiceAttributeId attrId, byte[] buf, int offset)
        {
            ServiceElement dummyElement
                = new ServiceElement(
                      ElementType.UInt16, unchecked ((UInt16)attrId));

            return(CreateElement(dummyElement, buf, offset));
        }
        private void WriteInt64(ServiceElement element, Int64 value, byte[] buf, ref int offset, out int totalLength)
        {
            Int64 host64 = value;
            Int64 net64  = IPAddress.HostToNetworkOrder(host64);

            byte[] valueBytes = BitConverter.GetBytes(net64);
            WriteFixedLength(element, valueBytes, buf, ref offset, out totalLength);
        }
        protected virtual void WriteFixedLength(ServiceElement element, byte[] valueBytes, byte[] buf, ref int offset, out int totalLength)
        {
            int headerLen = WriteHeaderFixedLength(element.ElementTypeDescriptor, valueBytes.Length, buf, offset, out totalLength);

            offset += headerLen;
            VerifyWriteSpaceRemaining(valueBytes.Length, buf, offset);
            valueBytes.CopyTo(buf, offset);
            System.Diagnostics.Debug.Assert(totalLength == headerLen + valueBytes.Length);
        }
        protected virtual void WriteVariableLength(ServiceElement element, byte[] valueBytes, byte[] buf, ref int offset, out int totalLength)
        {
            HeaderWriteState headerState;
            int curLen;

            curLen  = MakeVariableLengthHeader(buf, offset, element.ElementTypeDescriptor, out headerState);
            offset += curLen;
            VerifyWriteSpaceRemaining(valueBytes.Length, buf, offset);
            valueBytes.CopyTo(buf, offset);//write
            offset += valueBytes.Length;
            CompleteHeaderWrite(headerState, buf, offset, out totalLength);
        }
Example #7
0
        public String GetMultiLanguageStringAttributeById(ServiceAttributeId id, LanguageBaseItem language)
        {
            if (language == null)
            {
                throw new ArgumentNullException("language");
            }
            ServiceAttributeId actualId = CreateLanguageBasedAttributeId(id, language.AttributeIdBase);
            ServiceAttribute   attr     = GetAttributeById(actualId);
            ServiceElement     element  = attr.Value;
            // (No need to check that element is of type TextString, that's handled inside the following).
            String str = element.GetValueAsString(language);

            return(str);
        }
Example #8
0
        /// <summary>
        /// Add a custom attribute of simple type.
        /// </summary>
        /// -
        /// <remarks>
        /// <para>If the <paramref name="elementType"/> is a numerical type
        /// then this is equivalent to using
        /// <see cref="M:InTheHand.Net.Bluetooth.ServiceElement.CreateNumericalServiceElement(InTheHand.Net.Bluetooth.ElementType,System.Object)"/>
        /// otherwise the value is used directly in creating the
        /// <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.
        /// </para>
        /// </remarks>
        /// -
        /// <param name="id">The Attribute Id as a <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
        /// <param name="elementType">The type of the element as an <see cref="T:InTheHand.Net.Bluetooth.ElementType"/>.</param>
        /// <param name="value">The value for the new element.</param>
        public void AddCustomAttribute(ServiceAttributeId id, ElementType elementType, object value)
        {
            ServiceElement        e;
            ElementTypeDescriptor etd = ServiceRecordParser.GetEtdForType(elementType);

            if ((etd == ElementTypeDescriptor.UnsignedInteger ||
                 etd == ElementTypeDescriptor.TwosComplementInteger))
            {
                e = ServiceElement.CreateNumericalServiceElement(elementType, value);
            }
            else
            {
                e = new ServiceElement(elementType, value);
            }
            this.AddCustomAttribute(new ServiceAttribute(id, e));
        }
Example #9
0
        /// <summary>
        /// Get the enum-like class containing the Service Attribute Id definitions
        /// for the type of the Service Class contained in the given
        /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList"/>
        /// (type <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.Uuid"/>) data element.
        /// </summary>
        /// -
        /// <param name="idElement">A <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>
        /// of 'UUID' type containing the Service Class to search for.
        /// </param>
        /// -
        /// <returns>
        /// A <see cref="T:System.Type"/> object representing the enum-like class
        /// holding the Attribute Id definitions, or null if the Service Class is
        /// unknown or the element is not of <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.Uuid"/>
        /// type.
        /// </returns>
        /// -
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="idElement"/> is null.
        /// </exception>
        protected virtual Type GetAttributeIdEnumType(ServiceElement idElement)
        {
            if (idElement == null)
            {
                throw new ArgumentNullException("idElement");
            }
            //
            if (idElement.ElementTypeDescriptor != ElementTypeDescriptor.Uuid)
            {
                return(null);
            }
            Guid uuid = idElement.GetValueAsUuid();

            //
            return(GetAttributeIdEnumType(uuid));
        }
Example #10
0
        private static ServiceElement ServiceElementFromUuid(object classRaw)
        {
            ServiceElement tmp = null;

            UInt32 classU32 = 99;
            bool   writeIntegral;

            // First check raw type, and also if u16/u32 inside Guid.
            // If Guid write it, otherwise handle all integral value.
            if (classRaw is Guid)
            {
                Guid uuid128 = (Guid)classRaw;
                if (ServiceRecordUtilities.IsUuid32Value(uuid128))
                {
                    classU32      = ServiceRecordUtilities.GetAsUuid32Value(uuid128);
                    writeIntegral = true;
                }
                else
                {
                    tmp           = new ServiceElement(ElementType.Uuid128, uuid128);
                    writeIntegral = false;
                }
            }
            else
            {
                System.Diagnostics.Debug.Assert(classRaw != null,
                                                "Unexpected ServiceClassId value: null");
                System.Diagnostics.Debug.Assert(classRaw is Int32,
                                                "Unexpected ServiceClassId type: " + classRaw.GetType().Name);
                Int32 i32 = (Int32)classRaw;
                classU32      = unchecked ((UInt32)i32);
                writeIntegral = true;
            }
            if (writeIntegral)
            {
                try {
                    UInt16 u16 = Convert.ToUInt16(classU32);
                    Debug.Assert(classU32 <= UInt16.MaxValue, "NOT replace the throw, LTE");
                    tmp = new ServiceElement(ElementType.Uuid16, u16);
                } catch (OverflowException) {
                    Debug.Assert(classU32 > UInt16.MaxValue, "NOT replace the throw, GT");
                    tmp = new ServiceElement(ElementType.Uuid32, classU32);
                }
            }

            return(tmp);
        }
Example #11
0
        //--------------------------------------------------------------
        private static ServiceRecord CreateRecord()
        {
            List_ServiceAttribute attrs = new List_ServiceAttribute();
            ServiceElement        element;

            //
            element = new ServiceElement(ElementType.ElementSequence,
                                         new ServiceElement(ElementType.Uuid128, Guid.Empty));
            attrs.Add(new ServiceAttribute(UniversalAttributeId.ServiceClassIdList, element));
            //
            element = ServiceRecordHelper.CreateRfcommProtocolDescriptorList();
            attrs.Add(new ServiceAttribute(UniversalAttributeId.ProtocolDescriptorList, element));
            //
            ServiceRecord record = new ServiceRecord(attrs);

            return(record);
        }
Example #12
0
        private static void DumpString(System.IO.TextWriter writer, int depth, ServiceElement element, LanguageBaseItem langBase)
        {
            if (langBase != null)
            {
                try {
                    String value = element.GetValueAsString(langBase);
                    writer.WriteLine("{0}: [{1}] '{2}'", element.ElementType, langBase.NaturalLanguage, value);
                } catch (NotSupportedException ex) {
                    System.Diagnostics.Debug.Assert(ex.Message != null);
                    System.Diagnostics.Debug.Assert(ex.Message.StartsWith("Unrecognized character encoding"));
                    writer.WriteLine("{0}: Failure: {1}", element.ElementType, ex.Message);
                }
            }
            else
            {
                try {
                    String hack = element.GetValueAsStringUtf8();
                    if (hack.IndexOf((char)0) != -1)
                    {
                        throw new
#if !WinCE
                              System.Text.DecoderFallbackException
#else
                              // NETCF doesn't support DecoderFallbackException this what the docs say.
                              ArgumentException
#endif
                                  ("EEEEE contains nulls!  UTF-16?!");
                    }
                    writer.WriteLine("{0} (guessing UTF-8): '{1}'", element.ElementType, hack);
                } catch (
                    // TODO ! What exception thrown by UTF8Encoding on NETCF?
#if !WinCE
                    System.Text.DecoderFallbackException
#else
                    // NETCF doesn't support DecoderFallbackException this what the docs say.
                    ArgumentException
#endif
                    ) {
                    writer.WriteLine("{0} (Unknown/bad encoding):", element.ElementType);
                    var arr = (byte[])element.Value;
                    var str = BitConverter.ToString(arr);
                    WritePrefix(writer, depth); // On another line.
                    writer.WriteLine("Length: {0}, >>{1}<<", arr.Length, str);
                }//try
            }
        }
Example #13
0
 private static void DumpRawElement(System.IO.TextWriter writer, int depth, ServiceElement elem)
 {
     WritePrefix(writer, depth);
     if (elem.ElementType == ElementType.ElementSequence ||
         elem.ElementType == ElementType.ElementAlternative)
     {
         writer.WriteLine("{0}", elem.ElementType);
         foreach (ServiceElement element in elem.GetValueAsElementList())
         {
             DumpRawElement(writer, depth + 1, element);
         }
     }
     else if (elem.ElementType == ElementType.Nil)
     {
         writer.WriteLine("Nil:");
     }
     else if (elem.ElementType == ElementType.TextString ||
              elem.ElementType == ElementType.Boolean ||
              elem.ElementType == ElementType.Url)
     {
         // Non-numeric types
         writer.WriteLine("{0}: {1}", elem.ElementType, elem.Value);
     }
     else if (elem.ElementType == ElementType.Uuid128)
     {
         writer.WriteLine("{0}: {1}", elem.ElementType, elem.Value);
     }
     else if (elem.ElementType == ElementType.UInt128 ||
              elem.ElementType == ElementType.Int128)
     {
         string valueText = BitConverter.ToString((byte[])elem.Value);
         writer.WriteLine("{0}: {1}", elem.ElementType, valueText);
     }
     else
     {
         writer.WriteLine("{0}: 0x{1:X}", elem.ElementType, elem.Value);
         //{catch(?FOrmatExptn){
         //   writer.WriteLine("{0}: 0x{1}", elem.Type, elem.Value);
         //}
     }
 }
Example #14
0
        /// <summary>
        /// Get a list of enum-like classes containing Service Attribute Id definitions
        /// for the type of the Service Class contained in the given Service Record.
        /// </summary>
        /// -
        /// <param name="record">A <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
        /// whose <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList"/>
        /// element will be retrieved, and its Service Class Id will used
        /// for the lookup.
        /// </param>
        /// -
        /// <returns>
        /// An array of <see cref="T:System.Type"/> each of which is a enum-like class
        /// which defines the set of Service Attribute IDs used by a particular
        /// Service Class e.g. ObjectPushProfile.
        /// An empty array will be returned if none of the Service Classes
        /// are known, or the record contains no
        /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList"/>
        /// attribute, or it is invalid.
        /// <note>Currently only the first Service Class Id is looked-up.</note>
        /// </returns>
        /// -
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="record"/> is null.
        /// </exception>
        public Type[] GetAttributeIdEnumTypes(ServiceRecord record)
        {
            if (record == null)
            {
                throw new ArgumentNullException("record");
            }
            //
            ServiceAttribute attr;

            try {
                attr = record.GetAttributeById(UniversalAttributeId.ServiceClassIdList);
            } catch (
#if V1
                ArgumentException
#else
                System.Collections.Generic.KeyNotFoundException
#endif
                ex) {
                System.Diagnostics.Debug.Assert(ex.Message == ServiceRecord.ErrorMsgNoAttributeWithId);
                goto InvalidRecord;
            }
            ServiceElement element = attr.Value;
            if (element.ElementType != ElementType.ElementSequence)
            {
                goto InvalidRecord;
            }
            ServiceElement[] idElements = element.GetValueAsElementArray();
            //TODO ((GetServiceClassSpecificAttributeIdEnumDefiningType--foreach (ServiceElement curIdElem in idElements) {))
            if (idElements.Length != 0)
            {
                ServiceElement curIdElem = idElements[0];
                Type           enumType  = GetAttributeIdEnumType(curIdElem);
                if (enumType != null)
                {
                    return(new Type[] { enumType });
                }
            }//else fall through...
            // None-matched, or invalid attribute format etc.
InvalidRecord:
            return(new Type[0]);
        }
Example #15
0
        //--------------------
        //

        /// <summary>
        /// Gets the list of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>
        /// items in the service record.
        /// </summary>
        /// -
        /// <param name="elementSequence">
        /// A <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> holding the
        /// data from the
        /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>
        /// attribute.
        /// </param>
        /// -
        /// <returns>
        /// An array of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.
        /// An array length zero is returned if the service record contains no such attribute.
        /// </returns>
        /// -
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="elementSequence"/> is not of type
        /// <see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementSequence"/>.
        /// </exception>
        /// <exception cref="T:System.Net.ProtocolViolationException">
        /// The element sequence contains incorrectly formatted or invalid content,
        /// for example it contains the wrong element data types, or doesn't contain
        /// the elements in groups of three as required.
        /// </exception>
        public static LanguageBaseItem[] ParseListFromElementSequence(ServiceElement elementSequence)
        {
            if (elementSequence.ElementType != ElementType.ElementSequence)
            {
                throw new ArgumentException(ErrorMsgLangBaseListParseNotSequence);
            }
#if V1
            IList elementList = elementSequence.GetValueAsElementList();
#else
            IList <ServiceElement> elementList = elementSequence.GetValueAsElementList();
#endif
            int       numElements     = elementList.Count;
            const int ElementsPerItem = 3;
            if (numElements == 0 || (numElements % ElementsPerItem) != 0)
            {
                throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseNotInThrees);
            }
            int numItems             = numElements / ElementsPerItem;
            LanguageBaseItem[] items = new LanguageBaseItem[numItems];
            for (int i = 0; i < numItems; ++i)
            {
                // Casts are for the non-Generic version.
                ServiceElement e1Lang   = (ServiceElement)elementList[i * ElementsPerItem];
                ServiceElement e2EncId  = (ServiceElement)elementList[i * ElementsPerItem + 1];
                ServiceElement e3BaseId = (ServiceElement)elementList[i * ElementsPerItem + 2];
                if (e1Lang.ElementType != ElementType.UInt16 || e2EncId.ElementType != ElementType.UInt16 || e3BaseId.ElementType != ElementType.UInt16)
                {
                    throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseNotU16);
                }
                if ((UInt16)e3BaseId.Value == 0)
                {
                    throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseBaseInvalid);
                }
                LanguageBaseItem item = new LanguageBaseItem(
                    (UInt16)e1Lang.Value, (UInt16)e2EncId.Value, (UInt16)e3BaseId.Value);
                items[i] = item;
            }
            return(items);
        }
 private void WriteVariableLength(ServiceElement element, byte[] valueBytes, byte[] buf, ref int offset, out int totalLength)
 {
     HeaderWriteState headerState;
     int curLen;
     curLen = MakeVariableLengthHeader(buf, offset, element.ElementTypeDescriptor, out headerState);
     offset += curLen;
     VerifyWriteSpaceRemaining(valueBytes.Length, buf, offset);
     valueBytes.CopyTo(buf, offset);//write
     offset += valueBytes.Length;
     CompleteHeaderWrite(headerState, buf, offset, out totalLength);
 }
 private static ServiceElement CreateRfcommProtocolDescriptorListWithUpperLayers(params ServiceElement[] upperLayers)
 {
     IList_ServiceElement baseChildren = new List_ServiceElement();
     baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.L2Cap));
     baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.Rfcomm, 
         new ServiceElement(ElementType.UInt8, (byte)0)));
     foreach (ServiceElement nextLayer in upperLayers) {
         if (nextLayer.ElementType != ElementType.ElementSequence) {
             throw new ArgumentException("Each layer in a ProtocolDescriptorList must be an ElementSequence.");
         }
         baseChildren.Add(nextLayer);
     }//for
     ServiceElement baseElement = new ServiceElement(ElementType.ElementSequence, baseChildren);
     return baseElement;
 }
 private void WriteUInt32(ServiceElement element, UInt32 value, byte[] buf, ref int offset, out int totalLength)
 {
     Int32 valueS = unchecked((Int32)value);
     WriteInt32(element, valueS, buf, ref  offset, out  totalLength);
 }
Example #19
0
        //--------------------
        //

        /// <summary>
        /// Gets the list of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>
        /// items in the service record.
        /// </summary>
        /// -
        /// <param name="elementSequence">
        /// A <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> holding the 
        /// data from the 
        /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.LanguageBaseAttributeIdList"/>
        /// attribute.
        /// </param>
        /// -
        /// <returns>
        /// An array of <see cref="T:InTheHand.Net.Bluetooth.LanguageBaseItem"/>.  
        /// An array length zero is returned if the service record contains no such attribute.
        /// </returns>
        /// -
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="elementSequence"/> is not of type 
        /// <see cref="F:InTheHand.Net.Bluetooth.ElementType.ElementSequence"/>.
        /// </exception>
        /// <exception cref="T:System.Net.ProtocolViolationException">
        /// The element sequence contains incorrectly formatted or invalid content,
        /// for example it contains the wrong element data types, or doesn't contain
        /// the elements in groups of three as required.
        /// </exception>
        public static LanguageBaseItem[] ParseListFromElementSequence(ServiceElement elementSequence)
        {
            if (elementSequence.ElementType != ElementType.ElementSequence) {
                throw new ArgumentException(ErrorMsgLangBaseListParseNotSequence);
            }
#if V1
            IList  elementList = elementSequence.GetValueAsElementList();
#else
            IList<ServiceElement> elementList = elementSequence.GetValueAsElementList();
#endif
            int numElements = elementList.Count;
            const int ElementsPerItem = 3;
            if (numElements == 0 || (numElements % ElementsPerItem) != 0) {
                throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseNotInThrees);
            }
            int numItems = numElements / ElementsPerItem;
            LanguageBaseItem[] items = new LanguageBaseItem[numItems];
            for (int i = 0; i < numItems; ++i) {
                // Casts are for the non-Generic version.
                ServiceElement e1Lang = (ServiceElement)elementList[i * ElementsPerItem];
                ServiceElement e2EncId = (ServiceElement)elementList[i * ElementsPerItem + 1];
                ServiceElement e3BaseId = (ServiceElement)elementList[i * ElementsPerItem + 2];
                if (e1Lang.ElementType != ElementType.UInt16 || e2EncId.ElementType != ElementType.UInt16 || e3BaseId.ElementType != ElementType.UInt16) {
                    throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseNotU16);
                }
                if ((UInt16)e3BaseId.Value == 0) {
                    throw new System.Net.ProtocolViolationException(ErrorMsgLangBaseListParseBaseInvalid);
                }
                LanguageBaseItem item = new LanguageBaseItem(
                        (UInt16)e1Lang.Value, (UInt16)e2EncId.Value, (UInt16)e3BaseId.Value);
                items[i] = item;
            }
            return items;
        }
Example #20
0
        //--------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> class.
        /// </summary>
        public ServiceAttribute(ServiceAttributeId id, ServiceElement value)
        {
            m_id = id;
            m_element = value;
        }
Example #21
0
 [CLSCompliant(false)] // instead use .ctor(ServiceAttributeId,AttributeValue).
 public ServiceAttribute(UInt16 id, ServiceElement value)
     : this(unchecked ((ServiceAttributeId)(Int16)id), value)
 {
 }
Example #22
0
 private static void DumpElement(System.IO.TextWriter writer, int depth, ServiceElement elem)
 {
     WritePrefix(writer, depth);
     if (elem.ElementType == ElementType.ElementSequence || elem.ElementType == ElementType.ElementAlternative)
     {
         writer.WriteLine("{0}", elem.ElementType);
         foreach (ServiceElement element in elem.GetValueAsElementList())
         {
             DumpElement(writer, depth + 1, element);
         }//for
     }
     else if (elem.ElementType == ElementType.Nil)
     {
         writer.WriteLine("Nil:");
     }
     else if (elem.ElementType == ElementType.TextString)
     {
         DumpString(writer, depth, elem, null);
     }
     else if (elem.ElementType == ElementType.Boolean ||
              elem.ElementType == ElementType.Url)
     {
         // Non-numeric types
         writer.WriteLine("{0}: {1}", elem.ElementType, elem.Value);
     }
     else
     {
         String name      = null;
         String valueText = null;
         if (elem.ElementTypeDescriptor == ElementTypeDescriptor.Uuid)
         {
             if (elem.ElementType == ElementType.Uuid16)
             {
                 name = BluetoothService.GetName((UInt16)elem.Value);
             }
             else if (elem.ElementType == ElementType.Uuid32)
             {
                 name = BluetoothService.GetName((UInt32)elem.Value);
             }
             else
             {
                 System.Diagnostics.Debug.Assert(elem.ElementType == ElementType.Uuid128);
                 name      = BluetoothService.GetName((Guid)elem.Value);
                 valueText = ((Guid)elem.Value).ToString();
             }
         }//if UUID
         if (valueText == null)
         {
             if (elem.ElementTypeDescriptor == ElementTypeDescriptor.Unknown)
             {
                 valueText = "unknown";
             }
             else if (elem.ElementType == ElementType.UInt128 ||
                      elem.ElementType == ElementType.Int128)
             {
                 valueText = BitConverter.ToString((byte[])elem.Value);
             }
             else
             {
                 valueText = String.Format(System.Globalization.CultureInfo.InvariantCulture, "0x{0:X}", elem.Value);
             }
         }
         if (name == null)
         {
             writer.WriteLine("{0}: {1}", elem.ElementType, valueText);
         }
         else
         {
             writer.WriteLine("{0}: {1} -- {2}", elem.ElementType, valueText, name);
         }
     }//else
 }
 private void WriteSByte(ServiceElement element, SByte value, byte[] buf, ref int offset, out int totalLength)
 {
     Byte valueU = unchecked((Byte)value);
     WriteByte(element, valueU, buf, ref  offset, out  totalLength);
 }
        /// <summary>
        /// Create the element in the buffer starting at offset, and return its totalLength.
        /// </summary>
        /// <param name="element">The element to create.
        /// </param>
        /// <param name="buf">The byte array to write the encoded element to.
        /// </param>
        /// <param name="offset">The place to start writing in <paramref name="buf"/>.
        /// </param>
        ///
        /// <returns>The total length of the encoded element written to the buffer
        /// </returns>
        protected virtual int CreateElement(ServiceElement element, byte[] buf, int offset)
        {
            int totalLength;

            //
            if (element.ElementTypeDescriptor == ElementTypeDescriptor.ElementSequence ||
                element.ElementTypeDescriptor == ElementTypeDescriptor.ElementAlternative)
            {
                HeaderWriteState headerState;
                int curLen;
                curLen  = MakeVariableLengthHeader(buf, offset, element.ElementTypeDescriptor, out headerState);
                offset += curLen;
                foreach (ServiceElement childElement in element.GetValueAsElementList())
                {
                    curLen  = CreateElement(childElement, buf, offset);
                    offset += curLen;
                }//for
                CompleteHeaderWrite(headerState, buf, offset, out totalLength);
                //----------------
            }
            else if (element.ElementTypeDescriptor == ElementTypeDescriptor.UnsignedInteger ||
                     element.ElementTypeDescriptor == ElementTypeDescriptor.TwosComplementInteger)
            {
                switch (element.ElementType)
                {
                case ElementType.UInt8:
                    WriteByte(element, (Byte)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.Int8:
                    WriteSByte(element, (SByte)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.UInt16:
                    WriteUInt16(element, (UInt16)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.Int16:
                    WriteInt16(element, (Int16)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.UInt32:
                    WriteUInt32(element, (UInt32)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.Int32:
                    WriteInt32(element, (Int32)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.UInt64:
                    WriteUInt64(element, (UInt64)element.Value, buf, ref offset, out totalLength);
                    break;

                case ElementType.Int64:
                    WriteInt64(element, (Int64)element.Value, buf, ref offset, out totalLength);
                    break;

                default:
                    System.Diagnostics.Debug.Fail(String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                "Unexpected integral type '{0}'.", element.ElementType));
                    totalLength = 0;
                    break;
                }//switch
                 //----------------
            }
            else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Uuid)
            {
                if (element.ElementType == ElementType.Uuid16)
                {
                    WriteUInt16(element, (UInt16)element.Value, buf, ref offset, out totalLength);
                }
                else if (element.ElementType == ElementType.Uuid32)
                {
                    WriteUInt32(element, (UInt32)element.Value, buf, ref offset, out totalLength);
                }
                else
                {
                    //TODO If the 'Guid' holds a 'Bluetooth-based' UUID, then should we write the short form?
                    byte[] bytes;
                    System.Diagnostics.Debug.Assert(element.ElementType == ElementType.Uuid128);
                    Guid hostGuid = (Guid)element.Value;
                    Guid netGuid  = Sockets.BluetoothListener.HostToNetworkOrder(hostGuid);
                    bytes = netGuid.ToByteArray();
                    WriteFixedLength(element, bytes, buf, ref offset, out totalLength);
                }
                //----------------
            }
            else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Url)
            {
                Uri    uri        = element.GetValueAsUri();
                String uriString  = uri.ToString();
                byte[] valueBytes = System.Text.Encoding.ASCII.GetBytes(uriString);
                WriteVariableLength(element, valueBytes, buf, ref offset, out totalLength);
                //----------------
            }
            else if (element.ElementTypeDescriptor == ElementTypeDescriptor.TextString)
            {
                byte[] valueBytes;
                String valueString = element.Value as String;
                if (valueString != null)
                {
                    valueBytes = System.Text.Encoding.UTF8.GetBytes(valueString);
                }
                else
                {
                    System.Diagnostics.Debug.Assert(element.Value is byte[]);
                    valueBytes = (byte[])element.Value;
                }
                WriteVariableLength(element, valueBytes, buf, ref offset, out totalLength);
                //----------------
            }
            else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Nil)
            {
                WriteFixedLength(element, new byte[0], buf, ref offset, out totalLength);
                //----------------
            }
            else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Boolean)
            {
                bool   value      = (bool)element.Value;
                byte[] valueBytes = new byte[1];
                valueBytes[0] = value ? (byte)1 : (byte)0;
                WriteFixedLength(element, valueBytes, buf, ref offset, out totalLength);
                //----------------
            }
            else
            {
                totalLength = 0;
            }
            //
            if (totalLength == 0)
            {
                throw new NotSupportedException(String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                              "Creation of element type '{0}' not implemented.", element.ElementType));
            }
            return(totalLength);
        }
 private int CreateAttrId(ServiceAttributeId attrId, byte[] buf, int offset)
 {
     ServiceElement dummyElement
         = new ServiceElement(
             ElementType.UInt16, unchecked((UInt16)attrId));
     return CreateElement(dummyElement, buf, offset);
 }
 /// <summary>
 /// Get the enum-like class containing the Service Attribute Id definitions 
 /// for the type of the Service Class contained in the given 
 /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList"/>
 /// (type <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.Uuid"/>) data element.
 /// </summary>
 /// -
 /// <returns>
 /// A <see cref="T:System.Type"/> object representing the enum-like class
 /// holding the Attribute Id definitions, or null if the Service Class is
 /// unknown or the element is not of <see cref="F:InTheHand.Net.Bluetooth.ElementTypeDescriptor.Uuid"/>
 /// type.
 /// </returns>
 /// -
 /// <exception cref="T:System.ArgumentNullException">
 /// <paramref name="idElement"/> is null.
 /// </exception>
 protected virtual Type GetAttributeIdEnumType(ServiceElement idElement)
 {
     if (idElement == null) { throw new ArgumentNullException("idElement"); }
     //
     if (idElement.ElementTypeDescriptor != ElementTypeDescriptor.Uuid) {
         return null;
     }
     Guid uuid = idElement.GetValueAsUuid();
     //
     return GetAttributeIdEnumType(uuid);
 }
Example #27
0
        private static void DumpProtocolDescriptorListList(System.IO.TextWriter writer, int depth, ServiceElement element)
        {
            // The list.
            System.Diagnostics.Debug.Assert(element.ElementType == ElementType.ElementSequence);
            WritePrefix(writer, depth);
            writer.Write("( ");
            bool firstLayer = true;

            foreach (ServiceElement layer in element.GetValueAsElementList())
            {
                ServiceElement[] items = layer.GetValueAsElementArray();
                int used = 0;
                System.Diagnostics.Debug.Assert(items[used].ElementTypeDescriptor == ElementTypeDescriptor.Uuid);
                Guid           protoGuid = items[used].GetValueAsUuid();
                String         protoStr;
                HackProtocolId proto = GuidToHackProtocolId(protoGuid, out protoStr);
                //
                used++;
                writer.Write("{0}( {1}", (firstLayer ? string.Empty : ", "), protoStr);
                if (proto == HackProtocolId.L2Cap)
                {
                    if (used < items.Length)
                    {
                        System.Diagnostics.Debug.Assert(items[used].ElementType == ElementType.UInt16);
                        UInt16 u16 = (UInt16)items[used].Value;
                        HackProtocolServiceMultiplexer psm = unchecked ((HackProtocolServiceMultiplexer)u16);
                        used++;
                        writer.Write(", PSM={0}", Enum_ToStringNameOrHex(psm));
                    }
                }
                else if (proto == HackProtocolId.Rfcomm)
                {
                    if (used < items.Length)
                    {
                        System.Diagnostics.Debug.Assert(items[used].ElementType == ElementType.UInt8);
                        byte channelNumber = (byte)items[used].Value;
                        used++;
                        writer.Write(", ChannelNumber={0}", channelNumber);
                    }
                }
                // Others include BNEP for instance, which isn't defined in the base SDP spec.
                if (used < items.Length)
                {
                    writer.Write(", ...");
                }
                writer.Write(" )");
                firstLayer = false;
            }//foreach layer
            writer.WriteLine(" )");
        }
 private void WriteByte(ServiceElement element, Byte value, byte[] buf, ref int offset, out int totalLength)
 {
     byte[] valueBytes = new byte[1];
     valueBytes[0] = value;
     WriteFixedLength(element, valueBytes, buf, ref offset, out totalLength);
 }
 private void WriteFixedLength(ServiceElement element, byte[] valueBytes, byte[] buf, ref int offset, out int totalLength)
 {
     int headerLen = WriteHeaderFixedLength(element.ElementTypeDescriptor, valueBytes.Length, buf, offset, out totalLength);
     offset += headerLen;
     VerifyWriteSpaceRemaining(valueBytes.Length, buf, offset);
     valueBytes.CopyTo(buf, offset);
     System.Diagnostics.Debug.Assert(totalLength == headerLen + valueBytes.Length);
 }
 private void WriteByte(ServiceElement element, Byte value, byte[] buf, ref int offset, out int totalLength)
 {
     byte[] valueBytes = new byte[1];
     valueBytes[0] = value;
     WriteFixedLength(element, valueBytes, buf, ref offset, out totalLength);
 }
Example #31
0
        //--------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="T:InTheHand.Net.Bluetooth.ServiceAttribute"/> class.
        /// </summary>
        /// -
        /// <param name="id">The Attribute Id as a <see cref="T:InTheHand.Net.Bluetooth.ServiceAttributeId"/>.</param>
        /// <param name="value">The value as a <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</param>
        public ServiceAttribute(ServiceAttributeId id, ServiceElement value)
        {
            m_id      = id;
            m_element = value;
        }
 private static void DumpRawElement(System.IO.TextWriter writer, int depth, ServiceElement attr)
 {
     WritePrefix(writer, depth);
     if (attr.ElementType == ElementType.ElementSequence
             || attr.ElementType == ElementType.ElementAlternative) {
         writer.WriteLine("{0}", attr.ElementType);
         foreach (ServiceElement element in attr.GetValueAsElementList()) {
             DumpRawElement(writer, depth + 1, element);
         }
     } else if (attr.ElementType == ElementType.Nil) {
         writer.WriteLine("Nil:");
     } else if (attr.ElementType == ElementType.TextString
          || attr.ElementType == ElementType.Boolean
          || attr.ElementType == ElementType.Url) {
         // Non-numeric types
         writer.WriteLine("{0}: {1}", attr.ElementType, attr.Value);
     } else if (attr.ElementType == ElementType.Uuid128) {
         writer.WriteLine("{0}: ", attr.ElementType, attr.Value);
     } else {
         writer.WriteLine("{0}: 0x{1:X}", attr.ElementType, attr.Value);
         //{catch(?FOrmatExptn){
         //   writer.WriteLine("{0}: 0x{1}", attr.Type, attr.Value);
         //}
     }
 }
Example #33
0
 public ServiceElement[] GetValueAsElementArray()
 {
     IList_ServiceElement list = GetValueAsElementList();
     ServiceElement[] arr = new ServiceElement[list.Count];
     GetValueAsElementList().CopyTo(arr, 0);
     return arr;
 }
 private static void DumpProtocolDescriptorList(System.IO.TextWriter writer, int depth, ServiceElement element)
 {
     System.Diagnostics.Debug.Assert(element.ElementType == ElementType.ElementAlternative
         || element.ElementType == ElementType.ElementSequence);
     //
     // If passes a list of alternatives, each a protocol descriptor list,
     // then call ourselves on each list.
     if (element.ElementType == ElementType.ElementAlternative) {
         foreach (ServiceElement curStack in element.GetValueAsElementList()) {
             DumpProtocolDescriptorListList(writer, depth + 1, curStack);
         }//foreach
         return;
     }
     //else
     DumpProtocolDescriptorListList(writer, depth, element);
 }
Example #35
0
 [CLSCompliant(false)] // instead use .ctor(ServiceAttributeId,AttributeValue).
 public ServiceAttribute(UInt16 id, ServiceElement value)
     : this(unchecked((ServiceAttributeId)(Int16)id), value)
 { }
        private static void DumpString(System.IO.TextWriter writer, int depth, ServiceElement element, LanguageBaseItem langBase)
        {
            if (langBase != null) {
                try {
                    String value = element.GetValueAsString(langBase);
                    writer.WriteLine("{0}: [{1}] '{2}'", element.ElementType, langBase.NaturalLanguage, value);
                } catch (NotSupportedException ex) {
                    System.Diagnostics.Debug.Assert(ex.Message != null);
                    System.Diagnostics.Debug.Assert(ex.Message.StartsWith("Unrecognized character encoding"));
                    writer.WriteLine("{0}: Failure: {1}", element.ElementType, ex.Message);
                }
            } else {
                try {
                    String hack = element.GetValueAsStringUtf8();
                    writer.WriteLine("{0} (guessing UTF-8): '{1}'", element.ElementType, hack);
                } catch (
                    // TODO ! What exception thrown by UTF8Encoding on NETCF?
#if ! WinCE
                    System.Text.DecoderFallbackException
#else
                    // NETCF doesn't support DecoderFallbackException this what the docs say.
                    ArgumentException
#endif
                ) {
                    writer.WriteLine("{0} (Unknown/bad encoding):", element.ElementType);
                }//try
            }
        }
        private void WriteSByte(ServiceElement element, SByte value, byte[] buf, ref int offset, out int totalLength)
        {
            Byte valueU = unchecked ((Byte)value);

            WriteByte(element, valueU, buf, ref offset, out totalLength);
        }
 private void WriteInt32(ServiceElement element, Int32 value, byte[] buf, ref int offset, out int totalLength)
 {
     Int32 host32 = value;
     Int32 net32 = IPAddress.HostToNetworkOrder(host32);
     byte[] valueBytes = BitConverter.GetBytes(net32);
     WriteFixedLength(element, valueBytes, buf, ref offset, out totalLength);
 }
Example #39
0
 //--------------------------------------------------------------
 private static ServiceRecord CreateRecord()
 {
     List_ServiceAttribute attrs = new List_ServiceAttribute();
     ServiceElement element;
     //
     element = new ServiceElement(ElementType.ElementSequence,
         new ServiceElement(ElementType.Uuid128, Guid.Empty));
     attrs.Add(new ServiceAttribute(UniversalAttributeId.ServiceClassIdList, element));
     //
     element = ServiceRecordHelper.CreateRfcommProtocolDescriptorList();
     attrs.Add(new ServiceAttribute(UniversalAttributeId.ProtocolDescriptorList, element));
     //
     ServiceRecord record = new ServiceRecord(attrs);
     return record;
 }
        private void WriteUInt64(ServiceElement element, UInt64 value, byte[] buf, ref int offset, out int totalLength)
        {
            Int64 valueS = unchecked ((Int64)value);

            WriteInt64(element, valueS, buf, ref offset, out totalLength);
        }
 //--------
 private static void DumpAdditionalProtocolDescriptorLists(System.IO.TextWriter writer, int depth, ServiceElement element)
 {
     System.Diagnostics.Debug.Assert(element.ElementType == ElementType.ElementSequence);
     //
     // Is a list of PDLs
     foreach (ServiceElement curList in element.GetValueAsElementList()) {
         DumpProtocolDescriptorList(writer, depth + 1, curList);
     }//foreach
 }
Example #42
0
 private static ElementType checkTypeSuitsElementParamsArray(ElementType typePassThru, ServiceElement[] childElements)
 {
     // Throw a more specific error about the params array when the value is null.
     // As error would be thrown by SetValue, but we can report a more helpful message.
     if (childElements == null) {
         // Caller passed a literal null, so could be aiming for other ElementType
         // so can't complain that we need to be a Seq/Alt type.
     } else {
         //
         if (typePassThru != ElementType.ElementSequence && typePassThru != ElementType.ElementAlternative) {
             throw new ArgumentException(ErrorMsgSeqAltTypeNeedElementArray);
         }
     }
     return typePassThru;
 }
 private static void DumpProtocolDescriptorListList(System.IO.TextWriter writer, int depth, ServiceElement element)
 {
     // The list.
     System.Diagnostics.Debug.Assert(element.ElementType == ElementType.ElementSequence);
     WritePrefix(writer, depth);
     writer.Write("( ");
     bool firstLayer = true;
     foreach (ServiceElement layer in element.GetValueAsElementList()) {
         ServiceElement[] items = layer.GetValueAsElementArray();
         int used = 0;
         System.Diagnostics.Debug.Assert(items[used].ElementTypeDescriptor == ElementTypeDescriptor.Uuid);
         Guid protoGuid = items[used].GetValueAsUuid();
         HackProtocolId proto = GuidToHackProtocolId(protoGuid);
         String protoStr;
         if (proto != 0) {
             protoStr = Enum_ToStringNameOrHex(proto);
         } else { // Not a standard Bluetooth value so dump its UUID
             protoStr = protoGuid.ToString();
         }
         //
         used++;
         writer.Write("{0}( {1}", (firstLayer ? string.Empty : ", "), protoStr);
         if (proto == HackProtocolId.L2Cap) {
             if (used < items.Length) {
                 System.Diagnostics.Debug.Assert(items[used].ElementType == ElementType.UInt16);
                 HackProtocolServiceMultiplexer psm = (HackProtocolServiceMultiplexer)(UInt16)items[used].Value;
                 used++;
                 writer.Write(", PSM={0}", Enum_ToStringNameOrHex(psm));
             }
         } else if (proto == HackProtocolId.Rfcomm) {
             if (used < items.Length) {
                 System.Diagnostics.Debug.Assert(items[used].ElementType == ElementType.UInt8);
                 byte channelNumber = (byte)items[used].Value;
                 used++;
                 writer.Write(", ChannelNumber={0}", channelNumber);
             }
         }
         // Others include BNEP for instance, which isn't defined in the base SDP spec.
         if (used < items.Length) {
             writer.Write(", ...");
         }
         writer.Write(" )");
         firstLayer = false;
     }//foreach layer
     writer.WriteLine(" )");
 }
Example #44
0
 //--------
 private static void DumpAdditionalProtocolDescriptorLists(System.IO.TextWriter writer, int depth, ServiceElement element)
 {
     System.Diagnostics.Debug.Assert(element.ElementType == ElementType.ElementSequence);
     //
     // Is a list of PDLs
     foreach (ServiceElement curList in element.GetValueAsElementList())
     {
         DumpProtocolDescriptorList(writer, depth + 1, curList);
     }//foreach
 }
 private static void DumpElement(System.IO.TextWriter writer, int depth, ServiceElement attr)
 {
     WritePrefix(writer, depth);
     if (attr.ElementType == ElementType.ElementSequence || attr.ElementType == ElementType.ElementAlternative) {
         writer.WriteLine("{0}", attr.ElementType);
         foreach (ServiceElement element in attr.GetValueAsElementList()) {
             DumpElement(writer, depth + 1, element);
         }//for
     } else if (attr.ElementType == ElementType.Nil) {
         writer.WriteLine("Nil:");
     } else if (attr.ElementType == ElementType.TextString
          || attr.ElementType == ElementType.Boolean
          || attr.ElementType == ElementType.Url) {
         // Non-numeric types
         writer.WriteLine("{0}: {1}", attr.ElementType, attr.Value);
     } else {
         String name = null;
         String valueText = null;
         if (attr.ElementTypeDescriptor == ElementTypeDescriptor.Uuid) {
             if (attr.ElementType == ElementType.Uuid16) {
                 name = BluetoothService.GetName((UInt16)attr.Value);
             } else if (attr.ElementType == ElementType.Uuid32) {
                 name = BluetoothService.GetName((UInt32)attr.Value);
             } else {
                 System.Diagnostics.Debug.Assert(attr.ElementType == ElementType.Uuid128);
                 name = BluetoothService.GetName((Guid)attr.Value);
                 valueText = ((Guid)attr.Value).ToString();
             }
         }//if UUID
         if (valueText == null) {
             if (attr.ElementTypeDescriptor == ElementTypeDescriptor.Unknown) {
                 valueText = "unknown";
             } else {
                 valueText = String.Format(System.Globalization.CultureInfo.InvariantCulture, "0x{0:X}", attr.Value);
             }
         }
         if (name == null) {
             writer.WriteLine("{0}: {1}", attr.ElementType, valueText);
         } else {
             writer.WriteLine("{0}: {1} -- {2}", attr.ElementType, valueText, name);
         }
     }//else
 }
Example #46
0
 private static void DumpProtocolDescriptorList(System.IO.TextWriter writer, int depth, ServiceElement element)
 {
     System.Diagnostics.Debug.Assert(element.ElementType == ElementType.ElementAlternative ||
                                     element.ElementType == ElementType.ElementSequence);
     //
     // If passes a list of alternatives, each a protocol descriptor list,
     // then call ourselves on each list.
     if (element.ElementType == ElementType.ElementAlternative)
     {
         foreach (ServiceElement curStack in element.GetValueAsElementList())
         {
             DumpProtocolDescriptorListList(writer, depth + 1, curStack);
         }//foreach
         return;
     }
     //else
     DumpProtocolDescriptorListList(writer, depth, element);
 }
 private static ServiceElement CreatePdlLayer(UInt16 uuid, params ServiceElement[] data)
 {
     IList_ServiceElement curSeqChildren;
     ServiceElement curValueElmt, curSeqElmt;
     //
     curSeqChildren = new List_ServiceElement();
     curValueElmt = new ServiceElement(ElementType.Uuid16, uuid);
     curSeqChildren.Add(curValueElmt);
     foreach (ServiceElement element in data) {
         curSeqChildren.Add(element);
     }
     curSeqElmt = new ServiceElement(ElementType.ElementSequence, curSeqChildren);
     return curSeqElmt;
 }
 private int CreateElement(ServiceElement element, byte[] buf, int offset)
 {
     int totalLength;
     //
     if (element.ElementTypeDescriptor == ElementTypeDescriptor.ElementSequence
             || element.ElementTypeDescriptor == ElementTypeDescriptor.ElementAlternative) {
         HeaderWriteState headerState;
         int curLen;
         curLen = MakeVariableLengthHeader(buf, offset, element.ElementTypeDescriptor, out headerState);
         offset += curLen;
         foreach (ServiceElement childElement in element.GetValueAsElementList()) {
             curLen = CreateElement(childElement, buf, offset);
             offset += curLen;
         }//for
         CompleteHeaderWrite(headerState, buf, offset, out totalLength);
         //----------------
     } else if (element.ElementTypeDescriptor == ElementTypeDescriptor.UnsignedInteger
             || element.ElementTypeDescriptor == ElementTypeDescriptor.TwosComplementInteger) {
         switch (element.ElementType) {
             case ElementType.UInt8:
                 WriteByte(element, (Byte)element.Value, buf, ref offset, out totalLength);
                 break;
             case ElementType.Int8:
                 WriteSByte(element, (SByte)element.Value, buf, ref offset, out totalLength);
                 break;
             case ElementType.UInt16:
                 WriteUInt16(element, (UInt16)element.Value, buf, ref offset, out totalLength);
                 break;
             case ElementType.Int16:
                 WriteInt16(element, (Int16)element.Value, buf, ref offset, out totalLength);
                 break;
             case ElementType.UInt32:
                 WriteUInt32(element, (UInt32)element.Value, buf, ref offset, out totalLength);
                 break;
             case ElementType.Int32:
                 WriteInt32(element, (Int32)element.Value, buf, ref offset, out totalLength);
                 break;
             default:
                 System.Diagnostics.Debug.Fail(String.Format(System.Globalization.CultureInfo.InvariantCulture,
                         "Unexpected integral type '{0}'.", element.ElementType));
                 totalLength = 0;
                 break;
         }//switch
         //----------------
     } else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Uuid) {
         if (element.ElementType == ElementType.Uuid16) {
             WriteUInt16(element, (UInt16)element.Value, buf, ref offset, out totalLength);
         } else if (element.ElementType == ElementType.Uuid32) {
             WriteUInt32(element, (UInt32)element.Value, buf, ref offset, out totalLength);
         } else {
             //TODO If the 'Guid' holds a 'Bluetooth-based' UUID, then should we write the short form?
             byte[] bytes;
             System.Diagnostics.Debug.Assert(element.ElementType == ElementType.Uuid128);
             Guid hostGuid = (Guid)element.Value;
             Guid netGuid = Sockets.BluetoothListener.HostToNetworkOrder(hostGuid);
             bytes = netGuid.ToByteArray();
             WriteFixedLength(element, bytes, buf, ref offset, out totalLength);
         }
         //----------------
     } else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Url) {
         Uri uri = element.GetValueAsUri();
         String uriString = uri.ToString();
         byte[] valueBytes = System.Text.Encoding.ASCII.GetBytes(uriString);
         WriteVariableLength(element, valueBytes, buf, ref offset, out totalLength);
         //----------------
     } else if (element.ElementTypeDescriptor == ElementTypeDescriptor.TextString) {
         byte[] valueBytes;
         String valueString = element.Value as String;
         if (valueString != null) {
             valueBytes = System.Text.Encoding.UTF8.GetBytes(valueString);
         } else {
             System.Diagnostics.Debug.Assert(element.Value is byte[]);
             valueBytes = (byte[])element.Value;
         }
         WriteVariableLength(element, valueBytes, buf, ref offset, out totalLength);
         //----------------
     } else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Nil) {
         WriteFixedLength(element, new byte[0], buf, ref offset, out totalLength);
         //----------------
     } else if (element.ElementTypeDescriptor == ElementTypeDescriptor.Boolean) {
         bool value = (bool)element.Value;
         byte[] valueBytes = new byte[1];
         valueBytes[0] = value ? (byte)1 : (byte)0;
         WriteFixedLength(element, valueBytes, buf, ref offset, out totalLength);
         //----------------
     } else {
         totalLength = 0;
     }
     //
     if (totalLength == 0) {
         throw new NotSupportedException(String.Format(System.Globalization.CultureInfo.InvariantCulture,
             "Creation of element type '{0}' not implemented.", element.ElementType));
     }
     return totalLength;
 }