Extensions.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading.Tasks;
  6. using System.Xml.Linq;
  7. namespace MediaBrowser.Dlna.Ssdp
  8. {
  9. public static class Extensions
  10. {
  11. public static Task<int> ReceiveAsync(this Socket socket, byte[] buffer, int offset, int size)
  12. {
  13. var tcs = new TaskCompletionSource<int>(socket);
  14. var remoteip = new IPEndPoint(IPAddress.Any, 0);
  15. var endpoint = (EndPoint)remoteip;
  16. socket.BeginReceiveFrom(buffer, offset, size, SocketFlags.None, ref endpoint, iar =>
  17. {
  18. var result = (TaskCompletionSource<int>)iar.AsyncState;
  19. var iarSocket = (Socket)result.Task.AsyncState;
  20. try
  21. {
  22. result.TrySetResult(iarSocket.EndReceive(iar));
  23. }
  24. catch (Exception exc)
  25. {
  26. result.TrySetException(exc);
  27. }
  28. }, tcs);
  29. return tcs.Task;
  30. }
  31. public static string GetValue(this XElement container, XName name)
  32. {
  33. var node = container.Element(name);
  34. return node == null ? null : node.Value;
  35. }
  36. public static string GetAttributeValue(this XElement container, XName name)
  37. {
  38. var node = container.Attribute(name);
  39. return node == null ? null : node.Value;
  40. }
  41. public static string GetDescendantValue(this XElement container, XName name)
  42. {
  43. var node = container.Descendants(name)
  44. .FirstOrDefault();
  45. return node == null ? null : node.Value;
  46. }
  47. }
  48. }