//--------
 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 #2
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 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 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 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);
         //}
     }
 }
 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
 }
 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(" )");
 }
 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 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 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 #11
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 #12
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
 }
        /// <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 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;
 }