File size: 39,184 Bytes
8c763fb | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Reflection;
using System.Xml;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// This class provides functionality for serializing a PSObject.
/// </summary>
internal sealed class CustomSerialization
{
#region constructor
/// <summary>
/// Depth of serialization.
/// </summary>
private readonly int _depth;
/// <summary>
/// XmlWriter to be used for writing.
/// </summary>
private readonly XmlWriter _writer;
/// <summary>
/// Whether type information should be included in the xml.
/// </summary>
private readonly bool _notypeinformation;
/// <summary>
/// CustomerSerializer used for formatting the output for _writer.
/// </summary>
private CustomInternalSerializer _serializer;
/// <summary>
/// Initializes a new instance of the <see cref="CustomSerialization"/> class.
/// </summary>
/// <param name="writer">
/// writer to be used for serialization.
/// </param>
/// <param name="notypeinformation">
/// should the type information to be shown.
/// </param>
/// <param name="depth">
/// depth to be used for serialization. If this value is specified,
/// depth from types.xml is not used.
/// </param>
internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth)
{
if (writer == null)
{
throw PSTraceSource.NewArgumentException(nameof(writer));
}
if (depth < 1)
{
throw PSTraceSource.NewArgumentException(nameof(writer), Serialization.DepthOfOneRequired);
}
_depth = depth;
_writer = writer;
_notypeinformation = notypeinformation;
_serializer = null;
}
/// <summary>
/// Default depth of serialization.
/// </summary>
public static int MshDefaultSerializationDepth { get; } = 1;
/// <summary>
/// Initializes a new instance of the <see cref="CustomSerialization"/> class.
/// </summary>
/// <param name="writer">
/// writer to be used for serialization.
/// </param>
/// <param name="notypeinformation">
/// should the type information to be shown.
/// </param>
internal CustomSerialization(XmlWriter writer, bool notypeinformation)
: this(writer, notypeinformation, MshDefaultSerializationDepth)
{
}
#endregion constructor
#region public methods
private bool _firstCall = true;
/// <summary>
/// Serializes passed in object.
/// </summary>
/// <param name="source">
/// Object to be serialized.
/// </param>
internal void Serialize(object source)
{
// Write the root element tag before writing first object.
if (_firstCall)
{
_firstCall = false;
Start();
}
_serializer = new CustomInternalSerializer
(
_writer,
_notypeinformation,
true
);
_serializer.WriteOneObject(source, null, _depth);
_serializer = null;
}
/// <summary>
/// Serializes passed in object.
/// </summary>
/// <param name="source">
/// Object to be serialized.
/// </param>
internal void SerializeAsStream(object source)
{
_serializer = new CustomInternalSerializer
(
_writer,
_notypeinformation,
true
);
_serializer.WriteOneObject(source, null, _depth);
_serializer = null;
}
/// <summary>
/// Writes the start of root element.
/// </summary>
private void Start()
{
CustomInternalSerializer.WriteStartElement(_writer, CustomSerializationStrings.RootElementTag);
}
/// <summary>
/// Write the end of root element.
/// </summary>
internal void Done()
{
if (_firstCall)
{
_firstCall = false;
Start();
}
_writer.WriteEndElement();
_writer.Flush();
}
/// <summary>
/// Flush the writer.
/// </summary>
internal void DoneAsStream()
{
_writer.Flush();
}
internal void Stop()
{
CustomInternalSerializer serializer = _serializer;
serializer?.Stop();
}
#endregion
}
/// <summary>
/// This internal helper class provides methods for serializing mshObject.
/// </summary>
internal sealed class CustomInternalSerializer
{
#region constructor
/// <summary>
/// Xml writer to be used.
/// </summary>
private readonly XmlWriter _writer;
/// <summary>
/// Check first call for every pipeline object to write Object tag else property tag.
/// </summary>
private bool _firstcall;
/// <summary>
/// Should the type information to be shown.
/// </summary>
private readonly bool _notypeinformation;
/// <summary>
/// Check object call.
/// </summary>
private bool _firstobjectcall = true;
/// <summary>
/// Initializes a new instance of the <see cref="CustomInternalSerializer"/> class.
/// </summary>
/// <param name="writer">
/// Xml writer to be used.
/// </param>
/// <param name="notypeinformation">
/// Xml writer to be used.
/// </param>
/// <param name="isfirstcallforObject">
/// Check first call for every pipeline object to write Object tag else property tag.
/// </param>
internal CustomInternalSerializer(XmlWriter writer, bool notypeinformation, bool isfirstcallforObject)
{
Dbg.Assert(writer != null, "caller should validate the parameter");
_writer = writer;
_notypeinformation = notypeinformation;
_firstcall = isfirstcallforObject;
}
#endregion
#region Stopping
private bool _isStopping = false;
/// <summary>
/// Called from a separate thread will stop the serialization process.
/// </summary>
internal void Stop()
{
_isStopping = true;
}
private void CheckIfStopping()
{
if (_isStopping)
{
throw PSTraceSource.NewInvalidOperationException(Serialization.Stopping);
}
}
#endregion Stopping
/// <summary>
/// This writes one object.
/// </summary>
/// <param name="source">
/// source to be serialized.
/// </param>
/// <param name="property">
/// name of property. If null, name attribute is not written.
/// </param>
/// <param name="depth">
/// depth to which this object should be serialized.
/// </param>
internal void WriteOneObject(object source, string property, int depth)
{
Dbg.Assert(depth >= 0, "depth should always be greater or equal to zero");
CheckIfStopping();
if (source == null)
{
WriteNull(property);
return;
}
if (HandlePrimitiveKnownType(source, property))
{
return;
}
if (HandlePrimitiveKnownTypePSObject(source, property, depth))
{
return;
}
// Note: We donot use containers in depth calculation. i.e even if the
// current depth is zero, we serialize the container. All contained items will
// get serialized with depth zero.
if (HandleKnownContainerTypes(source, property, depth))
{
return;
}
PSObject mshSource = PSObject.AsPSObject(source);
// If depth is zero, complex type should be serialized as string.
if (depth == 0 || SerializeAsString(mshSource))
{
HandlePSObjectAsString(mshSource, property, depth);
return;
}
HandleComplexTypePSObject(mshSource, property, depth);
return;
}
/// <summary>
/// Serializes Primitive Known Types.
/// </summary>
/// <returns>
/// true if source is handled, else false.
/// </returns>
private bool HandlePrimitiveKnownType(object source, string property)
{
Dbg.Assert(source != null, "caller should validate the parameter");
// Check if source is of primitive known type
TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType());
if (pktInfo != null)
{
WriteOnePrimitiveKnownType(_writer, property, source, pktInfo);
return true;
}
return false;
}
/// <summary>
/// Serializes PSObject whose base objects are of primitive known type.
/// </summary>
/// <param name="source"></param>
/// <param name="property"></param>
/// <param name="depth"></param>
/// <returns>
/// true if source is handled, else false.
/// </returns>
private bool HandlePrimitiveKnownTypePSObject(object source, string property, int depth)
{
Dbg.Assert(source != null, "caller should validate the parameter");
bool sourceHandled = false;
if (source is PSObject moSource && !moSource.ImmediateBaseObjectIsEmpty)
{
// Check if baseObject is primitive known type
object baseObject = moSource.ImmediateBaseObject;
TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType());
if (pktInfo != null)
{
WriteOnePrimitiveKnownType(_writer, property, baseObject, pktInfo);
sourceHandled = true;
}
}
return sourceHandled;
}
private bool HandleKnownContainerTypes(object source, string property, int depth)
{
Dbg.Assert(source != null, "caller should validate the parameter");
ContainerType ct = ContainerType.None;
PSObject mshSource = source as PSObject;
IEnumerable enumerable = null;
IDictionary dictionary = null;
// If passed in object is PSObject with no baseobject, return false.
if (mshSource != null && mshSource.ImmediateBaseObjectIsEmpty)
{
return false;
}
// Check if source (or baseobject in mshSource) is known container type
GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct,
out dictionary, out enumerable);
if (ct == ContainerType.None)
return false;
WriteStartOfPSObject(mshSource ?? PSObject.AsPSObject(source), property, true);
switch (ct)
{
case ContainerType.Dictionary:
{
WriteDictionary(dictionary, depth);
}
break;
case ContainerType.Stack:
case ContainerType.Queue:
case ContainerType.List:
case ContainerType.Enumerable:
{
WriteEnumerable(enumerable, depth);
}
break;
default:
{
Dbg.Assert(false, "All containers should be handled in the switch");
}
break;
}
// An object which is original enumerable becomes an PSObject
// with arraylist on deserialization. So on roundtrip it will show up
// as List.
// We serialize properties of enumerable and on deserialization mark the object
// as Deserialized. So if object is marked deserialized, we should write properties.
// Note: we do not serialize the properties of IEnumerable if depth is zero.
if (depth != 0 && (ct == ContainerType.Enumerable || (mshSource != null && mshSource.IsDeserialized)))
{
// Note:Depth is the depth for serialization of baseObject.
// Depth for serialization of each property is one less.
WritePSObjectProperties(PSObject.AsPSObject(source), depth);
}
// If source is PSObject, serialize notes
if (mshSource != null)
{
// Serialize instanceMembers
PSMemberInfoCollection<PSMemberInfo> instanceMembers = mshSource.InstanceMembers;
if (instanceMembers != null)
{
WriteMemberInfoCollection(instanceMembers, depth, true);
}
}
_writer.WriteEndElement();
return true;
}
/// <summary>
/// Checks if source is known container type and returns appropriate information.
/// </summary>
/// <param name="source"></param>
/// <param name="ct"></param>
/// <param name="dictionary"></param>
/// <param name="enumerable"></param>
private static void GetKnownContainerTypeInfo(
object source, out ContainerType ct, out IDictionary dictionary, out IEnumerable enumerable)
{
Dbg.Assert(source != null, "caller should validate the parameter");
ct = ContainerType.None;
dictionary = null;
enumerable = null;
dictionary = source as IDictionary;
if (dictionary != null)
{
ct = ContainerType.Dictionary;
return;
}
if (source is Stack)
{
ct = ContainerType.Stack;
enumerable = LanguagePrimitives.GetEnumerable(source);
Dbg.Assert(enumerable != null, "Stack is enumerable");
}
else if (source is Queue)
{
ct = ContainerType.Queue;
enumerable = LanguagePrimitives.GetEnumerable(source);
Dbg.Assert(enumerable != null, "Queue is enumerable");
}
else if (source is IList)
{
ct = ContainerType.List;
enumerable = LanguagePrimitives.GetEnumerable(source);
Dbg.Assert(enumerable != null, "IList is enumerable");
}
else
{
Type gt = source.GetType();
if (gt.GetTypeInfo().IsGenericType)
{
if (DerivesFromGenericType(gt, typeof(Stack<>)))
{
ct = ContainerType.Stack;
enumerable = LanguagePrimitives.GetEnumerable(source);
Dbg.Assert(enumerable != null, "Stack is enumerable");
}
else if (DerivesFromGenericType(gt, typeof(Queue<>)))
{
ct = ContainerType.Queue;
enumerable = LanguagePrimitives.GetEnumerable(source);
Dbg.Assert(enumerable != null, "Queue is enumerable");
}
else if (DerivesFromGenericType(gt, typeof(List<>)))
{
ct = ContainerType.List;
enumerable = LanguagePrimitives.GetEnumerable(source);
Dbg.Assert(enumerable != null, "Queue is enumerable");
}
}
}
// Check if type is IEnumerable
if (ct == ContainerType.None)
{
enumerable = LanguagePrimitives.GetEnumerable(source);
if (enumerable != null)
{
ct = ContainerType.Enumerable;
}
}
}
/// <summary>
/// Checks if derived is of type baseType or a type derived from baseType.
/// </summary>
/// <param name="derived"></param>
/// <param name="baseType"></param>
/// <returns></returns>
private static bool DerivesFromGenericType(Type derived, Type baseType)
{
Dbg.Assert(derived != null, "caller should validate the parameter");
Dbg.Assert(baseType != null, "caller should validate the parameter");
while (derived != null)
{
if (derived.GetTypeInfo().IsGenericType)
derived = derived.GetGenericTypeDefinition();
if (derived == baseType)
{
return true;
}
derived = derived.GetTypeInfo().BaseType;
}
return false;
}
#region Write PSObject
/// <summary>
/// Serializes an PSObject whose baseobject is of primitive type.
/// and which has notes.
/// </summary>
/// <param name="source">
/// Source from which notes are written.
/// </param>
/// <param name="primitive">
/// primitive object which is written as base object. In most cases it
/// is same source.ImmediateBaseObject. When PSObject is serialized as string,
/// it can be different. <see cref="HandlePSObjectAsString"/> for more info.
/// </param>
/// <param name="pktInfo">
/// TypeSerializationInfo for the primitive.
/// </param>
/// <param name="property"></param>
/// <param name="depth"></param>
private void WritePrimitiveTypePSObjectWithNotes(
PSObject source,
object primitive,
TypeSerializationInfo pktInfo,
string property,
int depth)
{
Dbg.Assert(source != null, "caller should validate the parameter");
// Write start of PSObject. Since baseobject is primitive known
// type, we do not need TypeName information.
WriteStartOfPSObject(source, property, source.ToStringFromDeserialization != null);
if (pktInfo != null)
{
WriteOnePrimitiveKnownType(_writer, null, primitive, pktInfo);
}
// Serialize instanceMembers
PSMemberInfoCollection<PSMemberInfo> instanceMembers = source.InstanceMembers;
if (instanceMembers != null)
{
WriteMemberInfoCollection(instanceMembers, depth, true);
}
_writer.WriteEndElement();
}
private void HandleComplexTypePSObject(PSObject source, string property, int depth)
{
Dbg.Assert(source != null, "caller should validate the parameter");
WriteStartOfPSObject(source, property, true);
// Figure out what kind of object we are dealing with
bool isEnum = false;
bool isPSObject = false;
if (!source.ImmediateBaseObjectIsEmpty)
{
isEnum = source.ImmediateBaseObject is Enum;
isPSObject = source.ImmediateBaseObject is PSObject;
}
if (isEnum)
{
object baseObject = source.ImmediateBaseObject;
foreach (PSPropertyInfo prop in source.Properties)
{
WriteOneObject(System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), prop.Name, depth);
}
}
else if (isPSObject)
{
if (_firstobjectcall)
{
_firstobjectcall = false;
WritePSObjectProperties(source, depth);
}
else
{
WriteOneObject(source.ImmediateBaseObject, null, depth);
}
}
else
{
WritePSObjectProperties(source, depth);
}
_writer.WriteEndElement();
}
/// <summary>
/// Writes start element, attributes and typeNames for PSObject.
/// </summary>
/// <param name="mshObject"></param>
/// <param name="property"></param>
/// <param name="writeTNH">
/// if true, TypeName information is written, else not.
/// </param>
private void WriteStartOfPSObject(
PSObject mshObject,
string property,
bool writeTNH)
{
Dbg.Assert(mshObject != null, "caller should validate the parameter");
if (property != null)
{
WriteStartElement(_writer, CustomSerializationStrings.Properties);
WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property);
}
else
{
if (_firstcall)
{
WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag);
_firstcall = false;
}
else
{
WriteStartElement(_writer, CustomSerializationStrings.Properties);
}
}
object baseObject = mshObject.BaseObject;
if (!_notypeinformation)
WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, baseObject.GetType().ToString());
}
#region membersets
/// <summary>
/// Returns true if PSObject has notes.
/// </summary>
/// <param name="source"></param>
/// <returns>
/// </returns>
private static bool PSObjectHasNotes(PSObject source)
{
if (source.InstanceMembers != null && source.InstanceMembers.Count > 0)
{
return true;
}
return false;
}
/// <summary>
/// Serialize member set. This method serializes without writing.
/// enclosing tags and attributes.
/// </summary>
/// <param name="me">
/// Enumerable containing members
/// </param>
/// <param name="depth"></param>
/// <param name="writeEnclosingMemberSetElementTag">
/// if this is true, write an enclosing "<memberset></memberset>" tag.
/// </param>
/// <returns></returns>
private void WriteMemberInfoCollection(
PSMemberInfoCollection<PSMemberInfo> me, int depth, bool writeEnclosingMemberSetElementTag)
{
Dbg.Assert(me != null, "caller should validate the parameter");
foreach (PSMemberInfo info in me)
{
if (!info.ShouldSerialize)
{
continue;
}
if (info is not PSPropertyInfo property)
{
continue;
}
WriteStartElement(_writer, CustomSerializationStrings.Properties);
WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, info.Name);
if (!_notypeinformation)
WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, info.GetType().ToString());
_writer.WriteString(property.Value.ToString());
_writer.WriteEndElement();
}
}
#endregion membersets
#region properties
/// <summary>
/// Serializes properties of PSObject.
/// </summary>
private void WritePSObjectProperties(PSObject source, int depth)
{
Dbg.Assert(source != null, "caller should validate the information");
depth = GetDepthOfSerialization(source, depth);
// Depth available for each property is one less
--depth;
Dbg.Assert(depth >= 0, "depth should be greater or equal to zero");
if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties)
{
PSMemberInfoInternalCollection<PSPropertyInfo> specificProperties = new();
foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null))
{
PSPropertyInfo property = source.Properties[propertyName];
if (property != null)
{
specificProperties.Add(property);
}
}
SerializeProperties(specificProperties, CustomSerializationStrings.Properties, depth);
return;
}
foreach (PSPropertyInfo prop in source.Properties)
{
Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty");
object value = AutomationNull.Value;
// PSObject throws GetValueException if it cannot
// get value for a property.
try
{
value = prop.Value;
}
catch (GetValueException)
{
WritePropertyWithNullValue(_writer, prop, depth);
continue;
}
// Write the property
if (value == null)
{
WritePropertyWithNullValue(_writer, prop, depth);
}
else
{
WriteOneObject(value, prop.Name, depth);
}
}
}
/// <summary>
/// Serializes properties from collection.
/// </summary>
/// <param name="propertyCollection">
/// Collection of properties to serialize.
/// </param>
/// <param name="name">
/// Name for enclosing element tag.
/// </param>
/// <param name="depth">
/// Depth to which each property should be serialized.
/// </param>
private void SerializeProperties(
PSMemberInfoInternalCollection<PSPropertyInfo> propertyCollection, string name, int depth)
{
Dbg.Assert(propertyCollection != null, "caller should validate the parameter");
if (propertyCollection.Count == 0)
return;
foreach (PSMemberInfo info in propertyCollection)
{
PSPropertyInfo prop = info as PSPropertyInfo;
Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty");
object value = AutomationNull.Value;
// PSObject throws GetValueException if it cannot
// get value for a property.
try
{
value = prop.Value;
}
catch (GetValueException)
{
continue;
}
// Write the property
WriteOneObject(value, prop.Name, depth);
}
}
#endregion base properties
#endregion WritePSObject
#region enumerable and dictionary
/// <summary>
/// Serializes IEnumerable.
/// </summary>
/// <param name="enumerable">
/// Enumerable which is serialized.
/// </param>
/// <param name="depth"></param>
private void WriteEnumerable(IEnumerable enumerable, int depth)
{
Dbg.Assert(enumerable != null, "caller should validate the parameter");
IEnumerator enumerator = null;
try
{
enumerator = enumerable.GetEnumerator();
enumerator.Reset();
}
catch (Exception)
{
enumerator = null;
}
// AD has incorrect implementation of IEnumerable where they returned null
// for GetEnumerator instead of empty enumerator
if (enumerator != null)
{
while (true)
{
object item = null;
try
{
if (!enumerator.MoveNext())
{
break;
}
else
{
item = enumerator.Current;
}
}
catch (Exception)
{
break;
}
WriteOneObject(item, null, depth);
}
}
}
/// <summary>
/// Serializes IDictionary.
/// </summary>
/// <param name="dictionary">Dictionary which is serialized.</param>
/// <param name="depth"></param>
private void WriteDictionary(IDictionary dictionary, int depth)
{
IDictionaryEnumerator dictionaryEnum = null;
try
{
dictionaryEnum = (IDictionaryEnumerator)dictionary.GetEnumerator();
}
catch (Exception)
{
}
if (dictionaryEnum != null)
{
while (dictionaryEnum.MoveNext())
{
// Write Key
WriteOneObject(dictionaryEnum.Key, CustomSerializationStrings.DictionaryKey, depth);
// Write Value
WriteOneObject(dictionaryEnum.Value, CustomSerializationStrings.DictionaryValue, depth);
}
}
}
#endregion enumerable and dictionary
#region serialize as string
private void HandlePSObjectAsString(PSObject source, string property, int depth)
{
Dbg.Assert(source != null, "caller should validate the information");
bool hasNotes = PSObjectHasNotes(source);
string value = GetStringFromPSObject(source);
if (value != null)
{
TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType());
Dbg.Assert(pktInfo != null, "TypeSerializationInfo should be present for string");
if (hasNotes)
{
WritePrimitiveTypePSObjectWithNotes(source, value, pktInfo, property, depth);
}
else
{
WriteOnePrimitiveKnownType(_writer, property, source.BaseObject, pktInfo);
}
}
else
{
if (hasNotes)
{
WritePrimitiveTypePSObjectWithNotes(source, null, null, property, depth);
}
else
{
WriteNull(property);
}
}
}
/// <summary>
/// Gets the string from PSObject using the information from
/// types.ps1xml. This string is used for serializing the PSObject.
/// </summary>
/// <param name="source">
/// PSObject to be converted to string.
/// </param>
/// <returns>
/// string value to use for serializing this PSObject.
/// </returns>
private static string GetStringFromPSObject(PSObject source)
{
Dbg.Assert(source != null, "caller should have validated the information");
// check if we have a well known string serialization source
PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null);
string result = null;
if (serializationProperty != null)
{
object val = serializationProperty.Value;
if (val != null)
{
try
{
// if we have a string serialization value, return it
result = val.ToString();
}
catch (Exception)
{
}
}
}
else
{
try
{
// fall back value
result = source.ToString();
}
catch (Exception)
{
}
}
return result;
}
/// <summary>
/// Reads the information the PSObject
/// and returns true if this object should be serialized as string.
/// </summary>
/// <param name="source">PSObject to be serialized.</param>
/// <returns>True if the object needs to be serialized as a string.</returns>
private static bool SerializeAsString(PSObject source)
{
return source.GetSerializationMethod(null) == SerializationMethod.String;
}
#endregion serialize as string
/// <summary>
/// Compute the serialization depth for an PSObject instance subtree.
/// </summary>
/// <param name="source">PSObject whose serialization depth has to be computed.</param>
/// <param name="depth">Current depth.</param>
/// <returns></returns>
private static int GetDepthOfSerialization(PSObject source, int depth)
{
if (source == null)
return depth;
// get the depth from the PSObject
// NOTE: we assume that the depth out of the PSObject is > 0
// else we consider it not set in types.ps1xml
int objectLevelDepth = source.GetSerializationDepth(null);
if (objectLevelDepth <= 0)
{
// no override at the type level
return depth;
}
return objectLevelDepth;
}
/// <summary>
/// Writes null.
/// </summary>
/// <param name="property"></param>
private void WriteNull(string property)
{
if (property != null)
{
WriteStartElement(_writer, CustomSerializationStrings.Properties);
WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property);
}
else
{
if (_firstcall)
{
WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag);
_firstcall = false;
}
else
{
WriteStartElement(_writer, CustomSerializationStrings.Properties);
}
}
_writer.WriteEndElement();
}
#region known type serialization
private void WritePropertyWithNullValue(
XmlWriter writer, PSPropertyInfo source, int depth)
{
WriteStartElement(writer, CustomSerializationStrings.Properties);
WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name);
if (!_notypeinformation)
WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue);
writer.WriteEndElement();
}
private void WriteObjectString(
XmlWriter writer, string property, object source, TypeSerializationInfo entry)
{
if (property != null)
{
WriteStartElement(writer, CustomSerializationStrings.Properties);
WriteAttribute(writer, CustomSerializationStrings.NameAttribute, property);
}
else
{
if (_firstcall)
{
WriteStartElement(writer, CustomSerializationStrings.PSObjectTag);
_firstcall = false;
}
else
{
WriteStartElement(writer, CustomSerializationStrings.Properties);
}
}
if (!_notypeinformation)
WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, source.GetType().ToString());
writer.WriteString(source.ToString());
writer.WriteEndElement();
}
/// <summary>
/// Writes an item or property in Monad namespace.
/// </summary>
/// <param name="writer">The XmlWriter stream to which the object is serialized.</param>
/// <param name="property">Name of property. Pass null for item.</param>
/// <param name="source">Object to be written.</param>
/// <param name="entry">Serialization information about source.</param>
private void WriteOnePrimitiveKnownType(
XmlWriter writer, string property, object source, TypeSerializationInfo entry)
{
WriteObjectString(writer, property, source, entry);
}
#endregion known type serialization
#region misc
/// <summary>
/// Writes start element in Monad namespace.
/// </summary>
/// <param name="writer"></param>
/// <param name="elementTag">Tag of element.</param>
internal static void WriteStartElement(XmlWriter writer, string elementTag)
{
writer.WriteStartElement(elementTag);
}
/// <summary>
/// Writes attribute in monad namespace.
/// </summary>
/// <param name="writer"></param>
/// <param name="name">Name of attribute.</param>
/// <param name="value">Value of attribute.</param>
internal static void WriteAttribute(XmlWriter writer, string name, string value)
{
writer.WriteAttributeString(name, value);
}
#endregion misc
}
}
|