summaryrefslogtreecommitdiffstats
path: root/src/DotNetOAuth/Messaging/Reflection/MessageDescription.cs
blob: ef73a319cfe0cc0b2e6b96871e3945483992a85b (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
//-----------------------------------------------------------------------
// <copyright file="MessageDescription.cs" company="Andrew Arnott">
//     Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace DotNetOAuth.Messaging.Reflection {
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;

	internal class MessageDescription {
		private Type messageType;
		private Dictionary<string, MessagePart> mapping;

		internal MessageDescription(Type messageType) {
			if (messageType == null) {
				throw new ArgumentNullException("messageType");
			}

			if (!typeof(IProtocolMessage).IsAssignableFrom(messageType)) {
				throw new ArgumentOutOfRangeException(); // TODO: better message
			}

			this.messageType = messageType;
			this.ReflectMessageType();
		}

		internal Type MessageType {
			get { return this.messageType; }
		}

		internal IDictionary<string, MessagePart> Mapping {
			get { return this.mapping; }
		}

		internal void ReflectMessageType() {
			this.mapping = new Dictionary<string, MessagePart>();

			Type currentType = this.messageType;
			do {
				foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
					if (member is PropertyInfo || member is FieldInfo) {
						MessagePartAttribute partAttribute = member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>().FirstOrDefault();
						if (partAttribute != null) {
							MessagePart part = new MessagePart(member, partAttribute);
							this.mapping.Add(part.Name, part);
						}
					}
				}
				currentType = currentType.BaseType;
			} while (currentType != null);
		}
	}
}