summaryrefslogtreecommitdiffstats
path: root/src/DotNetOAuth/ProtocolMessageSerializer.cs
blob: da564d286aea54d1a023e113fcb170a54fd847a4 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace DotNetOAuth {
	/// <summary>
	/// Serializes/deserializes OAuth messages for/from transit.
	/// </summary>
	internal class ProtocolMessageSerializer<T> where T : IProtocolMessage {
		DataContractSerializer serializer;
		const string rootName = "root";

		internal ProtocolMessageSerializer() {
			serializer = new DataContractSerializer(typeof(T), rootName, Protocol.DataContractNamespace);
		}

		/// <summary>
		/// Reads the data from a message instance and returns a series of name=value pairs for the fields that must be included in the message.
		/// </summary>
		/// <param name="message">The message to be serialized.</param>
		internal IDictionary<string, string> Serialize(T message) {
			if (message == null) throw new ArgumentNullException("message");

			var fields = new Dictionary<string, string>();
			XmlWriter writer = new ProtocolMessageSerializer<T>.PseudoXmlWriter(fields);
			serializer.WriteObjectContent(writer, message);
			writer.Close();
			return fields;
		}

		/// <summary>
		/// Reads name=value pairs into an OAuth message.
		/// </summary>
		/// <param name="fields">The name=value pairs that were read in from the transport.</param>
		internal T Deserialize(IDictionary<string, string> fields) {
			if (fields == null) throw new ArgumentNullException("fields");

			var reader = new PseudoXmlReader(fields);
			//var reader = new XmlTextReader(new StringReader("<root xmlns='http://oauth.net/core/1.0/'><Name>Andrew</Name><age>15</age></root>"));
			T result = (T)serializer.ReadObject(reader, false);
			return result;
		}

		/// <summary>
		/// Writes out a dictionary as if it were XML.
		/// </summary>
		class PseudoXmlWriter : XmlWriter {
			Dictionary<string, string> dictionary;
			string key;
			StringBuilder value = new StringBuilder();

			internal PseudoXmlWriter(Dictionary<string, string> dictionary) {
				this.dictionary = dictionary;
			}

			public override void WriteStartElement(string prefix, string localName, string ns) {
				key = localName;
				value.Length = 0;
			}

			public override void WriteString(string text) {
				if (!string.IsNullOrEmpty(key)) {
					value.Append(text);
				}
			}

			public override void WriteEndElement() {
				if (key != null) {
					dictionary[key] = value.ToString();
					key = null;
					value.Length = 0;
				}
			}

			public override WriteState WriteState {
				get { return WriteState.Element; }
			}

			public override void WriteStartAttribute(string prefix, string localName, string ns) {
				key = null;
			}

			public override void WriteEndAttribute() { }

			public override void Close() { }

			#region Unimplemented methods

			public override void Flush() {
				throw new NotImplementedException();
			}

			public override string LookupPrefix(string ns) {
				throw new NotImplementedException();
			}

			public override void WriteBase64(byte[] buffer, int index, int count) {
				throw new NotImplementedException();
			}

			public override void WriteCData(string text) {
				throw new NotImplementedException();
			}

			public override void WriteCharEntity(char ch) {
				throw new NotImplementedException();
			}

			public override void WriteChars(char[] buffer, int index, int count) {
				throw new NotImplementedException();
			}

			public override void WriteComment(string text) {
				throw new NotImplementedException();
			}

			public override void WriteDocType(string name, string pubid, string sysid, string subset) {
				throw new NotImplementedException();
			}

			public override void WriteEndDocument() {
				throw new NotImplementedException();
			}

			public override void WriteEntityRef(string name) {
				throw new NotImplementedException();
			}

			public override void WriteFullEndElement() {
				throw new NotImplementedException();
			}

			public override void WriteProcessingInstruction(string name, string text) {
				throw new NotImplementedException();
			}

			public override void WriteRaw(string data) {
				throw new NotImplementedException();
			}

			public override void WriteRaw(char[] buffer, int index, int count) {
				throw new NotImplementedException();
			}

			public override void WriteStartDocument(bool standalone) {
				throw new NotImplementedException();
			}

			public override void WriteStartDocument() {
				throw new NotImplementedException();
			}

			public override void WriteSurrogateCharEntity(char lowChar, char highChar) {
				throw new NotImplementedException();
			}

			public override void WriteWhitespace(string ws) {
				throw new NotImplementedException();
			}

			#endregion
		}

		/// <summary>
		/// Reads in a dictionary as if it were XML.
		/// </summary>
		class PseudoXmlReader : XmlReader {
			IDictionary<string, string> dictionary;
			IEnumerator<string> keyEnumerator;
			bool isFinished;
			int depth;
			XmlNodeType currentNode = XmlNodeType.None;

			internal PseudoXmlReader(IDictionary<string, string> dictionary) {
				this.dictionary = dictionary;
				keyEnumerator = dictionary.Keys.OrderBy(key => key, StringComparer.Ordinal).GetEnumerator();
			}

			public override int AttributeCount {
				get { return 0; }
			}

			public override bool IsEmptyElement {
				get {
					if (keyEnumerator.Current == null) {
						return isFinished;
					}
					string value;
					bool result = !dictionary.TryGetValue(keyEnumerator.Current, out value) || String.IsNullOrEmpty(value);
					return result;
				}
			}

			public override string LocalName {
				get { return keyEnumerator.Current; }
			}

			public override bool MoveToElement() {
				bool result = currentNode != XmlNodeType.Element && depth > 0;
				currentNode = depth > 0 ? XmlNodeType.Element : XmlNodeType.None;
				return result;
			}

			public override bool MoveToNextAttribute() {
				if (depth == 1 && currentNode != XmlNodeType.Attribute) {
					currentNode = XmlNodeType.Attribute;
					return true;
				} else {
					return false;
				}
			}

			public override string NamespaceURI {
				get {
					string result = depth == 1 && currentNode == XmlNodeType.Attribute ?
						"http://www.w3.org/2000/xmlns/" : Protocol.DataContractNamespace;
					return result;
				}
			}

			public override XmlNodeType NodeType {
				get { return currentNode; }
			}

			public override bool Read() {
				if (isFinished) {
					if (depth > 0) {
						depth--;
					}
					return depth > 0;
				}
				switch (depth) {
					case 0: // moving to root node
						depth++; // -> 1
						currentNode = XmlNodeType.Element;
						return true;
					case 1: // moving to first content node
						depth++; // -> 2
						isFinished = !keyEnumerator.MoveNext();
						currentNode = isFinished ? XmlNodeType.EndElement : XmlNodeType.Element;
						return true;
					case 2: // content node
						switch (currentNode) {
							case XmlNodeType.Element:
								currentNode = XmlNodeType.Text;
								return true;
							case XmlNodeType.Text:
								currentNode = XmlNodeType.EndElement;
								return true;
							case XmlNodeType.EndElement:
								bool result = keyEnumerator.MoveNext();
								if (!result) {
									isFinished = true;
									depth--;
									currentNode = XmlNodeType.EndElement;
								} else {
									currentNode = XmlNodeType.Element;
								}
								return true;
						}
						break;
				}
				throw new InvalidOperationException();
			}

			public override string Value {
				get { return dictionary[keyEnumerator.Current]; }
			}

			#region Unimplemented methods

			public override string BaseURI {
				get { throw new NotImplementedException(); }
			}

			public override void Close() {
				throw new NotImplementedException();
			}

			public override int Depth {
				get { throw new NotImplementedException(); }
			}

			public override bool EOF {
				get { throw new NotImplementedException(); }
			}

			public override string GetAttribute(int i) {
				throw new NotImplementedException();
			}

			public override string GetAttribute(string name, string namespaceURI) {
				throw new NotImplementedException();
			}

			public override string GetAttribute(string name) {
				throw new NotImplementedException();
			}

			public override bool HasValue {
				get { throw new NotImplementedException(); }
			}

			public override string LookupNamespace(string prefix) {
				throw new NotImplementedException();
			}

			public override bool MoveToAttribute(string name, string ns) {
				throw new NotImplementedException();
			}

			public override bool MoveToAttribute(string name) {
				throw new NotImplementedException();
			}

			public override bool MoveToFirstAttribute() {
				throw new NotImplementedException();
			}

			public override XmlNameTable NameTable {
				get { throw new NotImplementedException(); }
			}

			public override string Prefix {
				get { throw new NotImplementedException(); }
			}

			public override ReadState ReadState {
				get { throw new NotImplementedException(); }
			}

			public override bool ReadAttributeValue() {
				throw new NotImplementedException();
			}

			public override void ResolveEntity() {
				throw new NotImplementedException();
			}

			#endregion
		}
	}
}