This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 327
/
EwsUtilities.cs
1606 lines (1450 loc) · 63.4 KB
/
EwsUtilities.cs
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
/// <summary>
/// EWS utilities
/// </summary>
internal static class EwsUtilities
{
#region Private members
/// <summary>
/// Map from XML element names to ServiceObject type and constructors.
/// </summary>
private static LazyMember<ServiceObjectInfo> serviceObjectInfo = new LazyMember<ServiceObjectInfo>(
delegate()
{
return new ServiceObjectInfo();
});
/// <summary>
/// Version of API binary.
/// </summary>
private static LazyMember<string> buildVersion = new LazyMember<string>(
delegate()
{
try
{
FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
return fileInfo.FileVersion;
}
catch
{
// OM:2026839 When run in an environment with partial trust, fetching the build version blows up.
// Just return a hardcoded value on failure.
return "0.0";
}
});
/// <summary>
/// Dictionary of enum type to ExchangeVersion maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<Enum, ExchangeVersion>>> enumVersionDictionaries = new LazyMember<Dictionary<Type, Dictionary<Enum, ExchangeVersion>>>(
() => new Dictionary<Type, Dictionary<Enum, ExchangeVersion>>()
{
{ typeof(WellKnownFolderName), BuildEnumDict(typeof(WellKnownFolderName)) },
{ typeof(ItemTraversal), BuildEnumDict(typeof(ItemTraversal)) },
{ typeof(ConversationQueryTraversal), BuildEnumDict(typeof(ConversationQueryTraversal)) },
{ typeof(FileAsMapping), BuildEnumDict(typeof(FileAsMapping)) },
{ typeof(EventType), BuildEnumDict(typeof(EventType)) },
{ typeof(MeetingRequestsDeliveryScope), BuildEnumDict(typeof(MeetingRequestsDeliveryScope)) },
{ typeof(ViewFilter), BuildEnumDict(typeof(ViewFilter)) },
});
/// <summary>
/// Dictionary of enum type to schema-name-to-enum-value maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<string, Enum>>> schemaToEnumDictionaries = new LazyMember<Dictionary<Type, Dictionary<string, Enum>>>(
() => new Dictionary<Type, Dictionary<string, Enum>>
{
{ typeof(EventType), BuildSchemaToEnumDict(typeof(EventType)) },
{ typeof(MailboxType), BuildSchemaToEnumDict(typeof(MailboxType)) },
{ typeof(FileAsMapping), BuildSchemaToEnumDict(typeof(FileAsMapping)) },
{ typeof(RuleProperty), BuildSchemaToEnumDict(typeof(RuleProperty)) },
{ typeof(WellKnownFolderName), BuildSchemaToEnumDict(typeof(WellKnownFolderName)) },
});
/// <summary>
/// Dictionary of enum type to enum-value-to-schema-name maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<Enum, string>>> enumToSchemaDictionaries = new LazyMember<Dictionary<Type, Dictionary<Enum, string>>>(
() => new Dictionary<Type, Dictionary<Enum, string>>
{
{ typeof(EventType), BuildEnumToSchemaDict(typeof(EventType)) },
{ typeof(MailboxType), BuildEnumToSchemaDict(typeof(MailboxType)) },
{ typeof(FileAsMapping), BuildEnumToSchemaDict(typeof(FileAsMapping)) },
{ typeof(RuleProperty), BuildEnumToSchemaDict(typeof(RuleProperty)) },
{ typeof(WellKnownFolderName), BuildEnumToSchemaDict(typeof(WellKnownFolderName)) },
});
/// <summary>
/// Dictionary to map from special CLR type names to their "short" names.
/// </summary>
private static LazyMember<Dictionary<string, string>> typeNameToShortNameMap = new LazyMember<Dictionary<string, string>>(
() => new Dictionary<string, string>
{
{ "Boolean", "bool" },
{ "Int16", "short" },
{ "Int32", "int" },
{ "String", "string" }
});
#endregion
#region Constants
internal const string XSFalse = "false";
internal const string XSTrue = "true";
internal const string EwsTypesNamespacePrefix = "t";
internal const string EwsMessagesNamespacePrefix = "m";
internal const string EwsErrorsNamespacePrefix = "e";
internal const string EwsSoapNamespacePrefix = "soap";
internal const string EwsXmlSchemaInstanceNamespacePrefix = "xsi";
internal const string PassportSoapFaultNamespacePrefix = "psf";
internal const string WSTrustFebruary2005NamespacePrefix = "wst";
internal const string WSAddressingNamespacePrefix = "wsa";
internal const string AutodiscoverSoapNamespacePrefix = "a";
internal const string WSSecurityUtilityNamespacePrefix = "wsu";
internal const string WSSecuritySecExtNamespacePrefix = "wsse";
internal const string EwsTypesNamespace = "http://schemas.microsoft.com/exchange/services/2006/types";
internal const string EwsMessagesNamespace = "http://schemas.microsoft.com/exchange/services/2006/messages";
internal const string EwsErrorsNamespace = "http://schemas.microsoft.com/exchange/services/2006/errors";
internal const string EwsSoapNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
internal const string EwsSoap12Namespace = "http://www.w3.org/2003/05/soap-envelope";
internal const string EwsXmlSchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
internal const string PassportSoapFaultNamespace = "http://schemas.microsoft.com/Passport/SoapServices/SOAPFault";
internal const string WSTrustFebruary2005Namespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
internal const string WSAddressingNamespace = "http://www.w3.org/2005/08/addressing"; // "http://schemas.xmlsoap.org/ws/2004/08/addressing";
internal const string AutodiscoverSoapNamespace = "http://schemas.microsoft.com/exchange/2010/Autodiscover";
internal const string WSSecurityUtilityNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
internal const string WSSecuritySecExtNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
/// <summary>
/// Regular expression for legal domain names.
/// </summary>
internal const string DomainRegex = "^[-a-zA-Z0-9_.]+$";
#endregion
/// <summary>
/// Asserts that the specified condition if true.
/// </summary>
/// <param name="condition">Assertion.</param>
/// <param name="caller">The caller.</param>
/// <param name="message">The message to use if assertion fails.</param>
internal static void Assert(
bool condition,
string caller,
string message)
{
Debug.Assert(
condition,
string.Format("[{0}] {1}", caller, message));
}
/// <summary>
/// Gets the namespace prefix from an XmlNamespace enum value.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <returns>Namespace prefix string.</returns>
internal static string GetNamespacePrefix(XmlNamespace xmlNamespace)
{
switch (xmlNamespace)
{
case XmlNamespace.Types:
return EwsTypesNamespacePrefix;
case XmlNamespace.Messages:
return EwsMessagesNamespacePrefix;
case XmlNamespace.Errors:
return EwsErrorsNamespacePrefix;
case XmlNamespace.Soap:
case XmlNamespace.Soap12:
return EwsSoapNamespacePrefix;
case XmlNamespace.XmlSchemaInstance:
return EwsXmlSchemaInstanceNamespacePrefix;
case XmlNamespace.PassportSoapFault:
return PassportSoapFaultNamespacePrefix;
case XmlNamespace.WSTrustFebruary2005:
return WSTrustFebruary2005NamespacePrefix;
case XmlNamespace.WSAddressing:
return WSAddressingNamespacePrefix;
case XmlNamespace.Autodiscover:
return AutodiscoverSoapNamespacePrefix;
default:
return string.Empty;
}
}
/// <summary>
/// Gets the namespace URI from an XmlNamespace enum value.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <returns>Uri as string</returns>
internal static string GetNamespaceUri(XmlNamespace xmlNamespace)
{
switch (xmlNamespace)
{
case XmlNamespace.Types:
return EwsTypesNamespace;
case XmlNamespace.Messages:
return EwsMessagesNamespace;
case XmlNamespace.Errors:
return EwsErrorsNamespace;
case XmlNamespace.Soap:
return EwsSoapNamespace;
case XmlNamespace.Soap12:
return EwsSoap12Namespace;
case XmlNamespace.XmlSchemaInstance:
return EwsXmlSchemaInstanceNamespace;
case XmlNamespace.PassportSoapFault:
return PassportSoapFaultNamespace;
case XmlNamespace.WSTrustFebruary2005:
return WSTrustFebruary2005Namespace;
case XmlNamespace.WSAddressing:
return WSAddressingNamespace;
case XmlNamespace.Autodiscover:
return AutodiscoverSoapNamespace;
default:
return string.Empty;
}
}
/// <summary>
/// Gets the XmlNamespace enum value from a namespace Uri.
/// </summary>
/// <param name="namespaceUri">XML namespace Uri.</param>
/// <returns>XmlNamespace enum value.</returns>
internal static XmlNamespace GetNamespaceFromUri(string namespaceUri)
{
switch (namespaceUri)
{
case EwsErrorsNamespace:
return XmlNamespace.Errors;
case EwsTypesNamespace:
return XmlNamespace.Types;
case EwsMessagesNamespace:
return XmlNamespace.Messages;
case EwsSoapNamespace:
return XmlNamespace.Soap;
case EwsSoap12Namespace:
return XmlNamespace.Soap12;
case EwsXmlSchemaInstanceNamespace:
return XmlNamespace.XmlSchemaInstance;
case PassportSoapFaultNamespace:
return XmlNamespace.PassportSoapFault;
case WSTrustFebruary2005Namespace:
return XmlNamespace.WSTrustFebruary2005;
case WSAddressingNamespace:
return XmlNamespace.WSAddressing;
default:
return XmlNamespace.NotSpecified;
}
}
/// <summary>
/// Creates EWS object based on XML element name.
/// </summary>
/// <typeparam name="TServiceObject">The type of the service object.</typeparam>
/// <param name="service">The service.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Service object.</returns>
internal static TServiceObject CreateEwsObjectFromXmlElementName<TServiceObject>(ExchangeService service, string xmlElementName)
where TServiceObject : ServiceObject
{
Type itemClass;
if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))
{
CreateServiceObjectWithServiceParam creationDelegate;
if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithServiceParam.TryGetValue(itemClass, out creationDelegate))
{
return (TServiceObject)creationDelegate(service);
}
else
{
throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);
}
}
else
{
return default(TServiceObject);
}
}
/// <summary>
/// Creates Item from Item class.
/// </summary>
/// <param name="itemAttachment">The item attachment.</param>
/// <param name="itemClass">The item class.</param>
/// <param name="isNew">If true, item attachment is new.</param>
/// <returns>New Item.</returns>
internal static Item CreateItemFromItemClass(
ItemAttachment itemAttachment,
Type itemClass,
bool isNew)
{
CreateServiceObjectWithAttachmentParam creationDelegate;
if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithAttachmentParam.TryGetValue(itemClass, out creationDelegate))
{
return (Item)creationDelegate(itemAttachment, isNew);
}
else
{
throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);
}
}
/// <summary>
/// Creates Item based on XML element name.
/// </summary>
/// <param name="itemAttachment">The item attachment.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>New Item.</returns>
internal static Item CreateItemFromXmlElementName(ItemAttachment itemAttachment, string xmlElementName)
{
Type itemClass;
if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))
{
return CreateItemFromItemClass(itemAttachment, itemClass, false);
}
else
{
return null;
}
}
/// <summary>
/// Gets the expected item type based on the local name.
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static Type GetItemTypeFromXmlElementName(string xmlElementName)
{
Type itemClass = null;
EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass);
return itemClass;
}
/// <summary>
/// Finds the first item of type TItem (not a descendant type) in the specified collection.
/// </summary>
/// <typeparam name="TItem">The type of the item to find.</typeparam>
/// <param name="items">The collection.</param>
/// <returns>A TItem instance or null if no instance of TItem could be found.</returns>
internal static TItem FindFirstItemOfType<TItem>(IEnumerable<Item> items)
where TItem : Item
{
Type itemType = typeof(TItem);
foreach (Item item in items)
{
// We're looking for an exact class match here.
if (item.GetType() == itemType)
{
return (TItem)item;
}
}
return null;
}
#region Tracing routines
/// <summary>
/// Write trace start element.
/// </summary>
/// <param name="writer">The writer to write the start element to.</param>
/// <param name="traceTag">The trace tag.</param>
/// <param name="includeVersion">If true, include build version attribute.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Exchange.Usage", "EX0009:DoNotUseDateTimeNowOrFromFileTime", Justification = "Client API")]
private static void WriteTraceStartElement(
XmlWriter writer,
string traceTag,
bool includeVersion)
{
writer.WriteStartElement("Trace");
writer.WriteAttributeString("Tag", traceTag);
writer.WriteAttributeString("Tid", Thread.CurrentThread.ManagedThreadId.ToString());
writer.WriteAttributeString("Time", DateTime.UtcNow.ToString("u", DateTimeFormatInfo.InvariantInfo));
if (includeVersion)
{
writer.WriteAttributeString("Version", EwsUtilities.BuildVersion);
}
}
/// <summary>
/// Format log message.
/// </summary>
/// <param name="entryKind">Kind of the entry.</param>
/// <param name="logEntry">The log entry.</param>
/// <returns>XML log entry as a string.</returns>
internal static string FormatLogMessage(string entryKind, string logEntry)
{
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, false);
xmlWriter.WriteWhitespace(Environment.NewLine);
xmlWriter.WriteValue(logEntry);
xmlWriter.WriteWhitespace(Environment.NewLine);
xmlWriter.WriteEndElement(); // Trace
xmlWriter.WriteWhitespace(Environment.NewLine);
}
}
return sb.ToString();
}
/// <summary>
/// Format the HTTP headers.
/// </summary>
/// <param name="sb">StringBuilder.</param>
/// <param name="headers">The HTTP headers.</param>
private static void FormatHttpHeaders(StringBuilder sb, WebHeaderCollection headers)
{
foreach (string key in headers.Keys)
{
sb.Append(
string.Format(
"{0}: {1}\n",
key,
headers[key]));
}
}
/// <summary>
/// Format request HTTP headers.
/// </summary>
/// <param name="request">The HTTP request.</param>
internal static string FormatHttpRequestHeaders(IEwsHttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("{0} {1} HTTP/1.1\n", request.Method, request.RequestUri.AbsolutePath));
EwsUtilities.FormatHttpHeaders(sb, request.Headers);
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Format response HTTP headers.
/// </summary>
/// <param name="response">The HTTP response.</param>
internal static string FormatHttpResponseHeaders(IEwsHttpWebResponse response)
{
StringBuilder sb = new StringBuilder();
sb.Append(
string.Format(
"HTTP/{0} {1} {2}\n",
response.ProtocolVersion,
(int)response.StatusCode,
response.StatusDescription));
sb.Append(EwsUtilities.FormatHttpHeaders(response.Headers));
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Format request HTTP headers.
/// </summary>
/// <param name="request">The HTTP request.</param>
internal static string FormatHttpRequestHeaders(HttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
sb.Append(
string.Format(
"{0} {1} HTTP/{2}\n",
request.Method.ToUpperInvariant(),
request.RequestUri.AbsolutePath,
request.ProtocolVersion));
sb.Append(EwsUtilities.FormatHttpHeaders(request.Headers));
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Formats HTTP headers.
/// </summary>
/// <param name="headers">The headers.</param>
/// <returns>Headers as a string</returns>
private static string FormatHttpHeaders(WebHeaderCollection headers)
{
StringBuilder sb = new StringBuilder();
foreach (string key in headers.Keys)
{
sb.Append(
string.Format(
"{0}: {1}\n",
key,
headers[key]));
}
return sb.ToString();
}
/// <summary>
/// Format XML content in a MemoryStream for message.
/// </summary>
/// <param name="entryKind">Kind of the entry.</param>
/// <param name="memoryStream">The memory stream.</param>
/// <returns>XML log entry as a string.</returns>
internal static string FormatLogMessageWithXmlContent(string entryKind, MemoryStream memoryStream)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
settings.CloseInput = false;
// Remember the current location in the MemoryStream.
long lastPosition = memoryStream.Position;
// Rewind the position since we want to format the entire contents.
memoryStream.Position = 0;
try
{
using (XmlReader reader = XmlReader.Create(memoryStream, settings))
{
using (StringWriter writer = new StringWriter(sb))
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, true);
while (!reader.EOF)
{
xmlWriter.WriteNode(reader, true);
}
xmlWriter.WriteEndElement(); // Trace
xmlWriter.WriteWhitespace(Environment.NewLine);
}
}
}
}
catch (XmlException)
{
// We tried to format the content as "pretty" XML. Apparently the content is
// not well-formed XML or isn't XML at all. Fallback and treat it as plain text.
sb.Length = 0;
memoryStream.Position = 0;
sb.Append(Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
}
// Restore Position in the stream.
memoryStream.Position = lastPosition;
return sb.ToString();
}
#endregion
#region Stream routines
/// <summary>
/// Copies source stream to target.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
internal static void CopyStream(Stream source, Stream target)
{
// See if this is a MemoryStream -- we can use WriteTo.
MemoryStream memContentStream = source as MemoryStream;
if (memContentStream != null)
{
memContentStream.WriteTo(target);
}
else
{
// Otherwise, copy data through a buffer
byte[] buffer = new byte[4096];
int bufferSize = buffer.Length;
int bytesRead = source.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
target.Write(buffer, 0, bytesRead);
bytesRead = source.Read(buffer, 0, bufferSize);
}
}
}
#endregion
/// <summary>
/// Gets the build version.
/// </summary>
/// <value>The build version.</value>
internal static string BuildVersion
{
get { return EwsUtilities.buildVersion.Member; }
}
#region Conversion routines
/// <summary>
/// Convert bool to XML Schema bool.
/// </summary>
/// <param name="value">Bool value.</param>
/// <returns>String representing bool value in XML Schema.</returns>
internal static string BoolToXSBool(bool value)
{
return value ? EwsUtilities.XSTrue : EwsUtilities.XSFalse;
}
/// <summary>
/// Parses an enum value list.
/// </summary>
/// <typeparam name="T">Type of value.</typeparam>
/// <param name="list">The list.</param>
/// <param name="value">The value.</param>
/// <param name="separators">The separators.</param>
internal static void ParseEnumValueList<T>(
IList<T> list,
string value,
params char[] separators)
where T : struct
{
EwsUtilities.Assert(
typeof(T).IsEnum,
"EwsUtilities.ParseEnumValueList",
"T is not an enum type.");
if (string.IsNullOrEmpty(value))
{
return;
}
string[] enumValues = value.Split(separators);
foreach (string enumValue in enumValues)
{
list.Add((T)Enum.Parse(typeof(T), enumValue, false));
}
}
/// <summary>
/// Converts an enum to a string, using the mapping dictionaries if appropriate.
/// </summary>
/// <param name="value">The enum value to be serialized</param>
/// <returns>String representation of enum to be used in the protocol</returns>
internal static string SerializeEnum(Enum value)
{
Dictionary<Enum, string> enumToStringDict;
string strValue;
if (enumToSchemaDictionaries.Member.TryGetValue(value.GetType(), out enumToStringDict) &&
enumToStringDict.TryGetValue(value, out strValue))
{
return strValue;
}
else
{
return value.ToString();
}
}
/// <summary>
/// Parses specified value based on type.
/// </summary>
/// <typeparam name="T">Type of value.</typeparam>
/// <param name="value">The value.</param>
/// <returns>Value of type T.</returns>
internal static T Parse<T>(string value)
{
if (typeof(T).IsEnum)
{
Dictionary<string, Enum> stringToEnumDict;
Enum enumValue;
if (schemaToEnumDictionaries.Member.TryGetValue(typeof(T), out stringToEnumDict) &&
stringToEnumDict.TryGetValue(value, out enumValue))
{
// This double-casting is ugly, but necessary. By this point, we know that T is an Enum
// (same as returned by the dictionary), but the compiler can't prove it. Thus, the
// up-cast before we can down-cast.
return (T)((object)enumValue);
}
else
{
return (T)Enum.Parse(typeof(T), value, false);
}
}
else
{
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Tries to parses the specified value to the specified type.
/// </summary>
/// <typeparam name="T">The type into which to cast the provided value.</typeparam>
/// <param name="value">The value to parse.</param>
/// <param name="result">The value cast to the specified type, if TryParse succeeds. Otherwise, the value of result is indeterminate.</param>
/// <returns>True if value could be parsed; otherwise, false.</returns>
internal static bool TryParse<T>(string value, out T result)
{
try
{
result = EwsUtilities.Parse<T>(value);
return true;
}
//// Catch all exceptions here, we're not interested in the reason why TryParse failed.
catch (Exception)
{
result = default(T);
return false;
}
}
/// <summary>
/// Converts the specified date and time from one time zone to another.
/// </summary>
/// <param name="dateTime">The date time to convert.</param>
/// <param name="sourceTimeZone">The source time zone.</param>
/// <param name="destinationTimeZone">The destination time zone.</param>
/// <returns>A DateTime that holds the converted</returns>
internal static DateTime ConvertTime(
DateTime dateTime,
TimeZoneInfo sourceTimeZone,
TimeZoneInfo destinationTimeZone)
{
try
{
return TimeZoneInfo.ConvertTime(
dateTime,
sourceTimeZone,
destinationTimeZone);
}
catch (ArgumentException e)
{
throw new TimeZoneConversionException(
string.Format(
Strings.CannotConvertBetweenTimeZones,
EwsUtilities.DateTimeToXSDateTime(dateTime),
sourceTimeZone.DisplayName,
destinationTimeZone.DisplayName),
e);
}
}
/// <summary>
/// Reads the string as date time, assuming it is unbiased (e.g. 2009/01/01T08:00)
/// and scoped to service's time zone.
/// </summary>
/// <param name="dateString">The date string.</param>
/// <param name="service">The service.</param>
/// <returns>The string's value as a DateTime object.</returns>
internal static DateTime ParseAsUnbiasedDatetimescopedToServicetimeZone(string dateString, ExchangeService service)
{
// Convert the element's value to a DateTime with no adjustment.
DateTime tempDate = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
// Set the kind according to the service's time zone
if (service.TimeZone == TimeZoneInfo.Utc)
{
return new DateTime(tempDate.Ticks, DateTimeKind.Utc);
}
else if (EwsUtilities.IsLocalTimeZone(service.TimeZone))
{
return new DateTime(tempDate.Ticks, DateTimeKind.Local);
}
else
{
return new DateTime(tempDate.Ticks, DateTimeKind.Unspecified);
}
}
/// <summary>
/// Determines whether the specified time zone is the same as the system's local time zone.
/// </summary>
/// <param name="timeZone">The time zone to check.</param>
/// <returns>
/// <c>true</c> if the specified time zone is the same as the system's local time zone; otherwise, <c>false</c>.
/// </returns>
internal static bool IsLocalTimeZone(TimeZoneInfo timeZone)
{
return (TimeZoneInfo.Local == timeZone) || (TimeZoneInfo.Local.Id == timeZone.Id && TimeZoneInfo.Local.HasSameRules(timeZone));
}
/// <summary>
/// Convert DateTime to XML Schema date.
/// </summary>
/// <param name="date">The date to be converted.</param>
/// <returns>String representation of DateTime.</returns>
internal static string DateTimeToXSDate(DateTime date)
{
// Depending on the current culture, DateTime formatter will
// translate dates from one culture to another (e.g. Gregorian to Lunar). The server
// however, considers all dates to be in Gregorian, so using the InvariantCulture will
// ensure this.
string format;
switch (date.Kind)
{
case DateTimeKind.Utc:
format = "yyyy-MM-ddZ";
break;
case DateTimeKind.Unspecified:
format = "yyyy-MM-dd";
break;
default: // DateTimeKind.Local is remaining
format = "yyyy-MM-ddzzz";
break;
}
return date.ToString(format, CultureInfo.InvariantCulture);
}
/// <summary>
/// Dates the DateTime into an XML schema date time.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns>String representation of DateTime.</returns>
internal static string DateTimeToXSDateTime(DateTime dateTime)
{
string format = "yyyy-MM-ddTHH:mm:ss.fff";
switch (dateTime.Kind)
{
case DateTimeKind.Utc:
format += "Z";
break;
case DateTimeKind.Local:
format += "zzz";
break;
default:
break;
}
// Depending on the current culture, DateTime formatter will replace ':' with
// the DateTimeFormatInfo.TimeSeparator property which may not be ':'. Force the proper string
// to be used by using the InvariantCulture.
return dateTime.ToString(format, CultureInfo.InvariantCulture);
}
/// <summary>
/// Convert EWS DayOfTheWeek enum to System.DayOfWeek.
/// </summary>
/// <param name="dayOfTheWeek">The day of the week.</param>
/// <returns>System.DayOfWeek value.</returns>
internal static DayOfWeek EwsToSystemDayOfWeek(DayOfTheWeek dayOfTheWeek)
{
if (dayOfTheWeek == DayOfTheWeek.Day ||
dayOfTheWeek == DayOfTheWeek.Weekday ||
dayOfTheWeek == DayOfTheWeek.WeekendDay)
{
throw new ArgumentException(
string.Format("Cannot convert {0} to System.DayOfWeek enum value", dayOfTheWeek),
"dayOfTheWeek");
}
else
{
return (DayOfWeek)dayOfTheWeek;
}
}
/// <summary>
/// Convert System.DayOfWeek type to EWS DayOfTheWeek.
/// </summary>
/// <param name="dayOfWeek">The dayOfWeek.</param>
/// <returns>EWS DayOfWeek value</returns>
internal static DayOfTheWeek SystemToEwsDayOfTheWeek(DayOfWeek dayOfWeek)
{
return (DayOfTheWeek)dayOfWeek;
}
/// <summary>
/// Takes a System.TimeSpan structure and converts it into an
/// xs:duration string as defined by the W3 Consortiums Recommendation
/// "XML Schema Part 2: Datatypes Second Edition",
/// http://www.w3.org/TR/xmlschema-2/#duration
/// </summary>
/// <param name="timeSpan">TimeSpan structure to convert</param>
/// <returns>xs:duration formatted string</returns>
internal static string TimeSpanToXSDuration(TimeSpan timeSpan)
{
// Optional '-' offset
string offsetStr = (timeSpan.TotalSeconds < 0) ? "-" : string.Empty;
// The TimeSpan structure does not have a Year or Month
// property, therefore we wouldn't be able to return an xs:duration
// string from a TimeSpan that included the nY or nM components.
return String.Format(
"{0}P{1}DT{2}H{3}M{4}S",
offsetStr,
Math.Abs(timeSpan.Days),
Math.Abs(timeSpan.Hours),
Math.Abs(timeSpan.Minutes),
Math.Abs(timeSpan.Seconds) + "." + Math.Abs(timeSpan.Milliseconds));
}
/// <summary>
/// Takes an xs:duration string as defined by the W3 Consortiums
/// Recommendation "XML Schema Part 2: Datatypes Second Edition",
/// http://www.w3.org/TR/xmlschema-2/#duration, and converts it
/// into a System.TimeSpan structure
/// </summary>
/// <remarks>
/// This method uses the following approximations:
/// 1 year = 365 days
/// 1 month = 30 days
/// Additionally, it only allows for four decimal points of
/// seconds precision.
/// </remarks>
/// <param name="xsDuration">xs:duration string to convert</param>
/// <returns>System.TimeSpan structure</returns>
internal static TimeSpan XSDurationToTimeSpan(string xsDuration)
{
Regex timeSpanParser = new Regex(
"(?<pos>-)?" +
"P" +
"((?<year>[0-9]+)Y)?" +
"((?<month>[0-9]+)M)?" +
"((?<day>[0-9]+)D)?" +
"(T" +
"((?<hour>[0-9]+)H)?" +
"((?<minute>[0-9]+)M)?" +
"((?<seconds>[0-9]+)(\\.(?<precision>[0-9]+))?S)?)?");
Match m = timeSpanParser.Match(xsDuration);
if (!m.Success)
{
throw new ArgumentException(Strings.XsDurationCouldNotBeParsed);
}
string token = m.Result("${pos}");
bool negative = false;
if (!String.IsNullOrEmpty(token))
{
negative = true;
}
// Year
token = m.Result("${year}");
int year = 0;
if (!String.IsNullOrEmpty(token))
{
year = Int32.Parse(token);
}
// Month
token = m.Result("${month}");
int month = 0;
if (!String.IsNullOrEmpty(token))
{
month = Int32.Parse(token);
}
// Day
token = m.Result("${day}");
int day = 0;
if (!String.IsNullOrEmpty(token))
{
day = Int32.Parse(token);
}
// Hour
token = m.Result("${hour}");
int hour = 0;