aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Dlna/Ssdp/Extensions.cs
blob: 12589e80fe9318a94c79603fc3aba74254bc4234 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MediaBrowser.Dlna.Ssdp
{
    public static class Extensions
    {
        public static Task<int> ReceiveAsync(this Socket socket, byte[] buffer, int offset, int size)
        {
            var tcs = new TaskCompletionSource<int>(socket);
            var remoteip = new IPEndPoint(IPAddress.Any, 0);
            var endpoint = (EndPoint)remoteip;

            socket.BeginReceiveFrom(buffer, offset, size, SocketFlags.None, ref endpoint, iar =>
            {
                var result = (TaskCompletionSource<int>)iar.AsyncState;
                var iarSocket = (Socket)result.Task.AsyncState;

                try
                {
                    result.TrySetResult(iarSocket.EndReceive(iar));
                }
                catch (Exception exc)
                {
                    result.TrySetException(exc);
                }
            }, tcs);

            return tcs.Task;
        }
        
        public static string GetValue(this XElement container, XName name)
        {
            var node = container.Element(name);

            return node == null ? null : node.Value;
        }

        public static string GetAttributeValue(this XElement container, XName name)
        {
            var node = container.Attribute(name);

            return node == null ? null : node.Value;
        }

        public static string GetDescendantValue(this XElement container, XName name)
        {
            var node = container.Descendants(name)
                .FirstOrDefault();

            return node == null ? null : node.Value;
        }
    }
}