Merge pull request #1736 from atsushieno/import-wcf
authorAtsushi Eno <atsushieno@gmail.com>
Fri, 24 Apr 2015 14:53:38 +0000 (23:53 +0900)
committerAtsushi Eno <atsushieno@gmail.com>
Fri, 24 Apr 2015 14:53:38 +0000 (23:53 +0900)
Import System.Runtime.Serialization from referencesource.

39 files changed:
data/net_4_5/machine.config
mcs/class/Makefile
mcs/class/System.Runtime.Serialization/Makefile
mcs/class/System.Runtime.Serialization/ReferenceSource.common.sources [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSource.desktop.sources [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/BitFlagsGenerator.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/CodeInterpreter.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/DiagnosticUtility.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/FxTrace.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/JsonFormatReaderGenerator_static.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/JsonFormatWriterGenerator_static.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/SR.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/SR_missing.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/SchemaExporter_mobile.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/SimplifiedCodeTypeReference.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/XmlDataContract_static.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/XmlExceptionHelper.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/XmlFormatReaderGenerator_static.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ReferenceSources/XmlFormatWriterGenerator_static.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization.dll.sources
mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XmlObjectSerializerTest.cs
mcs/class/System.Runtime.Serialization/Test/System.Runtime.Serialization/XsdDataContractImporterTest2.cs
mcs/class/System.Runtime.Serialization/Test/System.Xml/XmlMtomDictionaryWriterTest.cs
mcs/class/System.Runtime.Serialization/mobile_System.Runtime.Serialization.dll.sources
mcs/class/System.Runtime.Serialization/net_4_5_System.Runtime.Serialization.dll.sources
mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/AnnouncementClientTest.cs
mcs/class/System.ServiceModel.Internals/Makefile
mcs/class/System.ServiceModel.Web/System.ServiceModel.Channels/WebMessageEncoder.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel.Syndication/SyndicationElementExtensionCollection.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel.Syndication/XmlSyndicationContent.cs
mcs/class/System.ServiceModel.Web/Test/System.Runtime.Serialization.Json/DataContractJsonSerializerTest.cs
mcs/class/System.ServiceModel.Web/Test/System.Runtime.Serialization.Json/JsonReaderTest.cs
mcs/class/System.ServiceModel.Web/Test/System.Runtime.Serialization.Json/JsonWriterTest.cs
mcs/class/System.ServiceModel.Web/mobile_System.ServiceModel.Web.dll.sources
mcs/class/System.ServiceModel/System.ServiceModel.Channels/BinaryMessageEncoder.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/Message.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/MessageDescription.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/WsdlExporter.cs
mcs/class/System.XML/Assembly/AssemblyInfo.cs

index 5d4e12b80b0fb86f361e7eeacc01de9c8e833f32..8f7e56a4facce6876d87fe6238a4dbe43bed3575 100644 (file)
@@ -18,6 +18,9 @@
                <section name="system.windows.forms" type="System.Windows.Forms.WindowsFormsSection, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
                <section name="windows" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false" />
                <section name="strongNames" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false"/>
+               <sectionGroup name="system.runtime.serialization" type="System.Runtime.Serialization.Configuration.SerializationSectionGroup, System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+                       <section name="dataContractSerializer" type="System.Runtime.Serialization.Configuration.DataContractSerializerSection, System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
+               </sectionGroup>
                <sectionGroup name="system.web" type="System.Web.Configuration.SystemWebSectionGroup, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
                        <section name="anonymousIdentification" type="System.Web.Configuration.AnonymousIdentificationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
                        <section name="authentication" type="System.Web.Configuration.AuthenticationSection, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
index 5e3a041c1e2dd789b1567efd256b78e769d16765..ac61daed395b3756fdc55977417a2a82847d3e77 100644 (file)
@@ -118,6 +118,8 @@ net_4_5_dirs := \
        IBM.Data.DB2                    \
        CustomMarshalers                \
        SystemWebTestShim                       \
+       System.ServiceModel.Internals   \
+       SMDiagnostics   \
        System.Runtime.Serialization    \
        System.Xml.Linq                 \
        System.Data.Linq                \
index 88da7618a64f7487fa837b6d2003fc4bf790c560..468cd9f4104c99106c80d7341da39d6d1190115c 100644 (file)
@@ -2,21 +2,21 @@ thisdir = class/System.Runtime.Serialization
 SUBDIRS = 
 include ../../build/rules.make
 
-RESOURCE_FILES = \
-       resources/mstypes.schema
+RESOURCE_FILES =
 
 LIBRARY = System.Runtime.Serialization.dll
-LIB_REFS = System System.Xml System.Core
+LIB_REFS = System System.Xml System.Core System.ServiceModel.Internals SMDiagnostics
 LIB_MCS_FLAGS = \
                -unsafe \
+               -d:NO_DYNAMIC_CODEGEN \
                /nowarn:168,169,219,414 \
                $(RESOURCE_FILES:%=/resource:%)
 
-RESOURCE_STRINGS = ../../../external/referencesource/System.Runtime.Serialization/System.Runtime.Serialization.txt
-
 ifneq (2.1, $(FRAMEWORK_VERSION))
 LIB_REFS += System.Data System.Configuration
 LIB_MCS_FLAGS += /d:NET_3_0
+else
+LIB_MCS_FLAGS += /d:NO_CONFIGURATION /d:NO_SECURITY_ATTRIBUTES /d:NO_CODEDOM /d:NO_DESKTOP_SECURITY
 endif
 
 TEST_RESOURCE_FILES = \
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSource.common.sources b/mcs/class/System.Runtime.Serialization/ReferenceSource.common.sources
new file mode 100644 (file)
index 0000000..8f8e792
--- /dev/null
@@ -0,0 +1,131 @@
+
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/AppSettings.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Attributes.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ClassDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/CollectionDataContractAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/CollectionDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ContractNamespaceAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractResolver.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractSerializer.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractSerializerSettings.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractSet.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataMemberAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataMember.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DateTimeFormat.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DateTimeOffsetAdapter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Diagnostics/TraceCode.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Diagnostics/TraceUtility.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DictionaryGlobals.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/EmitTypeInformation.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/EnumDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/EnumMemberAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ExportOptions.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ExtensionDataObject.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ExtensionDataReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/GenericParameterDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Globals.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/HybridObjectCache.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/IDataContractSurrogate.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/IExtensibleDataObject.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/IgnoreDataMemberAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/InvalidDataContractException.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/ByteArrayHelperWithString.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/DataContractJsonSerializerSettings.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/IXmlJsonReaderInitializer.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/IXmlJsonWriterInitializer.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonClassDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonEnumDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonGlobals.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonNodeType.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonObjectDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonQNameDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonReaderDelegator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonStringDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonUriDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonWriterDelegator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/JsonXmlDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/XmlJsonReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/XmlJsonWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/KnownTypeAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/KnownTypeDataContractResolver.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/NetDataContractSerializer.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ObjectReferenceStack.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ObjectToIdCache.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/PrimitiveDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ScopedKnownTypes.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SerializationMode.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SerializationPermissionNotRequiredAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SerializationTrace.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SpecialTypeDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SurrogateDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/TypeInformation.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlDataContract.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlFormatReaderGenerator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlFormatWriterGenerator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlObjectSerializerContext.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlObjectSerializer.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlReaderDelegator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlSerializableReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlSerializableServices.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlSerializableWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XmlWriterDelegator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XPathQueryGenerator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Text/Base64Encoding.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Text/BinHexEncoding.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Text/SurrogateChar.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/ArrayHelper.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/EncodingStreamWrapper.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/IFragmentCapableXmlDictionaryWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/IStreamProvider.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/IXmlDictionary.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/PrefixHandle.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/StringHandle.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/UniqueID.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/ValueHandle.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBaseReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBaseWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBinaryNodeType.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBinaryReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBinaryReaderSession.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBinaryWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBinaryWriterSession.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlBufferReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlC14NWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlConverter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDelegatedReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDelegatedWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDictionary.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDictionaryReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDictionaryReaderQuotas.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDictionaryString.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlDictionaryWriter.cs
+# ../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlExceptionHelper.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlMtomReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlMtomWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlNodeWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlNodeWriterWriteBase64TextArgs.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlSigningNodeWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlStreamNodeWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlUTF8TextReader.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlUTF8TextWriter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Xml/XmlWriteBase64AsyncArgs.cs
+../../../external/referencesource/System.Runtime.Serialization/TD.Designer.cs
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSource.desktop.sources b/mcs/class/System.Runtime.Serialization/ReferenceSource.desktop.sources
new file mode 100644 (file)
index 0000000..8cc95f1
--- /dev/null
@@ -0,0 +1,29 @@
+
+#include ReferenceSource.common.sources
+
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/ConfigurationStrings.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/DataContractSerializerSection.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/DeclaredTypeElementCollection.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/DeclaredTypeElement.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/DeclaredTypeValidatorAttribute.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/DeclaredTypeValidator.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/NetDataContractSerializerSection.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/ParameterElementCollection.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/ParameterElement.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/Properties.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/SerializationSectionGroup.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/TypeElementCollection.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Configuration/TypeElement.cs
+
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/CodeExporter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ContractCodeDomInfo.cs
+
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ExportOptions.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ImportOptions.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SchemaExporter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SchemaHelper.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/SchemaImporter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XsdDataContractExporter.cs
+../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/XsdDataContractImporter.cs
+
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/BitFlagsGenerator.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/BitFlagsGenerator.cs
new file mode 100644 (file)
index 0000000..73a2f1e
--- /dev/null
@@ -0,0 +1,76 @@
+using System;
+
+namespace System.Runtime.Serialization
+{
+       public class BitFlagsGenerator
+       {
+               int bitCount;
+               byte [] locals;
+               
+               public BitFlagsGenerator (int bitCount)
+               {
+                       this.bitCount = bitCount;
+                       int localCount = (bitCount+7)/8;
+                       locals = new byte [localCount];
+               }
+               
+               public void Store (int bitIndex, bool value)
+               {
+                       if (value)
+                               locals [GetByteIndex (bitIndex)] |= GetBitValue(bitIndex);
+                       else
+                               locals [GetByteIndex (bitIndex)] &= (byte) ~GetBitValue(bitIndex);
+               }
+               
+               public bool Load (int bitIndex)
+               {
+                       var local = locals[GetByteIndex(bitIndex)];
+                       byte bitValue = GetBitValue(bitIndex);
+                       return (local & bitValue) == bitValue;
+               }
+               
+               public byte [] LoadArray ()
+               {
+                       return (byte []) locals.Clone ();
+               }
+               
+               public int GetLocalCount ()
+               {
+                       return locals.Length;
+               }
+               
+               public int GetBitCount ()
+               {
+                       return bitCount;
+               }
+               
+               public byte GetLocal (int i)
+               {
+                       return locals [i];
+               }
+               
+               public static bool IsBitSet (byte[] bytes, int bitIndex)
+               {
+                       int byteIndex = GetByteIndex (bitIndex);
+                       byte bitValue = GetBitValue (bitIndex);
+                       return (bytes[byteIndex] & bitValue) == bitValue;
+               }
+
+               public static void SetBit (byte[] bytes, int bitIndex)
+               {
+                       int byteIndex = GetByteIndex (bitIndex);
+                       byte bitValue = GetBitValue (bitIndex);
+                       bytes[byteIndex] |= bitValue;
+               }
+
+               static int GetByteIndex (int bitIndex)
+               {
+                       return bitIndex >> 3;
+               }
+               
+               static byte GetBitValue (int bitIndex)
+               {
+                       return (byte)(1 << (bitIndex & 7));
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/CodeInterpreter.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/CodeInterpreter.cs
new file mode 100644 (file)
index 0000000..4de29bb
--- /dev/null
@@ -0,0 +1,84 @@
+using System;
+using System.Reflection;
+
+namespace System.Runtime.Serialization
+{
+       public class CodeInterpreter
+       {
+
+               internal static object ConvertValue(object arg, Type source, Type target)
+               {
+                       return InternalConvert(arg, source, target, false);
+               }
+
+
+        static bool CanConvert (TypeCode typeCode)
+        {
+            switch (typeCode)
+            {
+                case TypeCode.Boolean:
+                case TypeCode.Char:
+                case TypeCode.SByte:
+                case TypeCode.Byte:
+                case TypeCode.Int16:
+                case TypeCode.UInt16:
+                case TypeCode.Int32:
+                case TypeCode.UInt32:
+                case TypeCode.Int64:
+                case TypeCode.UInt64:
+                case TypeCode.Single:
+                case TypeCode.Double:
+                                       return true;
+            }
+            return false;
+        }
+
+               static object InternalConvert(object arg, Type source, Type target, bool isAddress)
+               {
+
+            if (target == source)
+                return arg;
+            if (target.IsValueType)
+            {
+                if (source.IsValueType)
+                {
+                    if (!CanConvert (Type.GetTypeCode (target)))
+                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target))));
+                    else
+                                               return target;
+                }
+                else if (source.IsAssignableFrom(target))
+                                       return arg;
+                else
+                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
+            }
+            else if (target.IsAssignableFrom(source))
+                               return arg;
+            else if (source.IsAssignableFrom(target))
+                               return arg;
+            else if (target.IsInterface || source.IsInterface)
+                               return arg;
+            else
+                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
+               }
+
+               public static object GetMember (MemberInfo memberInfo, object instance)
+               {
+                       var pi = memberInfo as PropertyInfo;
+                       if (pi != null)
+                               return pi.GetValue (instance);
+                       else
+                               return ((FieldInfo) memberInfo).GetValue (instance);
+               }
+
+               public static void SetMember (MemberInfo memberInfo, object instance, object value)
+               {
+                       var pi = memberInfo as PropertyInfo;
+                       if (pi != null)
+                               pi.SetValue (instance, value);
+                       else
+                               ((FieldInfo) memberInfo).SetValue (instance, value);
+               }
+       }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/DiagnosticUtility.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/DiagnosticUtility.cs
new file mode 100644 (file)
index 0000000..bcde2c4
--- /dev/null
@@ -0,0 +1,61 @@
+using System.Diagnostics;
+
+namespace System.Runtime.Serialization {
+
+       internal static class DiagnosticUtility {
+               internal static bool ShouldTraceError = true;
+               internal static bool ShouldTraceWarning;
+               internal static bool ShouldTraceInformation;
+               internal static bool ShouldTraceVerbose = true;
+
+               internal static class DiagnosticTrace {
+                       internal static void TraceEvent (params object [] args)
+                       {
+                       }
+                       
+               }
+               
+               internal static class ExceptionUtility {
+                       internal static Exception ThrowHelperError (Exception e)
+                       {
+                               return ThrowHelper (e, TraceEventType.Error);
+                       }
+
+                       internal static Exception ThrowHelperCallback (string msg, Exception e)
+                       {
+                               return new CallbackException (msg, e);
+                       }
+
+                       internal static Exception ThrowHelperCallback (Exception e)
+                       {
+                               return new CallbackException ("Callback exception", e);
+                       }
+
+                       internal static Exception ThrowHelper (Exception e, TraceEventType type)
+                       {
+                               return e;
+                       }
+
+                       internal static Exception ThrowHelperArgument (string arg)
+                       {
+                               return new ArgumentException (arg);
+                       }
+
+                       internal static Exception ThrowHelperArgument (string arg, string message)
+                       {
+                               return new ArgumentException (message, arg);
+                       }
+
+                       internal static Exception ThrowHelperArgumentNull (string arg)
+                       {
+                               return new ArgumentNullException (arg);
+                       }
+
+                       internal static Exception ThrowHelperFatal (string msg, Exception e)
+                       {
+                               return new FatalException (msg, e);
+                       }
+               }
+       }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/FxTrace.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/FxTrace.cs
new file mode 100644 (file)
index 0000000..72e7f97
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// bare-bones based implementation based on the references
+// from the Microsoft reference source code to get things to build
+//
+using System.Runtime;
+using System.Runtime.Diagnostics;
+
+namespace System.Runtime.Serialization {
+       internal static class FxTrace {
+               public static EtwDiagnosticTrace Trace {
+                       get {
+                               return Fx.Trace;
+                       }
+               }
+
+               public static bool ShouldTraceError = true;
+               public static bool ShouldTraceVerbose = true;
+
+               static ExceptionTrace exception;
+               public static ExceptionTrace Exception {
+                       get {
+                               if (exception == null)
+                                       return new ExceptionTrace ("System.Runtime.Serialization", Trace);
+                               return exception;
+                       }
+               }
+
+               public static bool IsEventEnabled (int index)
+               {
+                       return false;
+               }
+
+               public static void UpdateEventDefinitions (EventDescriptor [] ed, ushort [] events) {}
+       }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/JsonFormatReaderGenerator_static.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/JsonFormatReaderGenerator_static.cs
new file mode 100644 (file)
index 0000000..53ad58d
--- /dev/null
@@ -0,0 +1,707 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Runtime;
+using System.Xml;
+
+namespace System.Runtime.Serialization.Json
+{
+       internal partial class JsonFormatReaderGenerator
+       {
+               partial class CriticalHelper
+               {
+                       internal JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
+                       {
+                               return (XmlReaderDelegator xr, XmlObjectSerializerReadContextComplexJson ctx, XmlDictionaryString emptyDictionaryString, XmlDictionaryString [] memberNames) => new JsonFormatReaderInterpreter (classContract).ReadFromJson (xr, ctx, emptyDictionaryString, memberNames);
+                       }
+
+                       internal JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
+                       {
+                               return (XmlReaderDelegator xr, XmlObjectSerializerReadContextComplexJson ctx, XmlDictionaryString emptyDS, XmlDictionaryString inm, CollectionDataContract cc) => new JsonFormatReaderInterpreter (collectionContract, false).ReadCollectionFromJson (xr, ctx, emptyDS, inm, cc);
+                       }
+                       
+                       internal JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
+                       {
+                               return (XmlReaderDelegator xr, XmlObjectSerializerReadContextComplexJson ctx, XmlDictionaryString emptyDS, XmlDictionaryString inm, CollectionDataContract cc) => new JsonFormatReaderInterpreter (collectionContract, true).ReadGetOnlyCollectionFromJson (xr, ctx, emptyDS, inm, cc);
+                       }
+               }
+       }
+
+       class JsonFormatReaderInterpreter
+       {
+               public JsonFormatReaderInterpreter (ClassDataContract classContract)
+               {
+                       this.classContract = classContract;
+               }
+
+               public JsonFormatReaderInterpreter (CollectionDataContract collectionContract, bool isGetOnly)
+               {
+                       this.collectionContract = collectionContract;
+                       this.is_get_only_collection = isGetOnly;
+               }
+
+               bool is_get_only_collection;
+
+               ClassDataContract classContract;
+
+               CollectionDataContract collectionContract;
+
+               object objectLocal;
+               Type objectType;
+               XmlReaderDelegator xmlReader;
+               XmlObjectSerializerReadContextComplexJson context;
+
+               XmlDictionaryString [] memberNames = null;
+               XmlDictionaryString emptyDictionaryString = null;
+               XmlDictionaryString itemName = null;
+               XmlDictionaryString itemNamespace = null;
+
+               public object ReadFromJson (XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames)
+               {
+                       // InitArgs()
+                       this.xmlReader = xmlReader;
+                       this.context = context;
+                       this.emptyDictionaryString = emptyDictionaryString;
+                       this.memberNames = memberNames;
+                       
+                       //DemandSerializationFormatterPermission(classContract);
+                       //DemandMemberAccessPermission(memberAccessFlag);
+                       CreateObject (classContract);
+                       
+                       context.AddNewObject (objectLocal);
+                       InvokeOnDeserializing (classContract);
+            
+            string objectId = null;
+            
+                       if (classContract.IsISerializable)
+                               ReadISerializable (classContract);
+                       else
+                               ReadClass (classContract);
+                       if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom (classContract.UnderlyingType))
+                               ((IDeserializationCallback) objectLocal).OnDeserialization (null);
+                       InvokeOnDeserialized(classContract);
+                       if (!InvokeFactoryMethod (classContract)) {
+
+                               // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization.
+                               // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation
+                               // on DateTimeOffset; which does not work in partial trust.
+
+                               if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
+                                       objectLocal = DateTimeOffsetAdapter.GetDateTimeOffset ((DateTimeOffsetAdapter) objectLocal);
+                               // else - do we have to call CodeInterpreter.ConvertValue()? I guess not...
+                       }
+                       return objectLocal;
+               }
+               
+               public object ReadCollectionFromJson (XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract)
+               {
+                       #region GenerateCollectionReaderHelper
+                       // InitArgs()
+                       this.xmlReader = xmlReader;
+                       this.context = context;
+                       this.emptyDictionaryString = emptyDictionaryString;
+                       this.itemName = itemName;
+
+                       this.collectionContract = collectionContract;
+
+                       #endregion
+
+                       ReadCollection (collectionContract);
+
+                       return objectLocal;
+               }
+               
+               public void ReadGetOnlyCollectionFromJson (XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract)
+               {
+                       #region GenerateCollectionReaderHelper
+                       // InitArgs()
+                       this.xmlReader = xmlReader;
+                       this.context = context;
+                       this.emptyDictionaryString = emptyDictionaryString;
+                       this.itemName = itemName;
+
+                       this.collectionContract = collectionContract;
+
+                       #endregion
+
+                       ReadGetOnlyCollection (collectionContract);
+               }
+
+               void CreateObject (ClassDataContract classContract)
+               {
+                       Type type = objectType = classContract.UnderlyingType;
+                       if (type.IsValueType && !classContract.IsNonAttributedType)
+                               type = Globals.TypeOfValueType;
+
+                       if (classContract.UnderlyingType == Globals.TypeOfDBNull)
+                               objectLocal = DBNull.Value;
+                       else if (classContract.IsNonAttributedType) {
+                               if (type.IsValueType)
+                                       objectLocal = FormatterServices.GetUninitializedObject (type);
+                               else
+                                       objectLocal = classContract.GetNonAttributedTypeConstructor ().Invoke (new object [0]);
+                       }
+                       else
+                               objectLocal = CodeInterpreter.ConvertValue (XmlFormatReaderGenerator.UnsafeGetUninitializedObject (DataContract.GetIdForInitialization (classContract)), Globals.TypeOfObject, type);
+               }
+
+               void InvokeOnDeserializing (ClassDataContract classContract)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnDeserializing (classContract.BaseContract);
+                       if (classContract.OnDeserializing != null)
+                               classContract.OnDeserializing.Invoke (objectLocal, new object [] {context.GetStreamingContext ()});
+               }
+
+               void InvokeOnDeserialized (ClassDataContract classContract)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnDeserialized (classContract.BaseContract);
+                       if (classContract.OnDeserialized != null)
+                               classContract.OnDeserialized.Invoke (objectLocal, new object [] {context.GetStreamingContext ()});
+               }
+
+               bool HasFactoryMethod (ClassDataContract classContract)
+               {
+                       return Globals.TypeOfIObjectReference.IsAssignableFrom (classContract.UnderlyingType);
+               }
+
+               bool InvokeFactoryMethod (ClassDataContract classContract)
+               {
+                       if (HasFactoryMethod (classContract)) {
+                               objectLocal = CodeInterpreter.ConvertValue (context.GetRealObject ((IObjectReference) objectLocal, Globals.NewObjectId), Globals.TypeOfObject, classContract.UnderlyingType);
+                               return true;
+                       }
+                       return false;
+               }
+
+               void ReadISerializable (ClassDataContract classContract)
+               {
+                       ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor (Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null);
+                       if (ctor == null)
+                               throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (XmlObjectSerializer.CreateSerializationException (SR.GetString (SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName (classContract.UnderlyingType))));
+                       context.ReadSerializationInfo (xmlReader, classContract.UnderlyingType);
+                       ctor.Invoke (objectLocal, new object [] {context.GetStreamingContext ()});
+               }
+
+               void ReadClass (ClassDataContract classContract)
+               {
+                       if (classContract.HasExtensionData) {
+                               ExtensionDataObject extensionData = new ExtensionDataObject ();
+                               ReadMembers (classContract, extensionData);
+                               ClassDataContract currentContract = classContract;
+                               while (currentContract != null) {
+                                       MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
+                                       if (extensionDataSetMethod != null)
+                                               extensionDataSetMethod.Invoke (objectLocal, new object [] {extensionData});
+                                       currentContract = currentContract.BaseContract;
+                               }
+                       }
+                       else
+                               ReadMembers (classContract, null);
+               }
+
+               void ReadMembers (ClassDataContract classContract, ExtensionDataObject  extensionData)
+               {
+                       int memberCount = classContract.MemberNames.Length;
+                       context.IncrementItemCount (memberCount);
+
+                       int memberIndex = -1;
+                       
+                       // JSON intrinsic part.
+                       BitFlagsGenerator expectedElements = new BitFlagsGenerator (memberCount);
+                       byte [] requiredElements = new byte [expectedElements.GetLocalCount ()];
+                       SetRequiredElements (classContract, requiredElements);
+                       SetExpectedElements (expectedElements, 0 /*startIndex*/);
+
+                       while (XmlObjectSerializerReadContext.MoveToNextElement (xmlReader)) {
+                               int idx; // used as in "switch (idx)" in the original source.
+                               idx = context.GetJsonMemberIndex (xmlReader, memberNames, memberIndex, extensionData);
+
+                               if (memberCount > 0)
+                                       ReadMembers (idx, classContract, expectedElements, ref memberIndex);
+                       }
+
+                       if (!CheckRequiredElements (expectedElements, requiredElements))
+                               XmlObjectSerializerReadContextComplexJson.ThrowMissingRequiredMembers (objectLocal, memberNames, expectedElements.LoadArray (), requiredElements);
+               }
+
+               int ReadMembers (int index, ClassDataContract classContract, BitFlagsGenerator expectedElements, ref int memberIndex)
+               {
+                       int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers (index, classContract.BaseContract, expectedElements,
+                       ref memberIndex);
+                       
+                       if (memberCount <= index && index < memberCount + classContract.Members.Count) {
+                               DataMember dataMember = classContract.Members [index - memberCount];
+                               Type memberType = dataMember.MemberType;
+                               
+                               memberIndex = memberCount;
+                               if (!expectedElements.Load (index))
+                                       XmlObjectSerializerReadContextComplexJson.ThrowDuplicateMemberException (objectLocal, memberNames, memberIndex);
+
+                               if (dataMember.IsGetOnlyCollection) {
+                                       var value = CodeInterpreter.GetMember (dataMember.MemberInfo, objectLocal);
+                                       context.StoreCollectionMemberInfo (value);
+                                       ReadValue (memberType, dataMember.Name);
+                               } else {
+                                       var value = ReadValue (memberType, dataMember.Name);
+                                       CodeInterpreter.SetMember (dataMember.MemberInfo, objectLocal, value);
+                               }
+                               memberIndex = index;
+                               ResetExpectedElements (expectedElements, index);
+                       }
+                       return memberCount + classContract.Members.Count;
+               }
+
+               bool CheckRequiredElements (BitFlagsGenerator expectedElements, byte [] requiredElements)
+               {
+                       for (int i = 0; i < requiredElements.Length; i++)
+                               if ((expectedElements.GetLocal(i) & requiredElements[i]) != 0)
+                                       return false;
+                       return true;
+               }
+
+               int SetRequiredElements (ClassDataContract contract, byte [] requiredElements)
+               {
+                       int memberCount = (contract.BaseContract == null) ? 0 :
+                       SetRequiredElements (contract.BaseContract, requiredElements);
+                       List<DataMember> members = contract.Members;
+                       for (int i = 0; i < members.Count; i++, memberCount++) {
+                               if (members[i].IsRequired)
+                                       BitFlagsGenerator.SetBit (requiredElements, memberCount);
+                       }
+                       return memberCount;
+               }
+
+               void SetExpectedElements (BitFlagsGenerator expectedElements, int startIndex)
+               {
+                       int memberCount = expectedElements.GetBitCount ();
+                       for (int i = startIndex; i < memberCount; i++)
+                               expectedElements.Store (i, true);
+               }
+
+               void ResetExpectedElements (BitFlagsGenerator expectedElements, int index)
+               {
+                       expectedElements.Store (index, false);
+               }
+
+               object ReadValue (Type type, string name)
+               {
+                       var valueType = type;
+                       object value = null;
+                       bool shouldAssignNullableValue = false;
+                       int nullables = 0;
+                       while (type.IsGenericType && type.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
+                               nullables++;
+                               type = type.GetGenericArguments () [0];
+                       }
+                       
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract (type);
+                       if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) {
+                               context.ReadAttributes (xmlReader);
+                               string objectId = context.ReadIfNullOrRef (xmlReader, type, DataContract.IsTypeSerializable (type));
+                               // Deserialize null
+                if (objectId == Globals.NullObjectId) {
+                                       
+                                       if (nullables != 0)
+                                               value = Activator.CreateInstance (valueType);
+                                       else if (type.IsValueType)
+                                               throw new SerializationException (SR.GetString (SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName (type)));
+                                       else
+                                               value = null;
+                               } else if (objectId == string.Empty) {
+                                       // Deserialize value
+
+                                       // Compare against Globals.NewObjectId, which is set to string.Empty
+                                       
+                                       objectId = context.GetObjectId ();
+                                       
+                                       if (type.IsValueType) {
+                                               if (!string.IsNullOrEmpty (objectId))
+                                                       throw new SerializationException (SR.GetString (SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
+                                       }
+                                       object innerValueRead = null;
+                                       if (nullables != 0)
+                                               shouldAssignNullableValue = true;
+
+                                       if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) {
+                                               value = primitiveContract.XmlFormatReaderMethod.Invoke (xmlReader, new object [0]);
+                                               if (!type.IsValueType)
+                                                       context.AddNewObject (value);
+                                       }
+                                       else
+                                                       value = InternalDeserialize (type, name);
+                               } else {
+                                       // Deserialize ref
+                                       if (type.IsValueType)
+                                               throw new SerializationException (SR.GetString (SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName (type)));
+                                       else
+                                               value = CodeInterpreter.ConvertValue (context.GetExistingObject (objectId, type, name, string.Empty), Globals.TypeOfObject, type);
+                               }
+
+                               if (shouldAssignNullableValue) {
+                                       if (objectId != Globals.NullObjectId)
+                                               value = WrapNullableObject (type, value, valueType, nullables);
+                               }
+                       }
+                       else
+                               value = InternalDeserialize (type, name);
+
+                       return value;
+               }
+
+               object InternalDeserialize (Type type, string name)
+               {
+                       Type declaredType = type.IsPointer ? Globals.TypeOfReflectionPointer : type;
+                       var obj = context.InternalDeserialize (xmlReader, DataContract.GetId (declaredType.TypeHandle), declaredType.TypeHandle, name, string.Empty);
+
+                       if (type.IsPointer)
+                               // wow, there is no way to convert void* to object in strongly typed way...
+                               return JsonFormatGeneratorStatics.UnboxPointer.Invoke (null, new object [] {obj});
+                       else
+                               return CodeInterpreter.ConvertValue (obj, Globals.TypeOfObject, type);
+               }
+
+               object WrapNullableObject (Type innerType, object innerValue, Type outerType, int nullables)
+               {
+                       var outerValue = innerValue;
+                       for (int i = 1; i < nullables; i++) {
+                               Type type = Globals.TypeOfNullable.MakeGenericType (innerType);
+                               outerValue = Activator.CreateInstance (type, new object[] { outerValue });
+                               innerType = type;
+                       }
+                       return Activator.CreateInstance (outerType, new object[] { outerValue });
+               }
+
+
+               void ReadCollection (CollectionDataContract collectionContract)
+               {
+                       Type type = collectionContract.UnderlyingType;
+                       Type itemType = collectionContract.ItemType;
+                       bool isArray = (collectionContract.Kind == CollectionKind.Array);
+
+                       ConstructorInfo constructor = collectionContract.Constructor;
+
+                       if (type.IsInterface) {
+                               switch (collectionContract.Kind) {
+                               case CollectionKind.GenericDictionary:
+                                       type = Globals.TypeOfDictionaryGeneric.MakeGenericType (itemType.GetGenericArguments ());
+                                       constructor = type.GetConstructor (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null);
+                                       break;
+                               case CollectionKind.Dictionary:
+                                       type = Globals.TypeOfHashtable;
+                                       constructor = type.GetConstructor (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null);
+                                       break;
+                               case CollectionKind.Collection:
+                               case CollectionKind.GenericCollection:
+                               case CollectionKind.Enumerable:
+                               case CollectionKind.GenericEnumerable:
+                               case CollectionKind.List:
+                               case CollectionKind.GenericList:
+                                       type = itemType.MakeArrayType ();
+                                       isArray = true;
+                                       break;
+                               }
+                       }
+
+                       if (!isArray) {
+                               if (type.IsValueType)
+                                       // FIXME: this is not what the original code does.
+                                       objectLocal = FormatterServices.GetUninitializedObject (type);
+                               else {
+                                       objectLocal = constructor.Invoke (new object [0]);
+                                       context.AddNewObject (objectLocal);
+                               }
+                       }
+
+                       bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary ||
+                       collectionContract.Kind == CollectionKind.GenericDictionary;
+
+                       bool readSimpleDictionary = canReadSimpleDictionary & context.UseSimpleDictionaryFormat;
+                       if (readSimpleDictionary)
+                               ReadSimpleDictionary (collectionContract, itemType);
+                       else {   
+                               string objectId = context.GetObjectId ();
+
+                               bool canReadPrimitiveArray = false, readResult = false;
+                               if (isArray && TryReadPrimitiveArray (itemType, out readResult))
+                                       canReadPrimitiveArray = true;
+
+                               if (!canReadPrimitiveArray) {
+                                       object growingCollection = null;
+                                       if (isArray)
+                                               growingCollection = Array.CreateInstance (itemType, 32);
+
+                                       int i = 0;
+                                       // FIXME: I cannot find i++ part, but without that it won't work as expected.
+                                       for (; i < int.MaxValue; i++) {
+                                               if (IsStartElement (this.itemName, this.emptyDictionaryString)) {
+                                                       context.IncrementItemCount (1);
+                                                       object value = ReadCollectionItem (collectionContract, itemType);
+                                                       if (isArray) {
+                                                               MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod (itemType);
+                                                               growingCollection = ensureArraySizeMethod.Invoke (null, new object [] {growingCollection, i});
+                                                               ((Array) growingCollection).SetValue (value, i);
+                                                       } else {
+                                                               StoreCollectionValue (objectLocal, itemType, value, collectionContract);
+                                                       }
+                                               }
+                                               else if (IsEndElement ())
+                                                       break;
+                                               else
+                                                       HandleUnexpectedItemInCollection (ref i);
+                                       }
+
+                                       if (isArray) {
+                                               MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod (itemType);
+                                               objectLocal = trimArraySizeMethod.Invoke (null, new object [] {growingCollection, i});
+                                               context.AddNewObjectWithId (objectId, objectLocal);
+                                       }
+                               }
+                               else
+                                       context.AddNewObjectWithId (objectId, objectLocal);
+                       }
+               }
+
+               void ReadSimpleDictionary (CollectionDataContract collectionContract, Type keyValueType)
+               {
+                       Type[] keyValueTypes = keyValueType.GetGenericArguments ();
+                       Type keyType = keyValueTypes [0];
+                       Type valueType = keyValueTypes [1];
+
+                       int keyTypeNullableDepth = 0;
+                       Type keyTypeOriginal = keyType;
+                       while (keyType.IsGenericType && keyType.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
+                               keyTypeNullableDepth++;
+                               keyType = keyType.GetGenericArguments () [0];
+                       }
+
+                       ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract;
+                       DataContract keyDataContract = keyValueDataContract.Members [0].MemberTypeContract;
+
+                       KeyParseMode keyParseMode = KeyParseMode.Fail;
+
+                       if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject) {
+                               keyParseMode = KeyParseMode.AsString;
+                       } else if (keyType.IsEnum) {
+                               keyParseMode = KeyParseMode.UsingParseEnum;
+                       } else if (keyDataContract.ParseMethod != null) {
+                               keyParseMode = KeyParseMode.UsingCustomParse;
+                       }
+
+                       if (keyParseMode == KeyParseMode.Fail) {
+                               ThrowSerializationException (
+                               SR.GetString (
+                               SR.KeyTypeCannotBeParsedInSimpleDictionary,
+                               DataContract.GetClrTypeFullName (collectionContract.UnderlyingType),
+                               DataContract.GetClrTypeFullName (keyType)));
+                       } else {
+                               XmlNodeType nodeType;
+
+                               while ((nodeType = xmlReader.MoveToContent ()) != XmlNodeType.EndElement) {
+                                       if (nodeType != XmlNodeType.Element)
+                                               ThrowUnexpectedStateException (XmlNodeType.Element);
+
+                                       context.IncrementItemCount (1);
+
+                                       var jsonMemberName = XmlObjectSerializerReadContextComplexJson.GetJsonMemberName (xmlReader);
+                                       object key = null;
+
+                                       if (keyParseMode == KeyParseMode.UsingParseEnum)
+                                               key = Enum.Parse (keyType, jsonMemberName);
+                                       else if (keyParseMode == KeyParseMode.UsingCustomParse)
+                                               key = keyDataContract.ParseMethod.Invoke (null, new object [] {jsonMemberName});
+
+                                       if (keyTypeNullableDepth > 0) {
+                                               var keyOriginal = WrapNullableObject (keyType, key, valueType, keyTypeNullableDepth);
+                                               key = keyOriginal;
+                                       }
+
+                                       var value = ReadValue (valueType, String.Empty);
+                                       collectionContract.AddMethod.Invoke (objectLocal, new object[] {key, value});
+                               }
+                       }
+               }
+
+               void ReadGetOnlyCollection (CollectionDataContract collectionContract)
+               {
+                       Type type = collectionContract.UnderlyingType;
+                       Type itemType = collectionContract.ItemType;
+                       bool isArray = (collectionContract.Kind == CollectionKind.Array);
+                       int size = 0;
+
+                       objectLocal = context.GetCollectionMember ();
+                       bool canReadSimpleDictionary = 
+                               collectionContract.Kind == CollectionKind.Dictionary ||
+                               collectionContract.Kind == CollectionKind.GenericDictionary;
+
+                       bool readSimple = canReadSimpleDictionary && context.UseSimpleDictionaryFormat;
+                       if (readSimple) {
+                               if (objectLocal == null)
+                                       XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException (type);
+                               else {
+                                       ReadSimpleDictionary(collectionContract, itemType);
+                                       context.CheckEndOfArray (xmlReader, size, this.itemName, emptyDictionaryString);
+                               }
+                       } else {
+
+                               //check that items are actually going to be deserialized into the collection
+                               if (IsStartElement (this.itemName, this.emptyDictionaryString)) {
+                                       if (objectLocal == null)
+                                               XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException (type);
+                                       else {
+                                               size = 0;
+                                               if (isArray)
+                                                       size = ((Array) objectLocal).Length;
+                                               for (int i = 0; i < int.MaxValue;) {
+                                                       if (IsStartElement (this.itemName, this.emptyDictionaryString)) {
+                                                               context.IncrementItemCount (1);
+                                                               var value = ReadCollectionItem (collectionContract, itemType);
+                                                               if (isArray) {
+                                                                       if (size == i)
+                                                                               XmlObjectSerializerReadContext.ThrowArrayExceededSizeException (size, type);
+                                                                       else
+                                                                               ((Array) objectLocal).SetValue (value, i);
+                                                               } else {
+                                                                       StoreCollectionValue (objectLocal, itemType, value, collectionContract);
+                                                               }
+                                                       }
+                                                       else if (IsEndElement())
+                                                               break;
+                                                       else
+                                                               HandleUnexpectedItemInCollection (ref i);
+                                               }
+                                               context.CheckEndOfArray (xmlReader, size, this.itemName, this.emptyDictionaryString);
+                                       }
+                               }
+                       }
+               }
+
+               bool TryReadPrimitiveArray (Type itemType, out bool readResult)
+               {
+                       readResult = false;
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract (itemType);
+                       if (primitiveContract == null)
+                               return false;
+
+                       string readArrayMethod = null;
+                       switch (Type.GetTypeCode (itemType))
+                       {
+                       case TypeCode.Boolean:
+                               readArrayMethod = "TryReadBooleanArray";
+                       break;
+                       case TypeCode.Decimal:
+                               readArrayMethod = "TryReadDecimalArray";
+                       break;
+                       case TypeCode.Int32:
+                               readArrayMethod = "TryReadInt32Array";
+                       break;
+                       case TypeCode.Int64:
+                               readArrayMethod = "TryReadInt64Array";
+                       break;
+                       case TypeCode.Single:
+                               readArrayMethod = "TryReadSingleArray";
+                       break;
+                       case TypeCode.Double:
+                               readArrayMethod = "TryReadDoubleArray";
+                               break;
+                       case TypeCode.DateTime:
+                               readArrayMethod = "TryReadJsonDateTimeArray";
+                       break;
+                       default:
+                               break;
+                       }
+                       if (readArrayMethod != null) {
+                               var mi = typeof (JsonReaderDelegator).GetMethod (readArrayMethod, Globals.ScanAllMembers);
+                               var args = new object [] {context, itemName, emptyDictionaryString, -1, objectLocal};
+                               readResult = (bool) mi.Invoke ((JsonReaderDelegator) xmlReader, args);
+                               objectLocal = args.Last ();
+                               return true;
+                       }
+                       return false;
+               }
+
+               object ReadCollectionItem (CollectionDataContract collectionContract, Type itemType)
+               {
+                       if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) {
+                               context.ResetAttributes ();
+                               var revisedContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract (collectionContract.ItemContract);
+                               var v = DataContractJsonSerializer.ReadJsonValue (revisedContract, xmlReader, context);
+                               return CodeInterpreter.ConvertValue (v, Globals.TypeOfObject, itemType);
+                       }
+                       else
+                               return ReadValue (itemType, JsonGlobals.itemString);
+               }
+
+               void StoreCollectionValue (object collection, Type valueType, object value, CollectionDataContract collectionContract)
+               {
+                       if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) {
+                               ClassDataContract keyValuePairContract = DataContract.GetDataContract (valueType) as ClassDataContract;
+                               if (keyValuePairContract == null)
+                                       Fx.Assert ("Failed to create contract for KeyValuePair type");
+                               DataMember keyMember = keyValuePairContract.Members [0];
+                               DataMember valueMember = keyValuePairContract.Members [1];
+                               object pkey = CodeInterpreter.GetMember (keyMember.MemberInfo, value);
+                               object pvalue = CodeInterpreter.GetMember (valueMember.MemberInfo, value);
+                               
+                               try {
+                                       collectionContract.AddMethod.Invoke (collection, new object [] {pkey, pvalue});
+                               } catch (TargetInvocationException ex) {
+                                       if (ex.InnerException != null)
+                                               throw ex.InnerException;
+                                       else
+                                               throw;
+                               }
+                       }
+                       else
+                               collectionContract.AddMethod.Invoke (collection, new object [] {value});
+               }
+
+               void HandleUnexpectedItemInCollection (ref int iterator)
+               {
+                       if (IsStartElement ()) {
+                               context.SkipUnknownElement (xmlReader);
+                               iterator--;
+                       }
+                       else 
+                               throw XmlObjectSerializerReadContext.CreateUnexpectedStateException (XmlNodeType.Element, xmlReader);
+               }
+
+               bool IsStartElement(XmlDictionaryString name, XmlDictionaryString ns)
+               {
+                       return xmlReader.IsStartElement (name, ns);
+               }
+
+               bool IsStartElement()
+               {
+                       return xmlReader.IsStartElement ();
+               }
+
+               bool IsEndElement ()
+               {
+                       return xmlReader.NodeType == XmlNodeType.EndElement;
+               }
+
+               void ThrowUnexpectedStateException (XmlNodeType expectedState)
+               {
+                       throw XmlObjectSerializerReadContext.CreateUnexpectedStateException (expectedState, xmlReader);
+               }
+
+               void ThrowSerializationException (string msg, params object [] values)
+               {
+                       if (values != null && values.Length > 0)
+                               msg = string.Format (msg, values);
+                       throw new SerializationException (msg);
+               }
+
+               enum KeyParseMode
+               {
+                       Fail,
+                       AsString,
+                       UsingParseEnum,
+                       UsingCustomParse
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/JsonFormatWriterGenerator_static.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/JsonFormatWriterGenerator_static.cs
new file mode 100644 (file)
index 0000000..1e595b7
--- /dev/null
@@ -0,0 +1,619 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Xml;
+
+namespace System.Runtime.Serialization.Json
+{
+       internal partial class JsonFormatWriterGenerator
+       {
+               partial class CriticalHelper
+               {
+                       internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
+                       {
+                               return (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString [] memberNames) => new JsonFormatWriterInterpreter (classContract).WriteToJson (xmlWriter, obj, context, dataContract, memberNames);
+                       }
+                       internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
+                       {
+                               return (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract) => new JsonFormatWriterInterpreter (collectionContract).WriteCollectionToJson (xmlWriter, obj, context, dataContract);
+                       }
+               }
+       }
+
+       class JsonFormatWriterInterpreter
+       {
+               public JsonFormatWriterInterpreter (ClassDataContract classContract)
+               {
+                       this.classContract = classContract;
+               }
+
+               public JsonFormatWriterInterpreter (CollectionDataContract collectionContract)
+               {
+                       this.collectionContract = collectionContract;
+               }
+
+               ClassDataContract classContract;
+
+               CollectionDataContract collectionContract;
+
+               XmlWriterDelegator writer = null;
+               object obj = null;
+               XmlObjectSerializerWriteContextComplexJson context = null;
+               DataContract dataContract = null;
+               object objLocal = null;
+
+               ClassDataContract classDataContract {
+                       get { return (ClassDataContract) dataContract; }
+               }
+               CollectionDataContract collectionDataContract {
+                       get {return (CollectionDataContract) dataContract; }
+               }
+
+               XmlDictionaryString [] memberNames = null;
+               int typeIndex = 1;
+               int childElementIndex = 0;
+
+               public void WriteToJson (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString [] memberNames)
+               {
+                       this.writer = xmlWriter;
+                       this.obj = obj;
+                       this.context = context;
+                       this.dataContract = dataContract;
+                       this.memberNames = memberNames;
+
+                       InitArgs (classContract.UnderlyingType);
+
+                       // DemandSerializationFormatterPermission (classContract) - irrelevant
+                       // DemandMemberAccessPermission (memberAccessFlag) - irrelevant
+
+                       if (classContract.IsReadOnlyContract)
+                       {
+                               DataContract.ThrowInvalidDataContractException (classContract.SerializationExceptionMessage, null);
+                       }
+
+                       WriteClass (classContract);
+               }
+
+               public void WriteCollectionToJson (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract)
+               {
+                       this.writer = xmlWriter;
+                       this.obj = obj;
+                       this.context = context;
+                       this.dataContract = dataContract;
+
+                       InitArgs (collectionContract.UnderlyingType);                   
+
+                       // DemandMemberAccessPermission(memberAccessFlag);
+                       if (collectionContract.IsReadOnlyContract)
+                       {
+                               DataContract.ThrowInvalidDataContractException (collectionContract.SerializationExceptionMessage, null);
+                       }
+
+                       WriteCollection (collectionContract);
+               }
+
+               void InitArgs (Type objType)
+               {
+                       if (objType == Globals.TypeOfDateTimeOffsetAdapter) {
+                               objLocal = DateTimeOffsetAdapter.GetDateTimeOffsetAdapter ((DateTimeOffset) obj);
+                       }
+                       else
+                               objLocal = CodeInterpreter.ConvertValue (obj, typeof (object), objType);
+               }
+
+               void InvokeOnSerializing (ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext context)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnSerializing (classContract.BaseContract, objSerialized, context);
+                       if (classContract.OnSerializing != null) {
+                               classContract.OnSerializing.Invoke (objSerialized, new object [] {context.GetStreamingContext ()});
+                       }
+               }
+
+               void InvokeOnSerialized (ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext context)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnSerialized (classContract.BaseContract, objSerialized, context);
+                       if (classContract.OnSerialized != null) {
+                               classContract.OnSerialized.Invoke (objSerialized, new object [] {context.GetStreamingContext ()});
+                       }
+               }
+
+               void WriteClass (ClassDataContract classContract)
+               {
+                       InvokeOnSerializing (classContract, objLocal, context);
+
+                       if (classContract.IsISerializable)
+                               context.WriteJsonISerializable (writer, (ISerializable) objLocal);
+                       else
+                       {
+                               if (classContract.HasExtensionData)
+                               {
+                                       ExtensionDataObject extensionData = ((IExtensibleDataObject) objLocal).ExtensionData;
+                                       context.WriteExtensionData (writer, extensionData, -1);
+
+                                       WriteMembers (classContract, extensionData, classContract);
+                               }
+                               else
+                                       WriteMembers (classContract, null, classContract);
+                       }
+                       InvokeOnSerialized (classContract, objLocal, context);
+               }
+
+               void WriteCollection(CollectionDataContract collectionContract)
+               {
+                       XmlDictionaryString itemName = context.CollectionItemName;
+
+                       if (collectionContract.Kind == CollectionKind.Array)
+                       {
+                               Type itemType = collectionContract.ItemType;
+                               int i;
+
+                               // This check does not exist in the original dynamic code,
+                               // but there is no other way to check type mismatch.
+                               // CollectionSerialization.ArrayContract() shows that it is required.
+                               if (objLocal.GetType ().GetElementType () != itemType)
+                                       throw new InvalidCastException (string.Format ("Cannot cast array of {0} to array of {1}", objLocal.GetType ().GetElementType (), itemType));
+
+                               context.IncrementArrayCount (writer, (Array) objLocal);
+
+                               if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName))
+                               {
+                                       WriteArrayAttribute ();
+                                       var arr = (Array) objLocal;
+                                       var idx = new int [1];
+                                       for (i = 0; i < arr.Length; i++) {
+                                               if (!TryWritePrimitive(itemType, null, null, i, itemName, 0)) {
+                                                       WriteStartElement (itemName, 0);
+                                                       idx [0] = i;
+                                                       var mbrVal = arr.GetValue (idx);
+                                                       WriteValue (itemType, mbrVal);
+                                                       WriteEndElement ();
+                                               }
+                                       }
+                               }
+                       }
+                       else
+                       {
+                               // This check does not exist in the original dynamic code,
+                               // but there is no other way to check type mismatch.
+                               // CollectionSerialization.ArrayContract() shows that it is required.
+                               if (!collectionContract.UnderlyingType.IsAssignableFrom (objLocal.GetType ()))
+                                       throw new InvalidCastException (string.Format ("Cannot cast {0} to {1}", objLocal.GetType (), collectionContract.UnderlyingType));
+                               
+                               MethodInfo incrementCollectionCountMethod = null;
+                               switch (collectionContract.Kind)
+                               {
+                               case CollectionKind.Collection:
+                               case CollectionKind.List:
+                               case CollectionKind.Dictionary:
+                                       incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
+                                       break;
+                               case CollectionKind.GenericCollection:
+                               case CollectionKind.GenericList:
+                                       incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
+                                       break;
+                               case CollectionKind.GenericDictionary:
+                                       incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
+                                       break;
+                               }
+                               if (incrementCollectionCountMethod != null)
+                                       incrementCollectionCountMethod.Invoke (context, new object [] {writer, objLocal});
+
+                               bool isDictionary = false, isGenericDictionary = false;
+                               Type enumeratorType = null;
+                               Type [] keyValueTypes = null;
+                               if (collectionContract.Kind == CollectionKind.GenericDictionary)
+                               {
+                                       isGenericDictionary = true;
+                                       keyValueTypes = collectionContract.ItemType.GetGenericArguments ();
+                                       enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType (keyValueTypes);
+                               }
+                               else if (collectionContract.Kind == CollectionKind.Dictionary)
+                               {
+                                       isDictionary = true;
+                                       keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
+                                       enumeratorType = Globals.TypeOfDictionaryEnumerator;
+                               }
+                               else
+                               {
+                                       enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
+                               }
+                               MethodInfo moveNextMethod = enumeratorType.GetMethod (Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
+                               MethodInfo getCurrentMethod = enumeratorType.GetMethod (Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
+                               if (moveNextMethod == null || getCurrentMethod == null)
+                               {
+                                       if (enumeratorType.IsInterface)
+                                       {
+                                               if (moveNextMethod == null)
+                                                       moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod;
+                                               if (getCurrentMethod == null)
+                                                       getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod;
+                                       }
+                                       else
+                                       {
+                                               Type ienumeratorInterface = Globals.TypeOfIEnumerator;
+                                               CollectionKind kind = collectionContract.Kind;
+                                               if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
+                                               {
+                                                       Type[] interfaceTypes = enumeratorType.GetInterfaces();
+                                                       foreach (Type interfaceType in interfaceTypes)
+                                                       {
+                                                               if (interfaceType.IsGenericType
+                                                                       && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
+                                                                       && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
+                                                               {
+                                                                       ienumeratorInterface = interfaceType;
+                                                                       break;
+                                                               }
+                                                       }
+                                               }
+                                               if (moveNextMethod == null)
+                                                       moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
+                                               if (getCurrentMethod == null)
+                                                       getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
+                                       }
+                               }
+                               Type elementType = getCurrentMethod.ReturnType;
+                               object currentValue = null; // of elementType
+
+                               var enumerator = (IEnumerator) collectionContract.GetEnumeratorMethod.Invoke (objLocal, new object [0]);
+                               if (isDictionary)
+                               {
+                                       ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor (Globals.ScanAllMembers, null, new Type[] { Globals.TypeOfIDictionaryEnumerator }, null);
+                                       enumerator = (IEnumerator) dictEnumCtor.Invoke (new object [] {enumerator});
+                               }
+                               else if (isGenericDictionary)
+                               {
+                                       Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
+                                       ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null);
+                                       enumerator = (IEnumerator) Activator.CreateInstance (enumeratorType, new object [] {enumerator});
+                               }
+
+                               bool canWriteSimpleDictionary = isDictionary || isGenericDictionary;
+                               
+                               bool writeSimpleDictionary = canWriteSimpleDictionary && context.UseSimpleDictionaryFormat;
+                               PropertyInfo genericDictionaryKeyProperty = null, genericDictionaryValueProperty = null;
+                               
+                               if (canWriteSimpleDictionary)
+                               {
+                                       Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType (keyValueTypes);
+                                       genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty (JsonGlobals.KeyString);
+                                       genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty (JsonGlobals.ValueString);
+                               }
+
+                               if (writeSimpleDictionary) {
+                                       WriteObjectAttribute ();
+                                       object key, value;
+                                       var empty_args = new object [0];
+                                       while ((bool) moveNextMethod.Invoke (enumerator, empty_args)) {
+                                               currentValue = getCurrentMethod.Invoke (enumerator, empty_args);
+                                               key = CodeInterpreter.GetMember (genericDictionaryKeyProperty, currentValue);
+                                               value = CodeInterpreter.GetMember (genericDictionaryValueProperty, currentValue);
+
+                                               WriteStartElement (key, 0 /*nameIndex*/);
+                                               WriteValue (genericDictionaryValueProperty.PropertyType, value);
+                                               WriteEndElement ();
+                                       }
+                               } else {
+                                       WriteArrayAttribute ();
+
+                                       var emptyArray = new object [0];
+                                       while (enumerator != null && enumerator.MoveNext ()) {
+                                               currentValue = getCurrentMethod.Invoke (enumerator, emptyArray);
+
+                                               if (incrementCollectionCountMethod == null)
+                                                       XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke (context, new object [] {1});
+
+                                               if (!TryWritePrimitive (elementType, () => currentValue, null, null, itemName, 0))
+                                               {
+                                                       WriteStartElement (itemName, 0);
+                                                       if (isGenericDictionary || isDictionary) {
+                                                               var jc = JsonDataContract.GetJsonDataContract (XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract (
+                                                               collectionDataContract.ItemContract));
+                                                               // FIXME: this TypeHandle might be wrong; there is no easy way to get Type for currentValue though.
+                                                               DataContractJsonSerializer.WriteJsonValue (jc, writer, currentValue, context, currentValue.GetType ().TypeHandle);
+                                                       }
+                                                       else
+                                                               WriteValue (elementType, currentValue);
+                                                       WriteEndElement ();
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               int WriteMembers (ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
+               {
+                       int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers (classContract.BaseContract, extensionData, derivedMostClassContract);
+
+                       context.IncrementItemCount (classContract.Members.Count);
+
+                       for (int i = 0; i < classContract.Members.Count; i++, memberCount++) {
+
+                               DataMember member = classContract.Members[i];
+                               Type memberType = member.MemberType;
+                               object memberValue = null;
+                               if (member.IsGetOnlyCollection)
+                                       context.StoreIsGetOnlyCollection ();
+                               bool doWrite = true, hasMemberValue = false;
+                               if (!member.EmitDefaultValue)
+                               {
+                                       hasMemberValue = true;
+                                       memberValue = LoadMemberValue (member);
+                                       doWrite = !IsDefaultValue (memberType, memberValue);
+                               }
+
+                               if (doWrite) {
+
+                                       bool requiresNameAttribute = DataContractJsonSerializer.CheckIfXmlNameRequiresMapping (classContract.MemberNames [i]);
+                                       
+                                       if (requiresNameAttribute || !TryWritePrimitive(memberType, hasMemberValue ? () => memberValue : (Func<object>) null, member.MemberInfo, null /*arrayItemIndex*/, null /*nameLocal*/, i + childElementIndex)) {
+
+                                               // Note: DataContractSerializer has member-conflict logic here to deal with the schema export
+                                               //       requirement that the same member can't be of two different types.
+                                               if (requiresNameAttribute)
+                                                       XmlObjectSerializerWriteContextComplexJson.WriteJsonNameWithMapping (writer, memberNames, i + childElementIndex);
+                                               else
+                                                       WriteStartElement (null /*nameLocal*/, i + childElementIndex);
+
+                                               if (memberValue == null)
+                                                       memberValue = LoadMemberValue (member);
+                                               WriteValue (memberType, memberValue);
+                                               WriteEndElement ();
+                                       }
+
+                                       if (classContract.HasExtensionData)
+                                               context.WriteExtensionData (writer, extensionData, memberCount);
+                               } else if (!member.EmitDefaultValue) {
+                                       if (member.IsRequired)
+                                               XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted (member.Name, classContract.UnderlyingType);
+                               }
+                       }
+
+                       typeIndex++;
+                       childElementIndex += classContract.Members.Count;
+                       return memberCount;
+               }
+
+
+               internal bool IsDefaultValue (Type type, object value)
+               {
+                       return GetDefaultValue (type).Equals (value);
+               }
+
+               internal object GetDefaultValue(Type type)
+               {
+                       if (type.IsValueType)
+                       {
+                               switch (Type.GetTypeCode(type))
+                               {
+                               case TypeCode.Boolean:
+                                       return false;
+                               case TypeCode.Char:
+                               case TypeCode.SByte:
+                               case TypeCode.Byte:
+                               case TypeCode.Int16:
+                               case TypeCode.UInt16:
+                               case TypeCode.Int32:
+                               case TypeCode.UInt32:
+                                       return 0;
+                               case TypeCode.Int64:
+                               case TypeCode.UInt64:
+                                       return 0L;
+                               case TypeCode.Single:
+                                       return 0.0F;
+                               case TypeCode.Double:
+                                       return 0.0;
+                               case TypeCode.Decimal:
+                                       return default (decimal);
+                               case TypeCode.DateTime:
+                                       return default (DateTime);
+                               }
+                       }
+                       return null;
+               }
+
+               void WriteStartElement (object nameLocal, int nameIndex)
+               {
+                       var name = nameLocal ?? memberNames [nameIndex];
+                       XmlDictionaryString namespaceLocal = null;
+                       if (nameLocal != null && nameLocal is string)
+                               writer.WriteStartElement ((string) name, null);
+                       else
+                               writer.WriteStartElement ((XmlDictionaryString) name, null);
+               }
+
+               void WriteEndElement ()
+               {
+                       writer.WriteEndElement ();
+               }
+
+               void WriteArrayAttribute ()
+               {
+                       writer.WriteAttributeString (
+                               null /* prefix */,
+                               JsonGlobals.typeString /* local name */,
+                               string.Empty /* namespace */,
+                               JsonGlobals.arrayString /* value */);
+               }
+
+               void WriteObjectAttribute ()
+               {
+                       writer.WriteAttributeString (
+                               null /* prefix */,
+                               JsonGlobals.typeString /* local name */,
+                               null /* namespace */,
+                               JsonGlobals.objectString /* value */);
+               }
+
+               void WriteValue (Type memberType, object memberValue)
+               {
+                       Pointer memberValueRefPointer = null;
+                       if (memberType.IsPointer)
+                               memberValueRefPointer = (Pointer) JsonFormatGeneratorStatics.BoxPointer.Invoke (null, new object [] {memberValue, memberType});
+                       bool isNullableOfT = (memberType.IsGenericType &&
+                               memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
+                       if (memberType.IsValueType && !isNullableOfT)
+                       {
+                               PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                               if (primitiveContract != null)
+                                       primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
+                               else
+                                       InternalSerialize (XmlFormatGeneratorStatics.InternalSerializeMethod, () => memberValue, memberType, false);
+                       }
+                       else
+                       {
+                               bool isNull;
+                               if (isNullableOfT)
+                                       memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull); //Leaves !HasValue on stack
+                               else
+                                       isNull = memberValue == null;
+                               if (isNull)
+                                       XmlFormatGeneratorStatics.WriteNullMethod.Invoke (context, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
+                               else {
+                                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                                       if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) {
+                                               if (isNullableOfT)
+                                                       primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
+                                               else                                                    
+                                                       primitiveContract.XmlFormatContentWriterMethod.Invoke (context, new object [] {writer, memberValue});
+                                       } else {
+                                               bool isNull2 = false;
+                                               if (memberType == Globals.TypeOfObject || //boxed Nullable<T>
+                                                       memberType == Globals.TypeOfValueType ||
+                                                       ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) {
+                                                       var unwrappedMemberValue = CodeInterpreter.ConvertValue (memberValue, memberType.GetType (), Globals.TypeOfObject);
+                                                       memberValue = unwrappedMemberValue;
+                                                       isNull2 = memberValue == null;
+                                               }
+                                               if (isNull2) {
+                                                       XmlFormatGeneratorStatics.WriteNullMethod.Invoke (context, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
+                                               } else {
+                                                       InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
+                                                               () => memberValue, memberType, false);
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               void InternalSerialize (MethodInfo methodInfo, Func<object> memberValue, Type memberType, bool writeXsiType)
+               {
+                       var v = memberValue ();
+                       var typeHandleValue = Type.GetTypeHandle (v);
+                       var isDeclaredType = typeHandleValue.Equals (CodeInterpreter.ConvertValue (v, memberType, Globals.TypeOfObject));
+                       try {
+                               methodInfo.Invoke (context, new object [] {writer, memberValue != null ? v : null, isDeclaredType, writeXsiType, DataContract.GetId (memberType.TypeHandle), memberType.TypeHandle});
+                       } catch (TargetInvocationException ex) {
+                               if (ex.InnerException != null)
+                                       throw ex.InnerException;
+                               else
+                                       throw;
+                       }
+               }
+
+               object UnwrapNullableObject(Func<object> memberValue, ref Type memberType, out bool isNull)// Leaves !HasValue on stack
+               {
+                       object v = memberValue ();
+                       isNull = false;
+                       while (memberType.IsGenericType && memberType.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
+                               Type innerType = memberType.GetGenericArguments () [0];
+                               if ((bool) XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v}))
+                                       v = XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v});
+                               else {
+                                       isNull = true;
+                                       v = XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod (memberType).Invoke (null, new object [0]);
+                               }
+                               memberType = innerType;
+                       }
+                       
+                       return v;
+               }
+
+               bool TryWritePrimitive(Type type, Func<object> value, MemberInfo memberInfo, int? arrayItemIndex, XmlDictionaryString name, int nameIndex)
+               {
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+                       if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
+                               return false;
+
+                       object callee = null;
+                       var args = new List<object> ();
+
+                       // load writer
+                       if (type.IsValueType)
+                               callee = writer;
+                       else {
+                               callee = context;
+                               args.Add (writer);
+                       }
+                       // load primitive value 
+                       if (value != null)
+                               args.Add (value ());
+                       else if (memberInfo != null)
+                               args.Add (CodeInterpreter.GetMember (memberInfo, objLocal));
+                       else
+                               args.Add (((Array) objLocal).GetValue (new int [] {(int) arrayItemIndex}));
+                       // load name
+                       if (name != null)
+                               args.Add (name);
+                       else
+                               args.Add (memberNames [nameIndex]);
+                       // load namespace
+                       args.Add (null);
+                       // call method to write primitive
+                       primitiveContract.XmlFormatWriterMethod.Invoke (callee, args.ToArray ());
+                       return true;
+               }
+
+               bool TryWritePrimitiveArray (Type type, Type itemType, Func<object> value, XmlDictionaryString itemName)
+               {
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                       if (primitiveContract == null)
+                               return false;
+
+                       string writeArrayMethod = null;
+                       switch (Type.GetTypeCode(itemType))
+                       {
+                       case TypeCode.Boolean:
+                               writeArrayMethod = "WriteJsonBooleanArray";
+                               break;
+                       case TypeCode.DateTime:
+                               writeArrayMethod = "WriteJsonDateTimeArray";
+                               break;
+                       case TypeCode.Decimal:
+                               writeArrayMethod = "WriteJsonDecimalArray";
+                               break;
+                       case TypeCode.Int32:
+                               writeArrayMethod = "WriteJsonInt32Array";
+                               break;
+                       case TypeCode.Int64:
+                               writeArrayMethod = "WriteJsonInt64Array";
+                               break;
+                       case TypeCode.Single:
+                               writeArrayMethod = "WriteJsonSingleArray";
+                               break;
+                       case TypeCode.Double:
+                               writeArrayMethod = "WriteJsonDoubleArray";
+                               break;
+                       default:
+                               break;
+                       }
+                       if (writeArrayMethod != null)
+                       {
+                               WriteArrayAttribute ();
+                               typeof(JsonWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, null, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null).Invoke (writer, new object [] {value (), itemName, null});
+                               return true;
+                       }
+                       return false;
+               }
+
+               object LoadMemberValue (DataMember member)
+               {
+                       return CodeInterpreter.GetMember (member.MemberInfo, objLocal);
+               }
+       }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/SR.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/SR.cs
new file mode 100644 (file)
index 0000000..ae10d9f
--- /dev/null
@@ -0,0 +1,371 @@
+using System.Globalization;
+
+#region "copy of ../../build/common/SR.cs"
+
+namespace System.Runtime.Serialization
+{
+       static partial class SR 
+       {
+
+        internal static string GetString(string name, params object[] args)
+        {
+                return GetString (CultureInfo.InvariantCulture, name, args);
+        }
+
+        internal static string GetString(CultureInfo culture, string name, params object[] args) {
+                return string.Format (culture, name, args);
+        }
+
+        internal static string GetString(string name)
+        {
+                return name;
+        }
+
+        internal static string GetString(CultureInfo culture, string name)
+        {
+                return name;
+        }
+}
+}
+
+/*
+namespace System.Text
+{
+       static partial class SR
+       {
+        internal static string GetString(string name, params object[] args)
+        {
+                return GetString (CultureInfo.InvariantCulture, name, args);
+        }
+
+        internal static string GetString(CultureInfo culture, string name, params object[] args) {
+                return string.Format (culture, name, args);
+        }
+
+        internal static string GetString(string name)
+        {
+                return name;
+        }
+
+        internal static string GetString(CultureInfo culture, string name)
+        {
+                return name;
+        }
+}
+}
+
+namespace System.Xml
+{
+       static partial class SR
+       {
+        internal static string GetString(string name, params object[] args)
+        {
+                return GetString (CultureInfo.InvariantCulture, name, args);
+        }
+
+        internal static string GetString(CultureInfo culture, string name, params object[] args) {
+                return string.Format (culture, name, args);
+        }
+
+        internal static string GetString(string name)
+        {
+                return name;
+        }
+
+        internal static string GetString(CultureInfo culture, string name)
+        {
+                return name;
+        }
+}
+}
+*/
+#endregion
+
+
+#region "retrieved string resources"
+
+namespace System.Runtime.Serialization
+{
+       static partial class SR {
+
+
+public const string ArrayExceededSize = @"Array length '{0}' provided by the get-only collection of type '{1}' is less than the number of array elements found in the input stream.  Consider increasing the length of the array.";
+public const string ArrayExceededSizeAttribute = @"Array length '{0}' provided by Size attribute is not equal to the number of array elements '{1}' from namespace '{2}' found.";
+public const string ArrayTypeIsNotSupported = @"An internal error has occurred. '{0}[]' is not supported when generating code for serialization.";
+public const string CannotDeserializeRefAtTopLevel = @"Cannot deserialize since root element references unrecognized object with id '{0}'.";
+public const string CannotLoadMemberType = @"Cannot load member type '{0}'.";
+public const string CannotSerializeObjectWithCycles = @"Object graph for type '{0}' contains cycles and cannot be serialized if references are not tracked. Consider using the DataContractAttribute with the IsReference property set to true.";
+public const string CanOnlyStoreIntoArgOrLocGot0 = @"An internal error has occurred. Data can only be stored into ArgBuilder or LocalBuilder. Got: {0}.";
+public const string CharIsInvalidPrimitive = @"An internal error has occurred. Char is not a valid schema primitive and should be treated as int in DataContract.";
+public const string CallbackMustReturnVoid = @"Serialization Callback '{1}' in type '{0}' must return void. ";
+public const string CallbackParameterInvalid = @"Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'. ";
+public const string CallbacksCannotBeVirtualMethods = @"Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute. ";
+public const string CollectionMustHaveAddMethod = @"Collection type '{0}' does not have a valid Add method.";
+public const string CollectionMustHaveGetEnumeratorMethod = @"Collection type '{0}' does not have a valid GetEnumerator method.";
+public const string CollectionMustHaveItemType = @"Collection type '{0}' must have a non-null item type.";
+public const string CollectionTypeCannotBeBuiltIn = @"{0} is a built-in type and cannot be a collection.";
+public const string CollectionTypeCannotHaveDataContract = @"{0} has DataContractAttribute attribute.";
+public const string CollectionTypeDoesNotHaveAddMethod = @"{0} does not have a valid Add method with parameter of type '{1}'.";
+public const string CollectionTypeDoesNotHaveDefaultCtor = @"{0} does not have a default constructor.";
+public const string CollectionTypeHasMultipleDefinitionsOfInterface = @"{0} has multiple definitions of interface '{1}'.";
+public const string CollectionTypeIsNotIEnumerable = @"{0} does not implement IEnumerable interface.";
+public const string DataContractCacheOverflow = @"An internal error has occurred. DataContract cache overflow.";
+public const string DataContractNamespaceAlreadySet = @"ContractNamespaceAttribute attribute maps CLR namespace '{2}' to multiple data contract namespaces '{0}' and '{1}'. You can map a CLR namespace to only one data contract namespace.";
+public const string DataContractNamespaceIsNotValid = @"DataContract namespace '{0}' is not a valid URI.";
+public const string DataContractNamespaceReserved = @"DataContract namespace '{0}' cannot be specified since it is reserved.";
+public const string DataMemberOnEnumField = @"Member '{0}.{1}' has DataMemberAttribute attribute. Use EnumMemberAttribute attribute instead.";
+public const string DcTypeNotFoundOnDeserialize = @"Element '{2}:{3}' contains data of the '{0}:{1}' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to '{1}' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.";
+public const string DcTypeNotFoundOnSerialize = @"Type '{0}' with data contract name '{1}:{2}' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.";
+public const string DcTypeNotResolvedOnDeserialize = @"Element '{2}:{3}' contains data from a type that maps to the name '{0}:{1}'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name '{1}' and namespace '{0}'.";
+public const string DeserializedObjectWithIdNotFound = @"Deserialized object with reference id '{0}' not found in stream.";
+public const string DupContractInKnownTypes = @"Type '{0}' cannot be added to list of known types since another type '{1}' with the same data contract name '{2}:{3}' is already present.";
+public const string DupKeyValueName = @"The collection data contract type '{0}' specifies the same value '{1}' for both the KeyName and the ValueName properties. This is not allowed. Consider changing either the KeyName or the ValueName property.";
+public const string DupEnumMemberValue = @"Type '{2}' contains two members '{0}' 'and '{1}' with the same name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using EnumMemberAttribute attribute.";
+public const string DupMemberName = @"Type '{2}' contains two members '{0}' 'and '{1}' with the same data member name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using DataMemberAttribute attribute.";
+public const string DuplicateAttribute = @"Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'. ";
+public const string DuplicateCallback = @"Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'. ";
+public const string EncounteredWithNameNamespace = @"{0}. Encountered '{1}'  with name '{2}', namespace '{3}'.";
+public const string EnumTypeCannotHaveIsReference = @"Enum type '{0}' cannot have the IsReference setting of '{1}'. Either change the setting to '{2}', or remove it completely.";
+public const string ErrorDeserializing = @"There was an error deserializing the object {0}. {1}";
+public const string ErrorInLine = @"Error in line {0} position {1}.";
+public const string ErrorIsStartObject = @"There was an error checking start element of object {0}. {1}";
+public const string ErrorSerializing = @"There was an error serializing the object {0}. {1}";
+public const string ErrorTypeInfo = @"of type {0}";
+public const string ErrorWriteEndObject = @"There was an error writing end element of object {0}. {1}";
+public const string ErrorWriteStartObject = @"There was an error writing start element of object {0}. {1}";
+public const string ExceededMaxItemsQuota = @"Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.";
+public const string ExpectingElement = @"Expecting element '{1}' from namespace '{0}'.";
+public const string ExpectingElementAtDeserialize = @"Expecting state '{0}' when ReadObject is called.";
+public const string ExpectingEnd = @"Expecting End'{0}'.";
+public const string ExpectingState = @"Expecting state '{0}'.";
+public const string GenericNameBraceMismatch = @"The data contract name '{0}' for type '{1}' has a curly brace '{{' that is not matched with a closing curly brace. Curly braces have special meaning in data contract names - they are used to customize the naming of data contracts for generic types.";
+public const string GenericParameterNotValid = @"In the data contract name for type '{1}', there are curly braces with '{0}' inside, which is an invalid value. Curly braces have special meaning in data contract names - they are used to customize the naming of data contracts for generic types. Based on the number of generic parameters this type has, the contents of the curly braces must either be a number between 0 and '{2}' to insert the name of the generic parameter at that index or the '#' symbol to insert a digest of the generic parameter namespaces.";
+public const string InconsistentIsReference = @"The IsReference setting for type '{0}' is '{1}', but the same setting for its parent class '{2}' is '{3}'. Derived types must have the same value for IsReference as the base type. Change the setting on type '{0}' to '{3}', or on type '{2}' to '{1}', or do not set IsReference explicitly.";
+public const string IndexedPropertyCannotBeSerialized = @"Property '{1}' in type '{0}' cannot be serialized because serialization of indexed properties is not supported.";
+public const string InterfaceTypeCannotBeCreated = @"Interface type '{0}' cannot be created. Consider replacing with a non-interface serializable type.";
+public const string InvalidCollectionContractItemName = @"Type '{0}' cannot have CollectionDataContractAttribute attribute ItemName set to null or empty string.";
+public const string InvalidCollectionContractKeyName = @"Type '{0}' cannot have CollectionDataContractAttribute attribute KeyName set to null or empty string.";
+public const string InvalidCollectionContractKeyNoDictionary = @"The collection data contract type '{0}' specifies '{1}' for the KeyName property. This is not allowed since the type is not IDictionary. Remove the setting for the KeyName property.";
+public const string InvalidCollectionContractName = @"Type '{0}' cannot have CollectionDataContractAttribute attribute Name set to null or empty string.";
+public const string InvalidCollectionContractNamespace = @"Type '{0}' cannot have CollectionDataContractAttribute attribute Namespace set to null.";
+public const string InvalidCollectionContractValueName = @"Type '{0}' cannot have CollectionDataContractAttribute attribute ValueName set to null or empty string.";
+public const string InvalidCollectionContractValueNoDictionary = @"The collection data contract type '{0}' specifies '{1}' for the ValueName property. This is not allowed since the type is not IDictionary. Remove the setting for the ValueName property.";
+public const string InvalidCollectionDataContract = @"Type '{0}' with CollectionDataContractAttribute attribute is an invalid collection type since it";
+public const string InvalidCollectionType = @"Type '{0}' is an invalid collection type since it";
+public const string InvalidDataContractName = @"Type '{0}' cannot have DataContractAttribute attribute Name set to null or empty string.";
+public const string InvalidDataContractNamespace = @"Type '{0}' cannot have DataContractAttribute attribute Namespace set to null.";
+public const string InvalidDataMemberName = @"Member '{0}' in type '{1}' cannot have DataMemberAttribute attribute Name set to null or empty string.";
+public const string InvalidEnumMemberValue = @"'{0}' in type '{1}' cannot have EnumMemberAttribute attribute Value set to null or empty string.";
+public const string InvalidEnumValueOnRead = @"Invalid enum value '{0}' cannot be deserialized into type '{1}'. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.";
+public const string InvalidEnumValueOnWrite = @"Enum value '{0}' is invalid for type '{1}' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.";
+public const string InvalidGetSchemaMethod = @"Type '{0}' cannot have MethodName on XmlSchemaProviderAttribute attribute set to null or empty string. ";
+public const string InvalidGlobalDataContractNamespace = @"CLR namespace '{0}' cannot have ContractNamespace set to null.";
+public const string InvalidMember = @"Member '{0}.{1}' cannot be serialized since it is neither a field nor a property, and therefore cannot be marked with the DataMemberAttribute attribute. Remove the DataMemberAttribute attribute from the '{1}' member.";
+public const string InvalidNonNullReturnValueByIsAny = @"Method '{0}.{1}()' returns a non-null value. The return value must be null since IsAny=true.";
+public const string InvalidPrimitiveType = @"Type '{0}' is not a valid serializable type.";
+public const string InvalidReturnTypeOnGetSchemaMethod = @"Method '{0}.{1}()' returns '{2}'. The return type must be compatible with '{3}'.";
+public const string InvalidSizeDefinition = @"Invalid Size '{0}'. Must be non-negative integer.";
+public const string InvalidXmlDataContractName = @"XML data contract Name for type '{0}' cannot be set to null or empty string.";
+public const string InvalidXsIdDefinition = @"Invalid Id '{0}'. Must not be null or empty.";
+public const string InvalidXsRefDefinition = @"Invalid Ref '{0}'. Must not be null or empty.";
+public const string IsAnyCannotBeNull = @"A null value cannot be serialized at the top level for IXmlSerializable root type '{0}' since its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct.";
+public const string IsAnyCannotBeSerializedAsDerivedType = @"An object of type '{0}' cannot be serialized at the top level for IXmlSerializable root type '{1}' since its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct.";
+public const string IsAnyCannotHaveXmlRoot = @"Type '{0}' cannot specify an XmlRootAttribute attribute because its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct.";
+public const string IsNotAssignableFrom = @"An internal error has occurred. '{0}' is not assignable from '{1}' - error generating code for serialization.";
+public const string IsRequiredDataMemberOnIsReferenceDataContractType = @"'{0}.{1}' has the IsRequired setting of '{2}. However, '{0}' has the IsReference setting of '{2}', because either it is set explicitly, or it is derived from a base class. Set IsRequired on '{0}.{1}' to false, or disable IsReference on '{0}'.";
+public const string IXmlSerializableCannotHaveCollectionDataContract = @"Type '{0}' cannot be IXmlSerializable and have CollectionDataContractAttribute attribute.";
+public const string IXmlSerializableCannotHaveDataContract = @"Type '{0}' cannot be IXmlSerializable and have DataContractAttribute attribute.";
+public const string IXmlSerializableIllegalOperation = @"This method cannot be called from IXmlSerializable implementations.";
+public const string IXmlSerializableMissingEndElements = @"IXmlSerializable.WriteXml method of type '{0}' did not close all open tags. Verify that the IXmlSerializable implementation is correct.";
+public const string IXmlSerializableMustHaveDefaultConstructor = @"IXmlSerializable Type '{0}' must have default constructor.";
+public const string IXmlSerializableWritePastSubTree = @"IXmlSerializable.WriteXml method of type '{0}' attempted to close too many tags.  Verify that the IXmlSerializable implementation is correct.";
+public const string KnownTypeAttributeEmptyString = @"Method name specified by KnownTypeAttribute attribute on type '{0}' cannot be the empty string.";
+public const string KnownTypeAttributeUnknownMethod = @"KnownTypeAttribute attribute on type '{1}' specifies a method named '{0}' to provide known types. Static method '{0}()' was not found on this type. Ensure that the method exists and is marked as static.";
+public const string KnownTypeAttributeReturnType = @"KnownTypeAttribute attribute on type '{0}' specifies a method named '{1}' to provide known types. The return type of this method is invalid because it is not assignable to IEnumerable<Type>. Ensure that the method exists and has a valid signature.";
+public const string KnownTypeAttributeOneScheme = @"Type '{0}': If a KnownTypeAttribute attribute specifies a method it must be the only KnownTypeAttribute attribute on that type.";
+public const string KnownTypeAttributeNoType = @"KnownTypeAttribute attribute on type '{0}' contains no Type.";
+public const string KnownTypeConfigClosedGenericDeclared = @"Declared type '{0}' in config cannot be a closed or partial generic type.";
+public const string KnownTypeAttributeValidMethodTypes = @"Method specified by KnownTypeAttribute attribute on type '{0}' does not expose valid types.";
+public const string KnownTypeAttributeNoData = @"KnownTypeAttribute attribute on type '{0}' contains no data.";
+public const string KnownTypeAttributeMethodNull = @"Method specified by KnownTypeAttribute attribute on type '{0}' returned null.";
+public const string MaxArrayLengthExceeded = @"The maximum array length ({0}) has been exceeded while reading XML data for array of type '{1}'.";
+public const string MissingGetSchemaMethod = @"Type '{0}' does not have a static method '{1}' that takes a parameter of type 'System.Xml.Schema.XmlSchemaSet' as specified by the XmlSchemaProviderAttribute attribute.";
+public const string MultipleIdDefinition = @"Invalid XML encountered. The same Id value '{0}' is defined more than once. Multiple objects cannot be deserialized using the same Id.";
+public const string NoConversionPossibleTo = @"An internal error has occurred. No conversion is possible to '{0}' - error generating code for serialization.";
+public const string NoGetMethodForProperty = @"No get method for property '{1}' in type '{0}'.";
+public const string NoSetMethodForProperty = @"No set method for property '{1}' in type '{0}'.";
+public const string NullKnownType = @"One of the known types provided to the serializer via '{0}' argument was invalid because it was null. All known types specified must be non-null values.";
+public const string NullValueReturnedForGetOnlyCollection = @"The get-only collection of type '{0}' returned a null value.  The input stream contains collection items which cannot be added if the instance is null.  Consider initializing the collection either in the constructor of the the object or in the getter.";
+public const string ObjectTableOverflow = @"An internal error has occurred. Object table overflow. This could be caused by serializing or deserializing extremely large object graphs.";
+public const string OrderCannotBeNegative = @"Property 'Order' in DataMemberAttribute attribute cannot be a negative number.";
+public const string ParameterCountMismatch = @"Invalid number of parameters to call method '{0}'. Expected '{1}' parameters, but '{2}' were provided.";
+public const string PartialTrustCollectionContractAddMethodNotPublic = @"The collection data contract type '{0}' cannot be deserialized because the method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustCollectionContractNoPublicConstructor = @"The collection data contract type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustCollectionContractTypeNotPublic = @"The collection data contract type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractOnSerializingNotPublic = @"The data contract type '{0}' cannot be serialized because the OnSerializing method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractOnSerializedNotPublic = @"The data contract type '{0}' cannot be serialized because the OnSerialized method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractOnDeserializingNotPublic = @"The data contract type '{0}' cannot be deserialized because the OnDeserializing method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractOnDeserializedNotPublic = @"The data contract type '{0}' cannot be deserialized because the OnDeserialized method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractFieldGetNotPublic = @"The data contract type '{0}' cannot be serialized because the member '{1}' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractFieldSetNotPublic = @"The data contract type '{0}' cannot be deserialized because the member '{1}' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractPropertyGetNotPublic = @"The data contract type '{0}' cannot be serialized because the property '{1}' does not have a public getter. Adding a public getter will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractPropertySetNotPublic = @"The data contract type '{0}' cannot be deserialized because the property '{1}' does not have a public setter. Adding a public setter will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustDataContractTypeNotPublic = @"The data contract type '{0}' is not serializable because it is not public. Making the type public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustNonAttributedSerializableTypeNoPublicConstructor = @"The type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustIXmlSerializableTypeNotPublic = @"The IXmlSerializable type '{0}' is not serializable in partial trust because it is not public. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string PartialTrustIXmlSerialzableNoPublicConstructor = @"The IXmlSerializable type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.";
+public const string NonAttributedSerializableTypesMustHaveDefaultConstructor = @"The Type '{0}' must have a parameterless constructor.";
+public const string AttributedTypesCannotInheritFromNonAttributedSerializableTypes = @"Type '{0}' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute.  Consider marking the base type '{1}' with DataContractAttribute or SerializableAttribute, or removing them from the derived type.";
+public const string GetOnlyCollectionsNotSupported = @"Get-only collection properties are not supported.  Consider adding a public setter to property '{0}.{1}' or marking the it with the IgnoreDataMemberAttribute. ";
+public const string QuotaMustBePositive = @"Quota must be a positive value.";
+public const string QuotaIsReadOnly = @"The '{0}' quota is readonly.";
+public const string QuotaCopyReadOnly = @"Cannot copy XmlDictionaryReaderQuotas. Target is readonly.";
+public const string RequiredMemberMustBeEmitted = @"Member {0} in type {1} cannot be serialized. This exception is usually caused by trying to use a null value where a null value is not allowed. The '{0}' member is set to its default value (usually null or zero). The member's EmitDefault setting is 'false', indicating that the member should not be serialized. However, the member's IsRequired setting is 'true', indicating that it must be serialized. This conflict cannot be resolved.  Consider setting '{0}' to a non-default value. Alternatively, you can change the EmitDefaultValue property on the DataMemberAttribute attribute to true, or changing the IsRequired property to false.";
+public const string ResolveTypeReturnedFalse = @"An object of type '{0}' which derives from DataContractResolver returned false from its TryResolveType method when attempting to resolve the name for an object of type '{1}', indicating that the resolution failed. Change the TryResolveType implementation to return true.";
+public const string ResolveTypeReturnedNull = @"An object of type '{0}' which derives from DataContractResolver returned a null typeName or typeNamespace but not both from its TryResolveType method when attempting to resolve the name for an object of type '{1}'. Change the TryResolveType implementation to return non-null values, or to return null values for both typeName and typeNamespace in order to serialize as the declared type.";
+public const string SupportForMultidimensionalArraysNotPresent = @"Multi-dimensional arrays are not supported.";
+public const string TooManyCollectionContracts = @"Type '{0}' has more than one CollectionDataContractAttribute attribute.";
+public const string TooManyDataContracts = @"Type '{0}' has more than one DataContractAttribute attribute.";
+public const string TooManyDataMembers = @"Member '{0}.{1}' has more than one DataMemberAttribute attribute.";
+public const string TooManyEnumMembers = @"Member '{0}.{1}' has more than one EnumMemberAttribute attribute.";
+public const string TooManyIgnoreDataMemberAttributes = @"Member '{0}.{1}' has more than one IgnoreDataMemberAttribute attribute.";
+public const string TypeMustBeConcrete = @"Error while getting known types for Type '{0}'. The type must not be an open or partial generic class.";
+public const string TypeNotSerializable = @"Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.";
+public const string UnexpectedContractType = @"An internal error has occurred. Unexpected contract type '{0}' for type '{1}' encountered.";
+public const string UnexpectedElementExpectingElements = @"'{0}' '{1}' from namespace '{2}' is not expected. Expecting element '{3}'.";
+public const string UnexpectedEndOfFile = @"Unexpected end of file.";
+public const string UnknownConstantType = @"Unrecognized constant type '{0}'.";
+public const string UnsupportedIDictionaryAsDataMemberType = @"Cannot deserialize one of the DataMember because it is an IDictionary. Use IDictionary<K,V> instead.";
+public const string ValueMustBeNonNegative = @"The value of this argument must be non-negative.";
+public const string ValueTypeCannotBeNull = @"ValueType '{0}' cannot be null.";
+public const string ValueTypeCannotHaveBaseType = @"Data contract '{0}' from namespace '{1}' is a value type and cannot have base contract '{2}' from namespace '{3}'.";
+public const string ValueTypeCannotHaveId = @"ValueType '{0}' cannot have id.";
+public const string ValueTypeCannotHaveIsReference = @"Value type '{0}' cannot have the IsReference setting of '{1}'. Either change the setting to '{2}', or remove it completely. ";
+public const string ValueTypeCannotHaveRef = @"ValueType '{0}' cannot have ref to another object.";
+public const string XmlElementAttributes = @"Only Element nodes have attributes.";
+public const string XmlForObjectCannotHaveContent = @"Element {0} from namespace {1} cannot have child contents to be deserialized as an object. Please use XElement to deserialize this pattern of XML.";
+public const string XmlInvalidConversion = @"The value '{0}' cannot be parsed as the type '{1}'.";
+public const string XmlInvalidConversionWithoutValue = @"The value cannot be parsed as the type '{0}'.";
+public const string XmlStartElementExpected = @"Start element expected. Found {0}.";
+public const string XmlWriterMustBeInElement = @"WriteState '{0}' not valid. Caller must write start element before serializing in contentOnly mode.";
+
+       }
+}
+
+namespace System.Runtime.Serialization
+{
+       static partial class SR {
+
+public const string OffsetExceedsBufferSize = @"The specified offset exceeds the buffer size ({0} bytes).";
+public const string SizeExceedsRemainingBufferSpace = @"The specified size exceeds the remaining buffer space ({0} bytes).";
+public const string ValueMustBeInRange = @"The value of this argument must fall within the range {0} to {1}.";
+public const string XmlArrayTooSmallOutput = @"Array too small.  Must be able to hold at least {0}.";
+public const string XmlInvalidBase64Length = @"Base64 sequence length ({0}) not valid. Must be a multiple of 4.";
+public const string XmlInvalidBase64Sequence = @"The characters '{0}' at offset {1} are not a valid Base64 sequence.";
+public const string XmlInvalidBinHexLength = @"BinHex sequence length ({0}) not valid. Must be a multiple of 2.";
+public const string XmlInvalidBinHexSequence = @"The characters '{0}' at offset {1} are not a valid BinHex sequence.";
+public const string XmlInvalidHighSurrogate = @"High surrogate char '0x{0}' not valid. High surrogate chars range from 0xD800 to 0xDBFF.";
+public const string XmlInvalidLowSurrogate = @"Low surrogate char '0x{0}' not valid. Low surrogate chars range from 0xDC00 to 0xDFFF.";
+public const string XmlInvalidSurrogate = @"Surrogate char '0x{0}' not valid. Surrogate chars range from 0x10000 to 0x10FFFF.";
+
+       }
+}
+
+namespace System.Runtime.Serialization
+{
+       static partial class SR {
+
+public const string CombinedPrefixNSLength = @"The combined length of the prefix and namespace must not be greater than {0}.";
+public const string InvalidInclusivePrefixListCollection = @"The inclusive namespace prefix collection cannot contain null as one of the items.";
+public const string InvalidLocalNameEmpty = @"The empty string is not a valid local name.";
+public const string XmlArrayTooSmall = @"Array too small.";
+public const string XmlArrayTooSmallInput = @"Array too small.  Length of available data must be at least {0}.";
+public const string XmlBadBOM = @"Unrecognized Byte Order Mark.";
+public const string XmlBase64DataExpected = @"Base64 encoded data expected. Found {0}.";
+public const string XmlCDATAInvalidAtTopLevel = @"CData elements not valid at top level of an XML document.";
+public const string XmlCloseCData = @"']]>' not valid in text node content.";
+public const string XmlConversionOverflow = @"The value '{0}' cannot be represented with the type '{1}'.";
+public const string XmlDeclarationRequired = @"An XML declaration with an encoding is required for all non-UTF8 documents.";
+public const string XmlDeclMissingVersion = @"Version not found in XML declaration.";
+public const string XmlDeclMissing = @"An XML declaration is required for all non-UTF8 documents.";
+public const string XmlDeclNotFirst = @"No characters can appear before the XML declaration.";
+public const string XmlDictionaryStringIDRange = @"XmlDictionaryString IDs must be in the range from {0} to {1}.";
+public const string XmlDictionaryStringIDUndefinedSession = @"XmlDictionaryString ID {0} not defined in the XmlBinaryReaderSession.";
+public const string XmlDictionaryStringIDUndefinedStatic = @"XmlDictionaryString ID {0} not defined in the static dictionary.";
+public const string XmlDuplicateAttribute = @"Duplicate attribute found. Both '{0}' and '{1}' are from the namespace '{2}'.";
+public const string XmlEmptyNamespaceRequiresNullPrefix = @"The empty namespace requires a null or empty prefix.";
+public const string XmlEncodingMismatch = @"The encoding in the declaration '{0}' does not match the encoding of the document '{1}'.";
+public const string XmlEncodingNotSupported = @"XML encoding not supported.";
+public const string XmlEndElementExpected = @"End element '{0}' from namespace '{1}' expected. Found {2}.";
+public const string XmlEndElementNoOpenNodes = @"No corresponding start element is open.";
+public const string XmlExpectedEncoding = @"The expected encoding '{0}' does not match the actual encoding '{1}'.";
+public const string XmlFoundCData = @"cdata '{0}'";
+public const string XmlFoundComment = @"comment '{0}'";
+public const string XmlFoundElement = @"element '{0}' from namespace '{1}'";
+public const string XmlFoundEndElement = @"end element '{0}' from namespace '{1}'";
+public const string XmlFoundEndOfFile = @"end of file";
+public const string XmlFoundNodeType = @"node {0}";
+public const string XmlFoundText = @"text '{0}'";
+public const string XmlFullStartElementExpected = @"Non-empty start element expected. Found {0}.";
+public const string XmlFullStartElementLocalNameNsExpected = @"Non-empty start element '{0}' from namespace '{1}' expected. Found {2}.";
+public const string XmlFullStartElementNameExpected = @"Non-empty start element '{0}' expected. Found {1}.";
+public const string XmlIDDefined = @"ID already defined.";
+public const string XmlKeyAlreadyExists = @"The specified key already exists in the dictionary.";
+public const string XmlIllegalOutsideRoot = @"Text cannot be written outside the root element.";
+public const string XmlInvalidBytes = @"Invalid byte encoding.";
+public const string XmlInvalidCharRef = @"Character reference not valid.";
+public const string XmlInvalidCommentChars = @"XML comments cannot contain '--' or end with '-'.";
+public const string XmlInvalidDeclaration = @"XML declaration can only be written at the beginning of the document.";
+public const string XmlInvalidDepth = @"Cannot call '{0}' while Depth is '{1}'.";
+public const string XmlInvalidEncoding = @"XML encoding must be 'UTF-8'.";
+public const string XmlInvalidFFFE = @"Characters with hexadecimal values 0xFFFE and 0xFFFF are not valid.";
+public const string XmlInvalidFormat = @"The input source is not correctly formatted.";
+public const string XmlInvalidID = @"ID must be >= 0.";
+public const string XmlInvalidOperation = @"The reader cannot be advanced.";
+public const string XmlInvalidPrefixState = @"A prefix cannot be defined while WriteState is '{0}'.";
+public const string XmlInvalidQualifiedName = @"Expected XML qualified name. Found '{0}'.";
+public const string XmlInvalidRootData = @"The data at the root level is invalid.";
+public const string XmlInvalidStandalone = @"'standalone' value in declaration must be 'yes' or 'no'.";
+public const string XmlInvalidStream = @"Stream returned by IStreamProvider cannot be null.";
+public const string XmlInvalidUniqueId = @"UniqueId cannot be zero length.";
+public const string XmlInvalidUTF8Bytes = @"'{0}' contains invalid UTF8 bytes.";
+public const string XmlInvalidVersion = @"XML version must be '1.0'.";
+public const string XmlInvalidWriteState = @"'{0}' cannot be called while WriteState is '{1}'.";
+public const string XmlInvalidXmlByte = @"The byte 0x{0} is not valid at this location.";
+public const string XmlInvalidXmlSpace = @"'{0}' is not a valid xml:space value. Valid values are 'default' and 'preserve'.";
+public const string XmlLineInfo = @"Line {0}, position {1}.";
+public const string XmlMalformedDecl = @"Malformed XML declaration.";
+public const string XmlMaxArrayLengthExceeded = @"The maximum array length quota ({0}) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader.";
+
+
+public const string XmlMaxNameTableCharCountExceeded = @"The maximum nametable character count quota ({0}) has been exceeded while reading XML data. The nametable is a data structure used to store strings encountered during XML processing - long XML documents with non-repeating element names, attribute names and attribute values may trigger this quota. This quota may be increased by changing the MaxNameTableCharCount property on the XmlDictionaryReaderQuotas object used when creating the XML reader.";
+
+public const string XmlMethodNotSupported = @"This XmlWriter implementation does not support the '{0}' method.";
+public const string XmlMissingLowSurrogate = @"The surrogate pair is invalid. Missing a low surrogate character.";
+public const string XmlMultipleRootElements = @"There are multiple root elements.";
+public const string XmlNamespaceNotFound = @"The namespace '{0}' is not defined.";
+public const string XmlNestedArraysNotSupported = @"Nested arrays are not supported.";
+public const string XmlNoRootElement = @"The document does not have a root element.";
+public const string XmlOnlyOneRoot = @"Only one root element is permitted per document.";
+public const string XmlOnlyWhitespace = @"Only white space characters can be written with this method.";
+public const string XmlOnlySingleValue = @"Only a single typed value may be written inside an attribute or content.";
+public const string XmlPrefixBoundToNamespace = @"The prefix '{0}' is bound to the namespace '{1}' and cannot be changed to '{2}'.";
+public const string XmlProcessingInstructionNotSupported = @"Processing instructions (other than the XML declaration) and DTDs are not supported.";
+public const string XmlReservedPrefix = @"Prefixes beginning with ""xml"" (regardless of casing) are reserved for use by XML.";
+public const string XmlSpaceBetweenAttributes = @"Whitespace must appear between attributes.";
+public const string XmlSpecificBindingNamespace = @"The namespace '{1}' can only be bound to the prefix '{0}'.";
+public const string XmlSpecificBindingPrefix = @"The prefix '{0}' can only be bound to the namespace '{1}'.";
+public const string XmlStartElementLocalNameNsExpected = @"Start element '{0}' from namespace '{1}' expected. Found {2}.";
+public const string XmlStartElementNameExpected = @"Start element '{0}' expected. Found {1}.";
+public const string XmlTagMismatch = @"Start element '{0}' does not match end element '{1}'.";
+public const string XmlTokenExpected = @"The token '{0}' was expected but found '{1}'.";
+public const string XmlUndefinedPrefix = @"The prefix '{0}' is not defined.";
+public const string XmlUnexpectedEndElement = @"No matching start tag for end element.";
+public const string XmlUnexpectedEndOfFile = @"Unexpected end of file. Following elements are not closed: {0}.";
+public const string XmlWriterClosed = @"The XmlWriter is closed.";
+public const string Xml_InvalidNmToken = @"Invalid NmToken value '{0}'.";
+
+       }
+}
+
+#endregion
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/SR_missing.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/SR_missing.cs
new file mode 100644 (file)
index 0000000..972c50a
--- /dev/null
@@ -0,0 +1,291 @@
+namespace System.Runtime.Serialization
+{
+       static partial class SR
+       {
+
+#region MissingInStrings.txt
+
+//
+// This was retrieved as follows:
+//
+// 1. mcs ReferenceSources/SR.cs -t:library -out:existing.dll
+// 2. mcs {https://raw.githubusercontent.com/mono/mono/wip-serialization-halfway/mcs/class/System.Runtime.Serialization/ReferenceSource/SR.cs} -t:library -out:full.dll
+// 3. csharp -e "System.IO.File.WriteAllLines ("existing.txt", System.Reflection.Assembly.ReflectionOnlyLoadFrom ("existing.dll").GetTypes ().SelectMany (t => t.GetFields ()).Select (f => f.Name).ToArray ())"
+// 4. csharp -e "System.IO.File.WriteAllLines ("full.txt", System.Reflection.Assembly.ReflectionOnlyLoadFrom ("full.dll").GetTypes ().SelectMany (t => t.GetFields ()).Select (f => f.Name).ToArray ())"
+// 5. csharp
+//     var existing = System.IO.File.ReadAllLines ("existing.txt");
+//     var full = System.IO.File.ReadAllLines ("full.txt");
+//  var missing = full.Where (f => !existing.Contains (f));
+//  System.IO.File.WriteAllLines ("missing.cs", missing.Select (m => "public const string " + m + " = @\"" + m + "\";").ToArray ())
+// 6. copy missing.cs contents here.
+//
+
+public const string AbstractElementNotSupported = @"Abstract element '{0}' is not supported.";
+public const string AbstractTypeNotSupported = @"Abstract type is not supported";
+public const string AmbiguousReferencedCollectionTypes1 = @"Ambiguous collection types were referenced: {0}";
+public const string AmbiguousReferencedCollectionTypes3 = @"In '{0}' element in '{1}' namespace, ambiguous collection types were referenced: {2}";
+public const string AmbiguousReferencedTypes1 = @"Ambiguous types were referenced: {0}";
+public const string AmbiguousReferencedTypes3 = @"In '{0}' element in '{1}' namespace, ambiguous types were referenced: {2}";
+public const string AnnotationAttributeNotFound = @"Annotation attribute was not found: default value annotation is '{0}', type is '{1}' in '{2}' namespace, emit default value is {3}.";
+public const string AnonymousTypeNotSupported = @"Anonymous type is not supported. Type is '{0}' in '{1}' namespace.";
+public const string AnyAttributeNotSupported = @"XML Schema 'any' attribute is not supported";
+public const string ArrayItemFormMustBe = @"For array item, element 'form' must be {0}.";
+public const string ArraySizeAttributeIncorrect = @"Array size attribute is incorrect; must be between {0} and {1}.";
+
+public const string ArrayTypeCannotBeImported = @"Array type cannot be imported for '{0}' in '{1}' namespace: {2}.";
+public const string AssemblyNotFound = @"Assembly '{0}' was not found.";
+public const string AttributeNotFound = @"Attribute was not found for CLR type '{1}' in namespace '{0}'. XML reader node is on {2}, '{4}' node in '{3}' namespace.";
+public const string BaseTypeNotISerializable = @"Base type '{0}' in '{1}' namespace is not ISerializable.";
+public const string CannotComputeUniqueName = @"Cannot compute unique name for '{0}'.";
+public const string CannotDeriveFromSealedReferenceType = @"Cannod drive from sealed reference type '{2}', for '{0}' element in '{1}' namespace.";
+public const string CannotDeserializeForwardedType = @"Cannot deserialize forwarded type '{0}'.";
+public const string CannotExportNullAssembly = @"Cannot export null assembly.";
+public const string CannotExportNullKnownType = @"Cannot export null known type.";
+public const string CannotExportNullType = @"Cannot export null type.";
+public const string CannotHaveDuplicateAttributeNames = @"Cannot have duplicate attribute names '{0}'.";
+public const string CannotHaveDuplicateElementNames = @"Cannot have duplicate element names '{0}'.";
+public const string CannotImportInvalidSchemas = @"Cannot import invalid schemas.";
+public const string CannotImportNullDataContractName = @"Cannot import data contract with null name.";
+public const string CannotImportNullSchema = @"Cannot import from schema list that contains null.";
+public const string CannotSetMembersForReferencedType = @"Cannot set members for already referenced type. Base type is '{0}'.";
+public const string CannotSetNamespaceForReferencedType = @"Cannot set namespace for already referenced type. Base type is '{0}'.";
+public const string CannotUseGenericTypeAsBase = @"For '{0}' in '{1}' namespace, generic type cannot be referenced as the base type.";
+public const string ChangingFullTypeNameNotSupported = @"Changing full type name is not supported. Serialization type name: '{0}', data contract type name: '{1}'.";
+public const string CircularTypeReference = @"Circular type reference was found for '{0}' in '{1}' namespace.";
+public const string ClassDataContractReturnedForGetOnlyCollection = @"For '{0}' type, class data contract was returned for get-only collection.";
+public const string CLRNamespaceMappedMultipleTimes = @"CLR namespace is mapped multiple times. Current data contract namespace is '{0}', found '{1}' for CLR namespace '{2}'.";
+public const string ClrTypeNotFound = @"CLR type '{1}' in assembly '{0}' is not found.";
+public const string CollectionAssignedToIncompatibleInterface = @"Collection of type '{0}' is assigned to an incompatible interface '{1}'";
+public const string ComplexTypeRestrictionNotSupported = @"XML schema complexType restriction is not supported.";
+public const string ConfigDataContractSerializerSectionLoadError = @"Failed to load configuration section for dataContractSerializer.";
+public const string ConfigIndexOutOfRange = @"For type '{0}', configuration index is out of range.";
+public const string ConfigMustOnlyAddParamsWithType = @"Configuration parameter element must only add params with type."; // huh? the code doesn't make a lot of sense to me...
+public const string ConfigMustOnlySetTypeOrIndex = @"Configuration parameter element can set only one of either type or index.";
+public const string ConfigMustSetTypeOrIndex = @"Configuration parameter element must set either type or index.";
+public const string CouldNotReadSerializationSchema = @"Could not read serialization schema for '{0}' namespace.";
+public const string DefaultOnElementNotSupported = @"On element '{0}', default value is not supported.";
+public const string DerivedTypeNotISerializable = @"On type '{0}' in '{1}' namespace, derived type is not ISerializable.";
+public const string DupContractInDataContractSet = @"Duplicate contract in data contract set was found, for '{0}' in '{1}' namespace.";
+public const string DuplicateExtensionDataSetMethod = @"Duplicate extension data set method was found, for method '{0}', existing method is '{1}', on data contract type '{2}'.";
+public const string DupTypeContractInDataContractSet = @"Duplicate type contract in data contract set. Type name '{0}', for data contract '{1}' in '{2}' namespace.";
+public const string ElementMaxOccursMustBe = @"On element '{0}', schema element maxOccurs must be 1.";
+public const string ElementMinOccursMustBe = @"On element '{0}', schema element minOccurs must be less or equal to 1.";
+public const string ElementRefOnLocalElementNotSupported = @"For local element, ref is not supported. The referenced name is '{0}' in '{1}' namespace.";
+public const string EnumEnumerationFacetsMustHaveValue = @"Schema enumeration facet must have values.";
+public const string EnumListInAnonymousTypeNotSupported = @"Enum list in anonymous type is not supported.";
+public const string EnumListMustContainAnonymousType = @"Enum list must contain an anonymous type.";
+public const string EnumOnlyEnumerationFacetsSupported = @"For schema facets, only enumeration is supported.";
+public const string EnumRestrictionInvalid = @"For simpleType restriction, only enum is supported and this type could not be convert to enum.";
+public const string EnumTypeCannotBeImported = @"For '{0}' in '{1}' namespace, enum type cannot be imported: {2}";
+public const string EnumTypeNotSupportedByDataContractJsonSerializer = @"Enum type is not supported by DataContractJsonSerializer. The underlying type is '{0}'.";
+public const string EnumUnionInAnonymousTypeNotSupported = @"Enum union in anonymous type is not supported.";
+public const string ExtensionDataSetMustReturnVoid = @"For type '{0}' method '{1}', extension data set method must return void.";
+public const string ExtensionDataSetParameterInvalid = @"For type '{0}' method '{1}', extension data set method has invalid type of parameter '{2}'.";
+public const string FactoryObjectContainsSelfReference = @"Factory object contains a reference to self. Old object is '{0}', new object is '{1}'.";
+public const string FactoryTypeNotISerializable = @"For data contract '{1}', factory type '{0}' is not ISerializable.";
+public const string FixedOnElementNotSupported = @"On schema element '{0}', fixed value is not supported.";
+public const string FlushBufferAlreadyInUse = @"Flush buffer is already in use.";
+public const string FormMustBeQualified = @"On schema element '{0}', form must be qualified.";
+public const string GenericAnnotationAttributeNotFound = @"On type '{0}' Generic annotation attribute '{1}' was not found.";
+public const string GenericAnnotationForNestedLevelMustBeIncreasing = @"On type '{2}', generic annotation for nested level must be increasing. Argument element is '{0}' in '{1}' namespace.";
+public const string GenericAnnotationHasInvalidAttributeValue = @"On type '{2}', generic annotation has invalid attribute value '{3}'. Argument element is '{0}' in '{1}' namespace. Nested level attribute attribute name is '{4}'. Type is '{5}'."; // dunno if this makes sense...
+public const string GenericAnnotationHasInvalidElement = @"On type '{2}', generic annotation has invalid element. Argument element is '{0}' in '{1}' namespace.";
+public const string GenericTypeNameMismatch = @"Generic type name mismatch. Expected '{0}' in '{1}' namespace, got '{2}' in '{3}' namespace instead.";
+public const string GenericTypeNotExportable = @"Generic type '{0}' is not exportable.";
+public const string GetOnlyCollectionMustHaveAddMethod = @"On type '{0}', get-only collection must have an Add method.";
+public const string GetRealObjectReturnedNull = @"On the surrogate data contract for '{0}', GetRealObject method returned null.";
+public const string InvalidAnnotationExpectingText = @"For annotation element '{0}' in namespace '{1}', expected text but got element '{2}' in '{3}' namespace.";
+public const string InvalidAssemblyFormat = @"'{0}': invalid assembly format.";
+public const string InvalidCharacterEncountered = @"Encountered an invalid character '{0}'.";
+public const string InvalidClassDerivation = @"Invalid class derivation from '{0}' in '{1}' namespace.";
+public const string InvalidClrNameGeneratedForISerializable = @"Invalid CLR name '{2}' is generated for ISerializable type '{0}' in '{1}' namespace.";
+public const string InvalidClrNamespaceGeneratedForISerializable = @"Invalid CLR namespace '{3}' is generated for ISerializable type '{0}' in '{1}' namespace. Data contract namespace from the URI would be generated as '{2}'.";
+public const string InvalidDataNode = @"Invalid data node for '{0}' type.";
+public const string InvalidEmitDefaultAnnotation = @"Invalid EmilDefault annotation for '{0}' in type '{1}' in '{2}' namespace.";
+public const string InvalidEnumBaseType = @"Invalid enum base type is specified for type '{0}' in '{1}' namespace, element name is '{2}' in '{3}' namespace.";
+public const string InvalidISerializableDerivation = @"Invalid ISerializable derivation from '{0}' in '{1}' namespace.";
+public const string InvalidKeyValueType = @"'{0}' is an invalid key value type.";
+public const string InvalidKeyValueTypeNamespace = @"'{0}' in '{1}' namespace is an invalid key value type.";
+public const string InvalidReturnSchemaOnGetSchemaMethod = @"On type '{0}', the return value from GetSchema method was invalid.";
+public const string InvalidStateInExtensionDataReader = @"Invalid state in extension data reader.";
+public const string InvalidXmlDeserializingExtensionData = @"Invalid XML while deserializing extension data.";
+public const string IsAnyNotSupportedByNetDataContractSerializer = @"For type '{0}', IsAny is not supported by NetDataContractSerializer.";
+public const string IsDictionaryFormattedIncorrectly = @"IsDictionary formatted value '{0}' is incorrect: {1}";
+public const string ISerializableAssemblyNameSetToZero = @"ISerializable AssemblyName is set to ""0"" for type '{0}'.";
+public const string ISerializableCannotHaveDataContract = @"ISerializable type '{0}' cannot have DataContract.";
+public const string ISerializableContainsMoreThanOneItems = @"ISerializable cannot contain more than one item.";
+public const string ISerializableDerivedContainsOneOrMoreItems = @"Type derived from ISerializable cannot contain more than one item.";
+public const string ISerializableDoesNotContainAny = @"ISerializable does not contain any element.";
+public const string ISerializableMustRefFactoryTypeAttribute = @"ISerializable must have ref attribute that points to its factory type.";
+public const string ISerializableTypeCannotBeImported = @"ISerializable type '{0}' in '{1}' namespace cannot be imported: {2}";
+public const string ISerializableWildcardMaxOccursMustBe = @"ISerializable wildcard maxOccurs must be '{0}'.";
+public const string ISerializableWildcardMinOccursMustBe = @"ISerializable wildcard maxOccurs must be '{0}'.";
+public const string ISerializableWildcardNamespaceInvalid = @"ISerializable wildcard namespace is invalid: '{0}'.";
+public const string ISerializableWildcardProcessContentsInvalid = @"ISerializable wildcard processContents is invalid: '{0}'.";
+public const string IsReferenceGetOnlyCollectionsNotSupported = @"On type '{1}', attribute '{0}' points to get-only collection, which is not supported.";
+public const string IsValueTypeFormattedIncorrectly = @"IsValueType is formatted incorrectly as '{0}': {1}";
+public const string JsonAttributeAlreadyWritten = @"JSON attribute '{0}' is already written.";
+public const string JsonAttributeMustHaveElement = @"JSON attribute must have an owner element.";
+public const string JsonCannotWriteStandaloneTextAfterQuotedText = @"JSON writer cannot write standalone text after quoted text.";
+public const string JsonCannotWriteTextAfterNonTextAttribute = @"JSON writer cannot write text after non-text attribute. Data type is '{0}'.";
+public const string JsonDateTimeOutOfRange = @"JSON DateTime is out of range.";
+public const string JsonDuplicateMemberInInput = @"Duplicate member '{0}' is found in JSON input.";
+public const string JsonDuplicateMemberNames = @"Duplicate member, including '{1}', is found in JSON input, in type '{0}'.";
+public const string JsonEncodingNotSupported = @"JSON Encoding is not supported.";
+public const string JsonEncounteredUnexpectedCharacter = @"Encountered an unexpected character '{0}' in JSON.";
+public const string JsonEndElementNoOpenNodes = @"Encountered an end element while there was no open element in JSON writer.";
+public const string JsonExpectedEncoding = @"Expected encoding '{0}', got '{1}' instead.";
+public const string JsonInvalidBytes = @"Invalid bytes in JSON.";
+public const string JsonInvalidDataTypeSpecifiedForServerType = @"The specified data type is invalid for server type. Type: '{0}', specified data type: '{1}', server type: '{2}', object '{3}'."; // I wonder if this makes sense...
+public const string JsonInvalidDateTimeString = @"Invalid JSON dateTime string is specified: original value '{0}', start guide writer: {1}, end guard writer: {2}.";
+public const string JsonInvalidFFFE = @"FFFE in JSON is invalid.";
+public const string JsonInvalidItemNameForArrayElement = @"Invalid JSON item name '{0}' for array element (item element is '{1}' in JSON).";
+public const string JsonInvalidLocalNameEmpty = @"Empty string is invalid as a local name.";
+public const string JsonInvalidMethodBetweenStartEndAttribute = @"Invalid method call state between start and end attribute.";
+public const string JsonInvalidRootElementName = @"Invalid root element name '{0}' (root element is '{1}' in JSON).";
+public const string JsonInvalidStartElementCall = @"Invalid call to JSON WriteStartElement method.";
+public const string JsonInvalidWriteState = @"Invalid write state {1} for '{0}' method.";
+public const string JsonMethodNotSupported = @"Method {0} is not supported in JSON.";
+public const string JsonMultipleRootElementsNotAllowedOnWriter = @"Multiple root element is not allowed on JSON writer.";
+public const string JsonMustSpecifyDataType = @"On JSON writer data type '{0}' must be specified. Object string is '{1}', server type string is '{2}'.";
+public const string JsonMustUseWriteStringForWritingAttributeValues = @"On JSON writer WriteString must be used for writing attribute values.";
+public const string JsonNamespaceMustBeEmpty = @"JSON namespace is specified as '{0}' but it must be empty.";
+public const string JsonNestedArraysNotSupported = @"Nested array is not supported in JSON: '{0}'";
+public const string JsonNodeTypeArrayOrObjectNotSpecified = @"Either Object or Array of JSON node type must be specified.";
+public const string JsonNoMatchingStartAttribute = @"WriteEndAttribute was called while there is no open attribute.";
+public const string JsonOffsetExceedsBufferSize = @"On JSON writer, offset exceeded buffer size {0}.";
+public const string JsonOneRequiredMemberNotFound = @"Required member {1} in type '{0}' is not found.";
+public const string JsonOnlyWhitespace = @"Only whitespace characters are allowed for {1} method. The specified value is '{0}'";
+public const string JsonOpenAttributeMustBeClosedFirst = @"JSON attribute must be closed first before calling {0} method.";
+public const string JsonPrefixMustBeNullOrEmpty = @"JSON prefix must be null or empty. '{0}' is specified instead.";
+public const string JsonRequiredMembersNotFound = @"Required members {0} in type '{1}' are not found.";
+public const string JsonServerTypeSpecifiedForInvalidDataType = @"Server type is specified for invalid data type in JSON. Server type: '{0}', type: '{1}', dataType: '{2}', object: '{3}'.";
+public const string JsonSizeExceedsRemainingBufferSpace = @"JSON size exceeded remaining buffer space, by {0} byte(s).";
+public const string JsonTypeNotSupportedByDataContractJsonSerializer = @"Type '{0}' is not suppotred by DataContractJsonSerializer.";
+public const string JsonUnexpectedAttributeLocalName = @"Unexpected attribute local name '{0}'.";
+public const string JsonUnexpectedAttributeValue = @"Unexpected attribute value '{0}'.";
+public const string JsonUnexpectedEndOfFile = @"Unexpected end of file in JSON.";
+public const string JsonUnsupportedForIsReference = @"Unsupported value for IsReference for type '{0}', IsReference value is {1}.";
+public const string JsonWriteArrayNotSupported = @"JSON WriteArray is not supported.";
+public const string JsonWriterClosed = @"JSON writer is already closed.";
+public const string JsonXmlInvalidDeclaration = @"Attempt to write invalid XML declration.";
+public const string JsonXmlProcessingInstructionNotSupported = @"processing instruction is not supported in JSON writer.";
+public const string KeyTypeCannotBeParsedInSimpleDictionary = @"Key type '{1}' for collection type '{0}' cannot be parsed in simple dictionary.";
+public const string KnownTypeConfigGenericParamMismatch = @"Generic parameter count do not match between known type and configuration. Type is '{0}', known type has {1} parameters, configuration has {2} parameters.";
+public const string KnownTypeConfigIndexOutOfBounds = @"For known type configuration, index is out of bound. Root type: '{0}' has {1} type arguments, and index was {2}.";
+public const string KnownTypeConfigIndexOutOfBoundsZero = @"For known type configuration, index is out of bound. Root type: '{0}' has {1} type arguments, and index was {2}.";
+public const string KnownTypeConfigObject = @"Known type configuration specifies System.Object.";
+public const string MaxMimePartsExceeded = @"MIME parts number exceeded the maximum settings. Must be less than {0}. Specified as '{1}'.";
+public const string MimeContentTypeHeaderInvalid = @"MIME content type header is invalid.";
+public const string MimeHeaderInvalidCharacter = @"MIME header has an invalid character ('{0}', {1} in hexadecimal value).";
+public const string MimeMessageGetContentStreamCalledAlready = @"On MimeMessage, GetContentStream method is already called.";
+public const string MimeReaderHeaderAlreadyExists = @"MIME header '{0}' already exists.";
+public const string MimeReaderMalformedHeader = @"Malformed MIME header.";
+public const string MimeReaderResetCalledBeforeEOF = @"On MimeReader, Reset method is called before EOF.";
+public const string MimeReaderTruncated = @"MIME parts are truncated.";
+public const string MimeVersionHeaderInvalid = @"MIME version header is invalid.";
+public const string MimeWriterInvalidStateForClose = @"MIME writer is at invalid state for closing.";
+public const string MimeWriterInvalidStateForContent = @"MIME writer is at invalid state for content.";
+public const string MimeWriterInvalidStateForHeader = @"MIME writer is at invalid state for header.";
+public const string MimeWriterInvalidStateForStartPart = @"MIME writer is at invalid state for starting a part.";
+public const string MimeWriterInvalidStateForStartPreface = @"MIME writer is at invalid state for starting preface.";
+public const string MissingSchemaType = @"Schema type '{0}' is missing and required for '{1}' type.";
+public const string MixedContentNotSupported = @"Mixed content is not supported.";
+public const string MtomBoundaryInvalid = @"MIME boundary is invalid: '{0}'.";
+public const string MtomBufferQuotaExceeded = @"MTOM buffer quota exceeded. The maximum size is {0}.";
+public const string MtomContentTransferEncodingNotPresent = @"MTOM content transfer encoding is not present. ContentTransferEncoding header is '{0}'.";
+public const string MtomContentTransferEncodingNotSupported = @"MTOM content transfer encoding value is not supported. Raw value is '{0}', '{1}' in 7bit encoding, '{2}' in 8bit encoding, and '{3}' in binary.";
+public const string MtomContentTypeInvalid = @"MTOM content type is invalid.";
+public const string MtomDataMustNotContainXopInclude = @"MTOM data must not contain xop:Include element. '{0}' element in '{1}' namespace.";
+public const string MtomExceededMaxSizeInBytes = @"MTOM exceeded max size in bytes. The maximum size is {0}.";
+public const string MtomInvalidCIDUri = @"Invalid MTOM CID URI: '{0}'.";
+public const string MtomInvalidEmptyURI = @"empty URI is invalid for MTOM MIME part.";
+public const string MtomInvalidStartUri = @"Invalid MTOM start URI: '{0}'.";
+public const string MtomInvalidTransferEncodingForMimePart = @"Invalid transfer encoding for MIME part: '{0}', in binary: '{1}'.";
+public const string MtomMessageContentTypeNotFound = @"MTOM message content type was not found.";
+public const string MtomMessageInvalidContent = @"MTOM message content is invalid.";
+public const string MtomMessageInvalidContentInMimePart = @"MTOM message content in MIME part is invalid.";
+public const string MtomMessageInvalidMimeVersion = @"MTOM message has invalid MIME version. Expected '{1}', got '{0}' instead.";
+public const string MtomMessageNotApplicationXopXml = @"MTOM msssage type is not '{0}'.";
+public const string MtomMessageNotMultipart = @"MTOM message is not multipart: media type should be '{0}', media subtype should be '{1}'.";
+public const string MtomMessageRequiredParamNotSpecified = @"Required MTOM parameter '{0}' is not specified.";
+public const string MtomMimePartReferencedMoreThanOnce = @"Specified MIME part '{0}' is referenced more than once.";
+public const string MtomPartNotFound = @"MTOM part with URI '{0}' is not found.";
+public const string MtomRootContentTypeNotFound = @"MTOM root content type is not found.";
+public const string MtomRootNotApplicationXopXml = @"MTOM root should have media type '{0}' and subtype '{1}'.";
+public const string MtomRootPartNotFound = @"MTOM root part is not found.";
+public const string MtomRootRequiredParamNotSpecified = @"Required MTOM root parameter '{0}' is not specified.";
+public const string MtomRootUnexpectedCharset = @"Unexpected charset on MTOM root. Expected '{1}', got '{0}' instead.";
+public const string MtomRootUnexpectedType = @"Unexpected type on MTOM root. Expected '{1}', got '{0}' instead.";
+public const string MtomXopIncludeHrefNotSpecified = @"xop Include element did not specify '{0}' attribute.";
+public const string MtomXopIncludeInvalidXopAttributes = @"xop Include element has invalid attribute: '{0}' in '{1}' namespace.";
+public const string MtomXopIncludeInvalidXopElement = @"xop Include element has invalid element: '{0}' in '{1}' namespace.";
+public const string MustContainOnlyLocalElements = @"Only local elements can be imported.";
+public const string NoAsyncWritePending = @"No async write operation is pending.";
+public const string NonOptionalFieldMemberOnIsReferenceSerializableType = @"For type '{0}', non-optional field member '{1}' is on the Serializable type that has IsReference as {2}.";
+public const string OnlyDataContractTypesCanHaveExtensionData = @"On '{0}' type, only DataContract types can have extension data.";
+public const string PartialTrustISerializableNoPublicConstructor = @"Partial trust access required for the constructor on the ISerializable type '{0}'";
+public const string QueryGeneratorPathToMemberNotFound = @"The path to member was not found for XPath query generator.";
+public const string ReadNotSupportedOnStream = @"Read operation is not supported on the Stream.";
+public const string ReadOnlyClassDeserialization = @"Error on deserializing read-only members in the class: {0}";
+public const string ReadOnlyCollectionDeserialization = @"Error on deserializing read-only collection: {0}";
+public const string RecursiveCollectionType = @"Type '{0}' involves recursive collection.";
+public const string RedefineNotSupported = @"XML Schema 'redefine' is not supported.";
+public const string ReferencedBaseTypeDoesNotExist = @"Referenced base type does not exist. Data contract name: '{0}' in '{1}' namespace, expected type: '{2}' in '{3}' namespace. Collection can be '{4}' or '{5}'."; // is it the expected message? I'm quite unsure.
+public const string ReferencedCollectionTypesCannotContainNull = @"Referenced collection types cannot contain null.";
+public const string ReferencedTypeDoesNotMatch = @"Referenced type '{0}' does not match the expected type '{1}' in '{2}' namespace.";
+public const string ReferencedTypeMatchingMessage = @"Reference type matches.";
+public const string ReferencedTypeNotMatchingMessage = @"Reference type does not match.";
+public const string ReferencedTypesCannotContainNull = @"Referenced types cannot contain null.";
+public const string RequiresClassDataContractToSetIsISerializable = @"To set IsISerializable, class data cotnract is required.";
+public const string RootParticleMustBeSequence = @"Root particle must be sequence to be imported.";
+public const string RootSequenceMaxOccursMustBe = @"On root sequence, maxOccurs must be 1.";
+public const string RootSequenceMustBeRequired = @"Root sequence must have an item and minOccurs must be 1.";
+public const string SeekNotSupportedOnStream = @"Seek operation is not supported on this Stream.";
+public const string SerializationInfo_ConstructorNotFound = @"Constructor that takes SerializationInfo and StreamingContext is not found for '{0}'.";
+public const string SimpleContentNotSupported = @"Simple content is not supported.";
+public const string SimpleTypeRestrictionDoesNotSpecifyBase = @"This simpleType restriction does not specify the base type.";
+public const string SimpleTypeUnionNotSupported = @"simpleType union is not supported.";
+public const string SpecifiedTypeNotFoundInSchema = @"Specified type '{0}' in '{1}' namespace is not found in the schemas.";
+public const string SubstitutionGroupOnElementNotSupported = @"substitutionGroups on elements are not supported.";
+public const string SurrogatesWithGetOnlyCollectionsNotSupported = @"Surrogates with get-only collections are not supported. Type '{1}' contains '{2}' which is of '{0}' type.";
+public const string SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser = @"Surrogates with get-only collections are not supported. Found on type '{0}'.";
+public const string TopLevelElementRepresentsDifferentType = @"Top-level element represents a different type. Expected '{0}' type in '{1}' namespace.";
+public const string TraceCodeElementIgnored = @"Element ignored";
+public const string TraceCodeFactoryTypeNotFound = @"Factory type not found";
+public const string TraceCodeObjectWithLargeDepth = @"Object with large depth";
+public const string TraceCodeReadObjectBegin = @"ReadObject begins";
+public const string TraceCodeReadObjectEnd = @"ReadObject ends";
+public const string TraceCodeWriteObjectBegin = @"WriteObject begins";
+public const string TraceCodeWriteObjectContentBegin = @"WriteObjectContent begins";
+public const string TraceCodeWriteObjectContentEnd = @"WriteObjectContent ends";
+public const string TraceCodeWriteObjectEnd = @"WriteObject ends";
+public const string TraceCodeXsdExportAnnotationFailed = @"XSD export annotation failed";
+public const string TraceCodeXsdExportBegin = @"XSD export begins";
+public const string TraceCodeXsdExportDupItems = @"XSD export duplicate items";
+public const string TraceCodeXsdExportEnd = @"XSD export ends";
+public const string TraceCodeXsdExportError = @"XSD export error";
+public const string TraceCodeXsdImportAnnotationFailed = @"XSD import annotation failed";
+public const string TraceCodeXsdImportBegin = @"XSD import begins";
+public const string TraceCodeXsdImportEnd = @"XSD import ends";
+public const string TraceCodeXsdImportError = @"XSD import error";
+public const string TypeCannotBeForwardedFrom = @"Type '{0}' in assembly '{1}' cannot be forwarded from assembly '{2}'.";
+public const string TypeCannotBeImported = @"Type '{0}' in '{1}' namespace cannot be imported: {2}";
+public const string TypeCannotBeImportedHowToFix = @"Type cannot be imported: {0}"; // I cannot see where HowToFix is given from...
+public const string TypeHasNotBeenImported = @"Type '{0}' in '{1}' namespace has not been imported.";
+public const string TypeMustBeIXmlSerializable = @"Type '{0}' must be IXmlSerializable. Contract type: '{1}', contract name: '{2}' in '{3}' namespace.";
+public const string TypeShouldNotContainAttributes = @"Type should not contain attributes. Serialization namespace: '{0}'.";
+public const string UnknownXmlType = @"Unknown XML type: '{0}'.";
+public const string WriteBufferOverflow = @"Write buffer overflow.";
+public const string WriteNotSupportedOnStream = @"Write operation is not supported on this '{0}' Stream.";
+public const string XmlCanonicalizationNotStarted = @"XML canonicalization was not started.";
+public const string XmlCanonicalizationStarted = @"XML canonicalization started";
+public const string XmlMaxArrayLengthOrMaxItemsQuotaExceeded = @"XML max array length or max items quota exceeded. It must be less than {0}.";
+public const string XmlMaxBytesPerReadExceeded = @"XML max bytes per read exceeded. It must be less than {0}.";
+public const string XmlMaxDepthExceeded = @"XML max depth exceeded. It must be less than {0}.";
+public const string XmlMaxStringContentLengthExceeded = @"XML max string content length exceeded. It must be less than {0}.";
+public const string XmlObjectAssignedToIncompatibleInterface = @"Object of type '{0}' is assigned to an incompatible interface '{1}'.";
+
+#endregion
+       }
+}
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/SchemaExporter_mobile.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/SchemaExporter_mobile.cs
new file mode 100644 (file)
index 0000000..aa55440
--- /dev/null
@@ -0,0 +1,223 @@
+
+namespace System.Runtime.Serialization
+{
+       using System;
+       using System.Collections;
+       using System.Collections.Generic;
+       using System.Collections.ObjectModel;
+       using System.Diagnostics;
+       using System.Globalization;
+       using System.IO;
+       using System.Reflection;
+       using System.Runtime.Diagnostics;
+       using System.ServiceModel.Diagnostics;
+       using System.Security;
+       using System.Xml;
+       using System.Xml.Schema;
+       using System.Xml.Serialization;
+       using System.Runtime.Serialization.Diagnostics;
+
+       class SchemaExporter
+       {
+        internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
+        {
+            if (IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot))
+                return;
+            XmlSchemaSet schemas = new XmlSchemaSet();
+            schemas.XmlResolver = null;
+            InvokeSchemaProviderMethod(type, schemas, out stableName, out xsdType, out hasRoot);
+            if (stableName.Name == null || stableName.Name.Length == 0)
+                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type))));
+        }
+
+        internal static bool IsSpecialXmlType(Type type, out XmlQualifiedName typeName, out XmlSchemaType xsdType, out bool hasRoot)
+        {
+            xsdType = null;
+            hasRoot = true;
+            if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray)
+            {
+                string name = null;
+                if (type == Globals.TypeOfXmlElement)
+                {
+                    xsdType = CreateAnyElementType();
+                    name = "XmlElement";
+                    hasRoot = false;
+                }
+                else
+                {
+                    xsdType = CreateAnyType();
+                    name = "ArrayOfXmlNode";
+                    hasRoot = true;
+                }
+                typeName = new XmlQualifiedName(name, DataContract.GetDefaultStableNamespace(type));
+                return true;
+            }
+            typeName = null;
+            return false;
+        }
+
+        static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
+        {
+            xsdType = null;
+            hasRoot = true;
+            object[] attrs = clrType.GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, false);
+            if (attrs == null || attrs.Length == 0)
+            {
+                stableName = DataContract.GetDefaultStableName(clrType);
+                return false;
+            }
+
+            XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0];
+            if (provider.IsAny)
+            {
+                xsdType = CreateAnyElementType();
+                hasRoot = false;
+            }
+            string methodName = provider.MethodName;
+            if (methodName == null || methodName.Length == 0)
+            {
+                if (!provider.IsAny)
+                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))));
+                stableName = DataContract.GetDefaultStableName(clrType);
+            }
+            else
+            {
+                MethodInfo getMethod = clrType.GetMethod(methodName,  /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null);
+                if (getMethod == null)
+                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName)));
+
+                if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType)))
+                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType))));
+
+                object typeInfo = getMethod.Invoke(null, new object[] { schemas });
+
+                if (provider.IsAny)
+                {
+                    if (typeInfo != null)
+                        throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidNonNullReturnValueByIsAny, DataContract.GetClrTypeFullName(clrType), methodName)));
+                    stableName = DataContract.GetDefaultStableName(clrType);
+                }
+                else if (typeInfo == null)
+                {
+                    xsdType = CreateAnyElementType();
+                    hasRoot = false;
+                    stableName = DataContract.GetDefaultStableName(clrType);
+                }
+                else
+                {
+                    XmlSchemaType providerXsdType = typeInfo as XmlSchemaType;
+                    if (providerXsdType != null)
+                    {
+                        string typeName = providerXsdType.Name;
+                        string typeNs = null;
+                        if (typeName == null || typeName.Length == 0)
+                        {
+                            DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs);
+                            stableName = new XmlQualifiedName(typeName, typeNs);
+                            providerXsdType.Annotation = GetSchemaAnnotation(ExportActualType(stableName, new XmlDocument()));
+                            xsdType = providerXsdType;
+                        }
+                        else
+                        {
+                            foreach (XmlSchema schema in schemas.Schemas())
+                            {
+                                foreach (XmlSchemaObject schemaItem in schema.Items)
+                                {
+                                    if ((object)schemaItem == (object)providerXsdType)
+                                    {
+                                        typeNs = schema.TargetNamespace;
+                                        if (typeNs == null)
+                                            typeNs = String.Empty;
+                                        break;
+                                    }
+                                }
+                                if (typeNs != null)
+                                    break;
+                            }
+                            if (typeNs == null)
+                                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.MissingSchemaType, typeName, DataContract.GetClrTypeFullName(clrType))));
+                            stableName = new XmlQualifiedName(typeName, typeNs);
+                        }
+                    }
+                    else
+                        stableName = (XmlQualifiedName)typeInfo;
+                }
+            }
+            return true;
+        }
+
+        static XmlSchemaComplexType CreateAnyElementType()
+        {
+            XmlSchemaComplexType anyElementType = new XmlSchemaComplexType();
+            anyElementType.IsMixed = false;
+            anyElementType.Particle = new XmlSchemaSequence();
+            XmlSchemaAny any = new XmlSchemaAny();
+            any.MinOccurs = 0;
+            any.ProcessContents = XmlSchemaContentProcessing.Lax;
+            ((XmlSchemaSequence)anyElementType.Particle).Items.Add(any);
+            return anyElementType;
+        }
+
+        static XmlSchemaAnnotation GetSchemaAnnotation(params XmlNode[] nodes)
+        {
+            if (nodes == null || nodes.Length == 0)
+                return null;
+            bool hasAnnotation = false;
+            for (int i = 0; i < nodes.Length; i++)
+                if (nodes[i] != null)
+                {
+                    hasAnnotation = true;
+                    break;
+                }
+            if (!hasAnnotation)
+                return null;
+
+            XmlSchemaAnnotation annotation = new XmlSchemaAnnotation();
+            XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo();
+            annotation.Items.Add(appInfo);
+            appInfo.Markup = nodes;
+            return annotation;
+        }
+
+        static XmlSchemaComplexType CreateAnyType()
+        {
+            XmlSchemaComplexType anyType = new XmlSchemaComplexType();
+            anyType.IsMixed = true;
+            anyType.Particle = new XmlSchemaSequence();
+            XmlSchemaAny any = new XmlSchemaAny();
+            any.MinOccurs = 0;
+            any.MaxOccurs = Decimal.MaxValue;
+            any.ProcessContents = XmlSchemaContentProcessing.Lax;
+            ((XmlSchemaSequence)anyType.Particle).Items.Add(any);
+            anyType.AnyAttribute = new XmlSchemaAnyAttribute();
+            return anyType;
+        }
+
+        static XmlElement ExportActualType(XmlQualifiedName typeName, XmlDocument xmlDoc)
+        {
+            XmlElement actualTypeElement = xmlDoc.CreateElement(ActualTypeAnnotationName.Name, ActualTypeAnnotationName.Namespace);
+
+            XmlAttribute nameAttribute = xmlDoc.CreateAttribute(Globals.ActualTypeNameAttribute);
+            nameAttribute.Value = typeName.Name;
+            actualTypeElement.Attributes.Append(nameAttribute);
+
+            XmlAttribute nsAttribute = xmlDoc.CreateAttribute(Globals.ActualTypeNamespaceAttribute);
+            nsAttribute.Value = typeName.Namespace;
+            actualTypeElement.Attributes.Append(nsAttribute);
+
+            return actualTypeElement;
+        }
+
+        static XmlQualifiedName actualTypeAnnotationName;
+        internal static XmlQualifiedName ActualTypeAnnotationName
+        {
+            get
+            {
+                if (actualTypeAnnotationName == null)
+                    actualTypeAnnotationName = new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace);
+                return actualTypeAnnotationName;
+            }
+        }
+       }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/SimplifiedCodeTypeReference.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/SimplifiedCodeTypeReference.cs
new file mode 100644 (file)
index 0000000..6fdb45d
--- /dev/null
@@ -0,0 +1,398 @@
+// This is a revised source code from CodeDom.
+
+//------------------------------------------------------------------------------
+// <copyright file="CodeTypeReference.cs" company="Microsoft">
+// 
+// <OWNER>[....]</OWNER>
+//     Copyright (c) Microsoft Corporation.  All rights reserved.
+// </copyright>                                                                
+//------------------------------------------------------------------------------
+
+namespace System.Runtime.Serialization {
+
+    using System.Diagnostics;
+    using System;
+    using Microsoft.Win32;
+    using System.Collections;
+    using System.Collections.Generic;
+    using System.Runtime.InteropServices;
+    using System.Runtime.Serialization;
+    using System.Globalization;
+    
+    enum CodeTypeReferenceOptions {
+        GlobalReference =  0x00000001,
+        GenericTypeParameter = 0x00000002
+    }
+
+    class CodeTypeReference {
+        private string baseType;
+        [OptionalField] 
+        private bool isInterface;
+        private int arrayRank;
+        private CodeTypeReference arrayElementType;
+        [OptionalField] 
+        private List<CodeTypeReference> typeArguments;
+        [OptionalField]
+        private CodeTypeReferenceOptions referenceOptions;
+        [OptionalField]
+        private bool needsFixup = false;
+        
+        public CodeTypeReference() {
+            baseType = string.Empty;
+            this.arrayRank = 0;
+            this.arrayElementType = null;            
+        }
+
+        public CodeTypeReference(Type type) {
+            if (type == null)
+                throw new ArgumentNullException("type");
+            
+            if (type.IsArray) {
+                this.arrayRank = type.GetArrayRank();
+                this.arrayElementType = new CodeTypeReference(type.GetElementType());
+                this.baseType = null;
+            } else {
+                InitializeFromType(type);
+                this.arrayRank = 0;
+                this.arrayElementType = null;
+            }
+
+            this.isInterface = type.IsInterface;
+        }
+
+        public CodeTypeReference (Type type, CodeTypeReferenceOptions codeTypeReferenceOption) : this(type) {
+            referenceOptions = codeTypeReferenceOption;
+        }
+        
+        public CodeTypeReference (String typeName, CodeTypeReferenceOptions codeTypeReferenceOption) {
+            Initialize(typeName, codeTypeReferenceOption);
+        }
+
+        /// <devdoc>
+        ///    <para>[To be supplied.]</para>
+        /// </devdoc>
+
+        // We support the reflection format for generice type name.
+        // The format is like:
+        //
+        public CodeTypeReference(string typeName) {
+            Initialize(typeName);
+        }
+
+        private void InitializeFromType(Type type) {
+            baseType = type.Name;
+            if (!type.IsGenericParameter) {
+                Type currentType = type;
+                while (currentType.IsNested) {
+                    currentType = currentType.DeclaringType;
+                    baseType = currentType.Name + "+" + baseType;
+                }
+                if (!String.IsNullOrEmpty(type.Namespace))
+                    baseType = type.Namespace + "." + baseType;
+            }
+
+            // pick up the type arguments from an instantiated generic type but not an open one    
+            if (type.IsGenericType && !type.ContainsGenericParameters) {
+                Type[] genericArgs = type.GetGenericArguments();
+                for (int i = 0; i < genericArgs.Length; i++) {
+                    TypeArguments.Add(new CodeTypeReference(genericArgs[i]));
+                }
+            }
+            else if (!type.IsGenericTypeDefinition) 
+            {
+                // if the user handed us a non-generic type, but later
+                // appends generic type arguments, we'll pretend
+                // it's a generic type for their sake - this is good for
+                // them if they pass in System.Nullable class when they
+                // meant the System.Nullable<T> value type.
+                needsFixup = true;
+            }
+        }
+
+        private void Initialize(string typeName) {
+            Initialize(typeName, this.referenceOptions);
+        }
+
+        private void Initialize(string typeName, CodeTypeReferenceOptions options)
+        {
+            Options = options;
+            if (typeName == null || typeName.Length == 0) {
+                typeName = typeof(void).FullName;            
+                this.baseType = typeName;
+                this.arrayRank = 0;
+                this.arrayElementType = null;
+                return;                
+            }
+
+            typeName = RipOffAssemblyInformationFromTypeName(typeName);
+            
+            int end = typeName.Length -1;
+            int current = end;
+            needsFixup = true;      // default to true, and if we find arity or generic type args, we'll clear the flag.
+            
+            // Scan the entire string for valid array tails and store ranks for array tails
+            // we found in a queue.
+            Queue q = new Queue();
+            while(current >= 0) {
+                int rank = 1;
+                if( typeName[current--] == ']') {
+                    while(current >=0 && typeName[current] == ',') {
+                        rank++;
+                        current--;
+                    }
+
+                    if( current>=0 && typeName[current] == '[') { // found a valid array tail
+                        q.Enqueue(rank); 
+                        current--;   
+                        end = current; 
+                        continue;
+                    }
+                }
+                break;
+            }
+            
+            // Try find generic type arguments
+            current = end;
+            ArrayList typeArgumentList = new ArrayList();
+            Stack subTypeNames = new Stack();
+            if( current > 0 && typeName[current--] == ']') {
+                needsFixup = false;
+                int unmatchedRightBrackets = 1;
+                int subTypeNameEndIndex = end;
+                
+                // Try find the matching '[', if we can't find it, we will not try to parse the string
+                while(current >= 0) {
+                    if( typeName[current] == '[' ) {      
+                        // break if we found matched brackets
+                        if( --unmatchedRightBrackets == 0) break;
+                    }
+                    else if( typeName[current] == ']' ) {                   
+                        ++unmatchedRightBrackets;
+                    }
+                    else if( typeName[current] == ',' && unmatchedRightBrackets == 1) {
+                        //
+                        // Type name can contain nested generic types. Following is an example:
+                        // System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], 
+                        //          [System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], 
+                        //           mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
+                        // 
+                        // Spliltting by ',' won't work. We need to do first-level split by ','. 
+                        //
+                        if( current + 1 < subTypeNameEndIndex) {
+                            subTypeNames.Push(typeName.Substring(current+1 , subTypeNameEndIndex - current - 1));                            
+                        }
+
+                        subTypeNameEndIndex = current;
+                        
+                    }    
+                    --current;
+                }
+            
+                if( current > 0 && (end - current - 1) > 0) { 
+                    // push the last generic type argument name if there is any
+                    if( current + 1 < subTypeNameEndIndex) {
+                        subTypeNames.Push(typeName.Substring(current+1 , subTypeNameEndIndex - current - 1));                                                    
+                    }
+                        
+                    // we found matched brackets and the brackets contains some characters.                    
+                    while( subTypeNames.Count > 0) {
+                        String name = RipOffAssemblyInformationFromTypeName((string)subTypeNames.Pop());                         
+                        typeArgumentList.Add(new CodeTypeReference(name));
+                    }
+                    end = current - 1;
+                }
+            }
+
+            if( end < 0) {  // this can happen if we have some string like "[...]"
+                this.baseType = typeName;
+                return;
+            }
+
+            if (q.Count > 0 ) {             
+                
+                CodeTypeReference type = new CodeTypeReference(typeName.Substring(0, end + 1), Options);
+
+                for(int i = 0; i < typeArgumentList.Count; i++) {
+                    type.TypeArguments.Add((CodeTypeReference)typeArgumentList[i]);
+                }
+
+                while( q.Count > 1) {
+                    type = new CodeTypeReference( type, (int)q.Dequeue());  
+                } 
+                
+                // we don't need to create a new CodeTypeReference for the last one.
+                Debug.Assert(q.Count == 1 , "We should have one and only one in the rank queue.");                                
+                this.baseType = null;
+                this.arrayRank = (int)q.Dequeue();
+                this.arrayElementType = type;
+            }
+            else if( typeArgumentList.Count > 0 ) {
+                for( int i = 0; i < typeArgumentList.Count; i++) {
+                    TypeArguments.Add((CodeTypeReference)typeArgumentList[i]);
+                }
+
+                this.baseType = typeName.Substring(0, end + 1);
+            }
+            else{
+                this.baseType = typeName;
+            }
+
+            // Now see if we have some arity.  baseType could be null if this is an array type. 
+            if (baseType != null && baseType.IndexOf('`') != -1)
+                needsFixup = false;
+            
+        }
+
+        public CodeTypeReference(string typeName, params CodeTypeReference[] typeArguments) : this(typeName){
+            if( typeArguments != null && typeArguments.Length > 0) {
+                TypeArguments.AddRange(typeArguments);
+            }
+        }
+
+        /// <devdoc>
+        ///    <para>[To be supplied.]</para>
+        /// </devdoc>
+        public CodeTypeReference(string baseType, int rank) {
+            this.baseType = null;
+            this.arrayRank = rank;
+            this.arrayElementType = new CodeTypeReference(baseType);
+        }
+
+        /// <devdoc>
+        ///    <para>[To be supplied.]</para>
+        /// </devdoc>
+        public CodeTypeReference(CodeTypeReference arrayType, int rank) {
+            this.baseType = null;
+            this.arrayRank = rank;
+            this.arrayElementType = arrayType;
+        }
+        /// <devdoc>
+        ///    <para>[To be supplied.]</para>
+        /// </devdoc>
+        public CodeTypeReference ArrayElementType {
+            get {
+                return arrayElementType;
+            }
+            set {
+                arrayElementType = value;
+            }
+        }
+
+        /// <devdoc>
+        ///    <para>[To be supplied.]</para>
+        /// </devdoc>
+        public int ArrayRank {
+            get {
+                return arrayRank;
+            }
+            set {
+                arrayRank = value;
+            }
+        }
+
+        internal int NestedArrayDepth {
+            get {
+                
+                if (arrayElementType == null)
+                    return 0;
+
+                return 1 + arrayElementType.NestedArrayDepth;
+            }
+        }
+
+        /// <devdoc>
+        ///    <para>[To be supplied.]</para>
+        /// </devdoc>
+        public string BaseType {
+            get {
+                if (arrayRank > 0 && arrayElementType != null) {
+                    return arrayElementType.BaseType;
+                }
+                if (String.IsNullOrEmpty(baseType)) 
+                    return string.Empty;
+                
+                string returnType = baseType;
+                if (needsFixup && TypeArguments.Count > 0)
+                    returnType = returnType + '`' + TypeArguments.Count.ToString(CultureInfo.InvariantCulture);
+
+                return returnType;
+                
+            }
+            set {
+                baseType = value;
+                Initialize(baseType);
+            }
+        }
+
+        [System.Runtime.InteropServices.ComVisible(false)]
+        public CodeTypeReferenceOptions Options {
+            get { return referenceOptions;}
+            set { referenceOptions = value;}            
+        }
+
+        [System.Runtime.InteropServices.ComVisible(false)]        
+        public List<CodeTypeReference> TypeArguments{ 
+            get {
+                if (arrayRank > 0 && arrayElementType != null) {
+                    return arrayElementType.TypeArguments;
+                }
+
+                if( typeArguments == null) {
+                    typeArguments = new List<CodeTypeReference>();
+                }
+                return typeArguments;
+            }
+        }
+
+        internal bool IsInterface {
+            get {
+                // Note that this only works correctly if the Type ctor was used. Otherwise, it's always false.
+                return this.isInterface;
+            }
+        }
+
+        //
+        // The string for generic type argument might contain assembly information and square bracket pair.
+        // There might be leading spaces in front the type name.
+        // Following function will rip off assembly information and brackets 
+        // Following is an example:
+        // " [System.Collections.Generic.List[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral,
+        //   PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]"
+        //
+        private string RipOffAssemblyInformationFromTypeName(string typeName) {
+            int start = 0;
+            int end = typeName.Length - 1;
+            string result = typeName;
+            
+            // skip white space in the beginning
+            while( start < typeName.Length && Char.IsWhiteSpace(typeName[start])) start++;
+            while( end >= 0 && Char.IsWhiteSpace(typeName[end])) end--;
+                    
+            if(start < end) {
+                if (typeName[start] =='[' && typeName[end] == ']') {  
+                    start++;
+                    end--;
+                }
+
+                // if we still have a ] at the end, there's no assembly info. 
+                if (typeName[end] != ']') {
+                    int commaCount = 0;                            
+                    for(int index = end; index >= start; index--) {
+                        if( typeName[index] == ',') {
+                            commaCount++;
+                            if( commaCount == 4) {
+                                result = typeName.Substring( start, index - start); 
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+
+            return result;
+        }
+    }
+}
+    
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlDataContract_static.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlDataContract_static.cs
new file mode 100644 (file)
index 0000000..c8829ad
--- /dev/null
@@ -0,0 +1,53 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Xml;
+using System.Xml.Serialization;
+
+namespace System.Runtime.Serialization
+{
+       internal partial class XmlDataContract
+       {
+        internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate()
+        {
+                               return () => new XmlDataContractInterpreter (this).CreateXmlSerializable ();
+               }
+       }
+       
+       internal class XmlDataContractInterpreter
+       {
+               XmlDataContract contract;
+               
+               public XmlDataContractInterpreter (XmlDataContract contract)
+               {
+                       this.contract = contract;
+               }
+               
+               public IXmlSerializable CreateXmlSerializable ()
+               {
+                       Type type = contract.UnderlyingType;
+                       object value = null;
+                       if (type.IsValueType)
+                               value = FormatterServices.GetUninitializedObject (type);
+                       else
+                               value = GetConstructor ().Invoke (new object [0]);
+                       return (IXmlSerializable) value;
+               }
+
+               ConstructorInfo GetConstructor ()
+               {
+                       Type type = contract.UnderlyingType;
+
+                       if (type.IsValueType)
+                               return null;
+
+                       ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
+                       if (ctor == null)
+                               throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
+
+                       return ctor;
+               }
+       }
+}
+
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlExceptionHelper.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlExceptionHelper.cs
new file mode 100644 (file)
index 0000000..f088bf5
--- /dev/null
@@ -0,0 +1,288 @@
+//------------------------------------------------------------
+// Copyright (c) Microsoft Corporation.  All rights reserved.
+//------------------------------------------------------------
+using System.Runtime.Serialization;
+////using System.ServiceModel.Channels;
+using System.Globalization;
+using System.Runtime.Serialization.Diagnostics.Application;
+
+using SR_ = System.Runtime.Serialization.SR;
+
+namespace System.Xml
+{
+    static class XmlExceptionHelper
+    {
+        static void ThrowXmlException(XmlDictionaryReader reader, string res)
+        {
+            ThrowXmlException(reader, res, null);
+        }
+
+        static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1)
+        {
+            ThrowXmlException(reader, res, arg1, null);
+        }
+
+        static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2)
+        {
+            ThrowXmlException(reader, res, arg1, arg2, null);
+        }
+
+        static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2, string arg3)
+        {
+            string s = SR_.GetString(res, arg1, arg2, arg3);
+            IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+            if (lineInfo != null && lineInfo.HasLineInfo())
+            {
+                s += " " + SR_.GetString(SR_.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
+            }
+
+            if (TD.ReaderQuotaExceededIsEnabled())
+            {
+                TD.ReaderQuotaExceeded(s);
+            }
+
+            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s));
+        }
+
+        static public void ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
+        {
+            string s = exception.Message;
+            IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+            if (lineInfo != null && lineInfo.HasLineInfo())
+            {
+                s += " " + SR_.GetString(SR_.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
+            }
+            throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s));
+        }
+
+        static string GetName(string prefix, string localName)
+        {
+            if (prefix.Length == 0)
+                return localName;
+            else
+                return string.Concat(prefix, ":", localName);
+        }
+
+        static string GetWhatWasFound(XmlDictionaryReader reader)
+        {
+            if (reader.EOF)
+                return SR_.GetString(SR_.XmlFoundEndOfFile);
+            switch (reader.NodeType)
+            {
+                case XmlNodeType.Element:
+                    return SR_.GetString(SR_.XmlFoundElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
+                case XmlNodeType.EndElement:
+                    return SR_.GetString(SR_.XmlFoundEndElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
+                case XmlNodeType.Text:
+                case XmlNodeType.Whitespace:
+                case XmlNodeType.SignificantWhitespace:
+                    return SR_.GetString(SR_.XmlFoundText, reader.Value);
+                case XmlNodeType.Comment:
+                    return SR_.GetString(SR_.XmlFoundComment, reader.Value);
+                case XmlNodeType.CDATA:
+                    return SR_.GetString(SR_.XmlFoundCData, reader.Value);
+            }
+            return SR_.GetString(SR_.XmlFoundNodeType, reader.NodeType);
+        }
+
+        static public void ThrowStartElementExpected(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlStartElementExpected, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowStartElementExpected(XmlDictionaryReader reader, string name)
+        {
+            ThrowXmlException(reader, SR_.XmlStartElementNameExpected, name, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowStartElementExpected(XmlDictionaryReader reader, string localName, string ns)
+        {
+            ThrowXmlException(reader, SR_.XmlStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns)
+        {
+            ThrowStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns));
+        }
+
+        static public void ThrowFullStartElementExpected(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlFullStartElementExpected, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowFullStartElementExpected(XmlDictionaryReader reader, string name)
+        {
+            ThrowXmlException(reader, SR_.XmlFullStartElementNameExpected, name, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowFullStartElementExpected(XmlDictionaryReader reader, string localName, string ns)
+        {
+            ThrowXmlException(reader, SR_.XmlFullStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowFullStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns)
+        {
+            ThrowFullStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns));
+        }
+
+        static public void ThrowEndElementExpected(XmlDictionaryReader reader, string localName, string ns)
+        {
+            ThrowXmlException(reader, SR_.XmlEndElementExpected, localName, ns, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, int maxStringContentLength)
+        {
+            ThrowXmlException(reader, SR_.XmlMaxStringContentLengthExceeded, maxStringContentLength.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowMaxArrayLengthExceeded(XmlDictionaryReader reader, int maxArrayLength)
+        {
+            ThrowXmlException(reader, SR_.XmlMaxArrayLengthExceeded, maxArrayLength.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(XmlDictionaryReader reader, int maxQuota)
+        {
+            ThrowXmlException(reader, SR_.XmlMaxArrayLengthOrMaxItemsQuotaExceeded, maxQuota.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowMaxDepthExceeded(XmlDictionaryReader reader, int maxDepth)
+        {
+            ThrowXmlException(reader, SR_.XmlMaxDepthExceeded, maxDepth.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowMaxBytesPerReadExceeded(XmlDictionaryReader reader, int maxBytesPerRead)
+        {
+            ThrowXmlException(reader, SR_.XmlMaxBytesPerReadExceeded, maxBytesPerRead.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowMaxNameTableCharCountExceeded(XmlDictionaryReader reader, int maxNameTableCharCount)
+        {
+            ThrowXmlException(reader, SR_.XmlMaxNameTableCharCountExceeded, maxNameTableCharCount.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowBase64DataExpected(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlBase64DataExpected, GetWhatWasFound(reader));
+        }
+
+        static public void ThrowUndefinedPrefix(XmlDictionaryReader reader, string prefix)
+        {
+            ThrowXmlException(reader, SR_.XmlUndefinedPrefix, prefix);
+        }
+
+        static public void ThrowProcessingInstructionNotSupported(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlProcessingInstructionNotSupported);
+        }
+
+        static public void ThrowInvalidXml(XmlDictionaryReader reader, byte b)
+        {
+            ThrowXmlException(reader, SR_.XmlInvalidXmlByte, b.ToString("X2", CultureInfo.InvariantCulture));
+        }
+
+        static public void ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlUnexpectedEndOfFile, ((XmlBaseReader)reader).GetOpenElements());
+        }
+
+        static public void ThrowUnexpectedEndElement(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlUnexpectedEndElement);
+        }
+
+        static public void ThrowTokenExpected(XmlDictionaryReader reader, string expected, char found)
+        {
+            ThrowXmlException(reader, SR_.XmlTokenExpected, expected, found.ToString());
+        }
+
+        static public void ThrowTokenExpected(XmlDictionaryReader reader, string expected, string found)
+        {
+            ThrowXmlException(reader, SR_.XmlTokenExpected, expected, found);
+        }
+
+        static public void ThrowInvalidCharRef(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlInvalidCharRef);
+        }
+
+        static public void ThrowTagMismatch(XmlDictionaryReader reader, string expectedPrefix, string expectedLocalName, string foundPrefix, string foundLocalName)
+        {
+            ThrowXmlException(reader, SR_.XmlTagMismatch, GetName(expectedPrefix, expectedLocalName), GetName(foundPrefix, foundLocalName));
+        }
+
+        static public void ThrowDuplicateXmlnsAttribute(XmlDictionaryReader reader, string localName, string ns)
+        {
+            string name;
+            if (localName.Length == 0)
+                name = "xmlns";
+            else
+                name = "xmlns:" + localName;
+            ThrowXmlException(reader, SR_.XmlDuplicateAttribute, name, name, ns);
+        }
+
+        static public void ThrowDuplicateAttribute(XmlDictionaryReader reader, string prefix1, string prefix2, string localName, string ns)
+        {
+            ThrowXmlException(reader, SR_.XmlDuplicateAttribute, GetName(prefix1, localName), GetName(prefix2, localName), ns);
+        }
+
+        static public void ThrowInvalidBinaryFormat(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlInvalidFormat);
+        }
+
+        static public void ThrowInvalidRootData(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlInvalidRootData);
+        }
+
+        static public void ThrowMultipleRootElements(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlMultipleRootElements);
+        }
+
+        static public void ThrowDeclarationNotFirst(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlDeclNotFirst);
+        }
+
+        static public void ThrowConversionOverflow(XmlDictionaryReader reader, string value, string type)
+        {
+            ThrowXmlException(reader, SR_.XmlConversionOverflow, value, type);
+        }
+
+        static public void ThrowXmlDictionaryStringIDOutOfRange(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlDictionaryStringIDRange, XmlDictionaryString.MinKey.ToString(NumberFormatInfo.CurrentInfo), XmlDictionaryString.MaxKey.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowXmlDictionaryStringIDUndefinedStatic(XmlDictionaryReader reader, int key)
+        {
+            ThrowXmlException(reader, SR_.XmlDictionaryStringIDUndefinedStatic, key.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowXmlDictionaryStringIDUndefinedSession(XmlDictionaryReader reader, int key)
+        {
+            ThrowXmlException(reader, SR_.XmlDictionaryStringIDUndefinedSession, key.ToString(NumberFormatInfo.CurrentInfo));
+        }
+
+        static public void ThrowEmptyNamespace(XmlDictionaryReader reader)
+        {
+            ThrowXmlException(reader, SR_.XmlEmptyNamespaceRequiresNullPrefix);
+        }
+
+        static public XmlException CreateConversionException(string value, string type, Exception exception)
+        {
+            return new XmlException(SR_.GetString(SR_.XmlInvalidConversion, value, type), exception);
+        }
+
+        static public XmlException CreateEncodingException(byte[] buffer, int offset, int count, Exception exception)
+        {
+            return CreateEncodingException(new System.Text.UTF8Encoding(false, false).GetString(buffer, offset, count), exception);
+        }
+
+        static public XmlException CreateEncodingException(string value, Exception exception)
+        {
+            return new XmlException(SR_.GetString(SR_.XmlInvalidUTF8Bytes, value), exception);
+        }
+    }
+}
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlFormatReaderGenerator_static.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlFormatReaderGenerator_static.cs
new file mode 100644 (file)
index 0000000..8b81bec
--- /dev/null
@@ -0,0 +1,618 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Xml;
+
+namespace System.Runtime.Serialization
+{
+       internal partial class XmlFormatReaderGenerator
+       {
+               partial class CriticalHelper
+               {
+                       internal XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
+                       {
+                               return (XmlReaderDelegator xr, XmlObjectSerializerReadContext ctx, XmlDictionaryString [] memberNames, XmlDictionaryString [] memberNamespaces) => new XmlFormatReaderInterpreter (classContract).ReadFromXml (xr, ctx, memberNames, memberNamespaces);
+                       }
+
+                       internal XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
+                       {
+                               return (XmlReaderDelegator xr, XmlObjectSerializerReadContext ctx, XmlDictionaryString inm, XmlDictionaryString ins, CollectionDataContract cc) => new XmlFormatReaderInterpreter (collectionContract, false).ReadCollectionFromXml (xr, ctx, inm, ins, cc);
+                       }
+                       
+                       internal XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
+                       {
+                               return (XmlReaderDelegator xr, XmlObjectSerializerReadContext ctx, XmlDictionaryString inm, XmlDictionaryString ins, CollectionDataContract cc) => new XmlFormatReaderInterpreter (collectionContract, true).ReadGetOnlyCollectionFromXml (xr, ctx, inm, ins, cc);
+                       }
+               }
+       }
+
+       class XmlFormatReaderInterpreter
+       {
+               public XmlFormatReaderInterpreter (ClassDataContract classContract)
+               {
+                       this.classContract = classContract;
+               }
+
+               public XmlFormatReaderInterpreter (CollectionDataContract collectionContract, bool isGetOnly)
+               {
+                       this.collectionContract = collectionContract;
+                       this.is_get_only_collection = isGetOnly;
+               }
+
+               bool is_get_only_collection;
+
+               ClassDataContract classContract;
+
+               CollectionDataContract collectionContract;
+
+               object objectLocal;
+               Type objectType;
+               XmlReaderDelegator xmlReader;
+               XmlObjectSerializerReadContext context;
+
+               XmlDictionaryString [] memberNames = null;
+               XmlDictionaryString [] memberNamespaces = null;
+               XmlDictionaryString itemName = null;
+               XmlDictionaryString itemNamespace = null;
+
+               public object ReadFromXml (XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces)
+               {
+                       // InitArgs()
+                       this.xmlReader = xmlReader;
+                       this.context = context;
+                       this.memberNames = memberNames;
+                       this.memberNamespaces = memberNamespaces;
+                       
+                       //DemandSerializationFormatterPermission(classContract);
+                       //DemandMemberAccessPermission(memberAccessFlag);
+                       CreateObject (classContract);
+                       
+                       context.AddNewObject (objectLocal);
+                       InvokeOnDeserializing (classContract);
+            
+            string objectId = null;
+            
+                       if (HasFactoryMethod (classContract))
+                               objectId = context.GetObjectId ();
+                       if (classContract.IsISerializable)
+                               ReadISerializable (classContract);
+                       else
+                               ReadClass (classContract);
+                       bool isFactoryType = InvokeFactoryMethod (classContract, objectId);
+                       if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom (classContract.UnderlyingType))
+                               ((IDeserializationCallback) objectLocal).OnDeserialization (null);
+                       InvokeOnDeserialized(classContract);
+                       if (objectId == null || !isFactoryType) {
+
+                               // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization.
+                               // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation
+                               // on DateTimeOffset; which does not work in partial trust.
+
+                               if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
+                                       objectLocal = DateTimeOffsetAdapter.GetDateTimeOffset ((DateTimeOffsetAdapter) objectLocal);
+                               // else - do we have to call CodeInterpreter.ConvertValue()? I guess not...
+                       }
+                       return objectLocal;
+               }
+               
+               public object ReadCollectionFromXml (XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract)
+               {
+                       #region GenerateCollectionReaderHelper
+                       // InitArgs()
+                       this.xmlReader = xmlReader;
+                       this.context = context;
+                       this.itemName = itemName;
+                       this.itemNamespace = itemNamespace;
+
+                       this.collectionContract = collectionContract;
+
+                       #endregion
+
+                       ReadCollection (collectionContract);
+
+                       return objectLocal;
+               }
+               
+               public void ReadGetOnlyCollectionFromXml (XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract)
+               {
+                       #region GenerateCollectionReaderHelper
+                       // InitArgs()
+                       this.xmlReader = xmlReader;
+                       this.context = context;
+                       this.itemName = itemName;
+                       this.itemNamespace = itemNamespace;
+
+                       this.collectionContract = collectionContract;
+
+                       #endregion
+
+                       ReadGetOnlyCollection (collectionContract);
+               }
+
+               void CreateObject (ClassDataContract classContract)
+               {
+                       Type type = objectType = classContract.UnderlyingType;
+                       if (type.IsValueType && !classContract.IsNonAttributedType)
+                               type = Globals.TypeOfValueType;
+
+                       if (classContract.UnderlyingType == Globals.TypeOfDBNull)
+                               objectLocal = DBNull.Value;
+                       else if (classContract.IsNonAttributedType) {
+                               if (type.IsValueType)
+                                       objectLocal = FormatterServices.GetUninitializedObject (type);
+                               else
+                                       objectLocal = classContract.GetNonAttributedTypeConstructor ().Invoke (new object [0]);
+                       }
+                       else
+                               objectLocal = CodeInterpreter.ConvertValue (XmlFormatReaderGenerator.UnsafeGetUninitializedObject (DataContract.GetIdForInitialization (classContract)), Globals.TypeOfObject, type);
+               }
+
+               void InvokeOnDeserializing (ClassDataContract classContract)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnDeserializing (classContract.BaseContract);
+                       if (classContract.OnDeserializing != null)
+                               classContract.OnDeserializing.Invoke (objectLocal, new object [] {context.GetStreamingContext ()});
+               }
+
+               void InvokeOnDeserialized (ClassDataContract classContract)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnDeserialized (classContract.BaseContract);
+                       if (classContract.OnDeserialized != null)
+                               classContract.OnDeserialized.Invoke (objectLocal, new object [] {context.GetStreamingContext ()});
+               }
+
+               bool HasFactoryMethod (ClassDataContract classContract)
+               {
+                       return Globals.TypeOfIObjectReference.IsAssignableFrom (classContract.UnderlyingType);
+               }
+
+               bool InvokeFactoryMethod (ClassDataContract classContract, string objectId)
+               {
+                       if (HasFactoryMethod (classContract)) {
+                               objectLocal = CodeInterpreter.ConvertValue (context.GetRealObject ((IObjectReference) objectLocal, objectId), Globals.TypeOfObject, classContract.UnderlyingType);
+                               return true;
+                       }
+                       return false;
+               }
+
+               void ReadISerializable (ClassDataContract classContract)
+               {
+                       ConstructorInfo ctor = classContract.GetISerializableConstructor ();
+                       context.ReadSerializationInfo (xmlReader, classContract.UnderlyingType);
+                       ctor.Invoke (objectLocal, new object [] {context.GetStreamingContext ()});
+               }
+
+               void ReadClass (ClassDataContract classContract)
+               {
+                       if (classContract.HasExtensionData) {
+                               ExtensionDataObject extensionData = new ExtensionDataObject ();
+                               ReadMembers (classContract, extensionData);
+                               ClassDataContract currentContract = classContract;
+                               while (currentContract != null) {
+                                       MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
+                                       if (extensionDataSetMethod != null)
+                                               extensionDataSetMethod.Invoke (objectLocal, new object [] {extensionData});
+                                       currentContract = currentContract.BaseContract;
+                               }
+                       }
+                       else
+                               ReadMembers (classContract, null);
+               }
+
+               void ReadMembers (ClassDataContract classContract, ExtensionDataObject  extensionData)
+               {
+                       int memberCount = classContract.MemberNames.Length;
+                       context.IncrementItemCount (memberCount);
+
+                       int memberIndex = -1;
+                       
+                       int firstRequiredMember;
+                       bool[] requiredMembers = GetRequiredMembers (classContract, out firstRequiredMember);
+                       bool hasRequiredMembers = (firstRequiredMember < memberCount);
+                       int requiredIndex = hasRequiredMembers ? firstRequiredMember : memberCount;
+
+                       while (XmlObjectSerializerReadContext.MoveToNextElement (xmlReader)) {
+                               int idx; // used as in "switch (idx)" in the original source.
+                               if (hasRequiredMembers)
+                                       idx = context.GetMemberIndexWithRequiredMembers (xmlReader, memberNames, memberNamespaces, memberIndex, (int) requiredIndex, extensionData);
+                               else
+                                       idx = context.GetMemberIndex (xmlReader, memberNames, memberNamespaces, memberIndex, extensionData);
+
+                               if (memberCount > 0)
+                                       ReadMembers (idx, classContract, requiredMembers, ref memberIndex, ref requiredIndex);
+                       }
+
+                       if (hasRequiredMembers)
+                       {
+                               if (requiredIndex < memberCount)
+                                       XmlObjectSerializerReadContext.ThrowRequiredMemberMissingException (xmlReader, memberIndex, requiredIndex, memberNames);
+                       }
+               }
+
+               int ReadMembers (int index, ClassDataContract classContract, bool [] requiredMembers, ref int memberIndex, ref int requiredIndex)
+               {
+                       int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers (index, classContract.BaseContract, requiredMembers,
+                       ref memberIndex, ref requiredIndex);
+                       
+                       if (memberCount <= index && index < memberCount + classContract.Members.Count) {
+                               DataMember dataMember = classContract.Members [index - memberCount];
+                               Type memberType = dataMember.MemberType;
+                               if (dataMember.IsRequired) {
+                                       int nextRequiredIndex = index + 1;
+                                       for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++)
+                                               if (requiredMembers [nextRequiredIndex])
+                                                       break;
+                                       requiredIndex = nextRequiredIndex;
+                               }
+
+                               if (dataMember.IsGetOnlyCollection) {
+                                       var value = CodeInterpreter.GetMember (dataMember.MemberInfo, objectLocal);
+                                       context.StoreCollectionMemberInfo (value);
+                                       ReadValue (memberType, dataMember.Name, classContract.StableName.Namespace);
+                               } else {
+                                       var value = ReadValue (memberType, dataMember.Name, classContract.StableName.Namespace);
+                                       CodeInterpreter.SetMember (dataMember.MemberInfo, objectLocal, value);
+                               }
+                               memberIndex = index;
+                       }
+                       return memberCount + classContract.Members.Count;
+               }
+
+               bool[] GetRequiredMembers (ClassDataContract contract, out int firstRequiredMember)
+               {
+                       int memberCount = contract.MemberNames.Length;
+                       bool [] requiredMembers = new bool [memberCount];
+                       GetRequiredMembers (contract, requiredMembers);
+                       for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++)
+                               if (requiredMembers [firstRequiredMember])
+                                       break;
+                       return requiredMembers;
+               }
+
+               int GetRequiredMembers (ClassDataContract contract, bool[] requiredMembers)
+               {
+                       int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers (contract.BaseContract, requiredMembers);
+                       List<DataMember> members = contract.Members;
+                       for (int i = 0; i < members.Count; i++, memberCount++)
+                               requiredMembers [memberCount] = members [i].IsRequired;
+                       return memberCount;
+               }
+
+               object ReadValue (Type type, string name, string ns)
+               {
+                       var valueType = type;
+                       object value = null;
+                       bool shouldAssignNullableValue = false;
+                       int nullables = 0;
+                       while (type.IsGenericType && type.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
+                               nullables++;
+                               type = type.GetGenericArguments () [0];
+                       }
+                       
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract (type);
+                       if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) {
+                               context.ReadAttributes (xmlReader);
+                               string objectId = context.ReadIfNullOrRef (xmlReader, type, DataContract.IsTypeSerializable (type));
+                               // Deserialize null
+                if (objectId == Globals.NullObjectId) {
+                                       
+                                       if (nullables != 0)
+                                               value = Activator.CreateInstance (valueType);
+                                       else if (type.IsValueType)
+                                               throw new SerializationException (SR.GetString (SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName (type)));
+                                       else
+                                               value = null;
+                               } else if (objectId == string.Empty) {
+                                       // Deserialize value
+
+                                       // Compare against Globals.NewObjectId, which is set to string.Empty
+                                       
+                                       objectId = context.GetObjectId ();
+                                       
+                                       if (type.IsValueType) {
+                                               if (!string.IsNullOrEmpty (objectId))
+                                                       throw new SerializationException (SR.GetString (SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
+                                       }
+                                       object innerValueRead = null;
+                                       if (nullables != 0)
+                                               shouldAssignNullableValue = true;
+
+                                       if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) {
+                                               value = primitiveContract.XmlFormatReaderMethod.Invoke (xmlReader, new object [0]);
+                                               if (!type.IsValueType)
+                                                       context.AddNewObject (value);
+                                       }
+                                       else
+                                                       value = InternalDeserialize (type, name, ns);
+                               } else {
+                                       // Deserialize ref
+                                       if (type.IsValueType)
+                                               throw new SerializationException (SR.GetString (SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName (type)));
+                                       else
+                                               value = CodeInterpreter.ConvertValue (context.GetExistingObject (objectId, type, name, ns), Globals.TypeOfObject, type);
+                               }
+
+                               if (shouldAssignNullableValue) {
+                                       if (objectId != Globals.NullObjectId)
+                                               value = WrapNullableObject (type, value, valueType, nullables);
+                               }
+                       }
+                       else
+                               value = InternalDeserialize (type, name, ns);
+
+                       return value;
+               }
+
+               object InternalDeserialize (Type type, string name, string ns)
+               {
+                       Type declaredType = type.IsPointer ? Globals.TypeOfReflectionPointer : type;
+                       var obj = context.InternalDeserialize (xmlReader, DataContract.GetId (declaredType.TypeHandle), declaredType.TypeHandle, name, ns);
+
+                       if (type.IsPointer)
+                               // wow, there is no way to convert void* to object in strongly typed way...
+                               return XmlFormatGeneratorStatics.UnboxPointer.Invoke (null, new object [] {obj});
+                       else
+                               return CodeInterpreter.ConvertValue (obj, Globals.TypeOfObject, type);
+               }
+
+               object WrapNullableObject (Type innerType, object innerValue, Type outerType, int nullables)
+               {
+                       var outerValue = innerValue;
+                       for (int i = 1; i < nullables; i++) {
+                               Type type = Globals.TypeOfNullable.MakeGenericType (innerType);
+                               outerValue = Activator.CreateInstance (type, new object[] { outerValue });
+                               innerType = type;
+                       }
+                       return Activator.CreateInstance (outerType, new object[] { outerValue });
+               }
+
+
+               void ReadCollection (CollectionDataContract collectionContract)
+               {
+                       Type type = collectionContract.UnderlyingType;
+                       Type itemType = collectionContract.ItemType;
+                       bool isArray = (collectionContract.Kind == CollectionKind.Array);
+
+                       ConstructorInfo constructor = collectionContract.Constructor;
+
+                       if (type.IsInterface) {
+                               switch (collectionContract.Kind) {
+                               case CollectionKind.GenericDictionary:
+                                       type = Globals.TypeOfDictionaryGeneric.MakeGenericType (itemType.GetGenericArguments ());
+                                       constructor = type.GetConstructor (BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
+                                       break;
+                               case CollectionKind.Dictionary:
+                                       type = Globals.TypeOfHashtable;
+                                       constructor = XmlFormatGeneratorStatics.HashtableCtor;
+                                       break;
+                               case CollectionKind.Collection:
+                               case CollectionKind.GenericCollection:
+                               case CollectionKind.Enumerable:
+                               case CollectionKind.GenericEnumerable:
+                               case CollectionKind.List:
+                               case CollectionKind.GenericList:
+                                       type = itemType.MakeArrayType ();
+                                       isArray = true;
+                                       break;
+                               }
+                       }
+                       string itemName = collectionContract.ItemName;
+                       string itemNs = collectionContract.StableName.Namespace;
+
+                       if (!isArray) {
+                               if (type.IsValueType)
+                                       // FIXME: this is not what the original code does.
+                                       objectLocal = FormatterServices.GetUninitializedObject (type);
+                               else {
+                                       objectLocal = constructor.Invoke (new object [0]);
+                                       context.AddNewObject (objectLocal);
+                               }
+                       }
+
+                       int size = context.GetArraySize ();
+
+                       string objectId = context.GetObjectId ();
+
+                       bool canReadPrimitiveArray = false, readResult = false;
+                       if (isArray && TryReadPrimitiveArray (type, itemType, size, out readResult))
+                               canReadPrimitiveArray = true;
+
+                       if (!readResult) {
+                               if (size == -1) {
+
+                                       object growingCollection = null;
+                                       if (isArray)
+                                               growingCollection = Array.CreateInstance (itemType, 32);
+
+                                       int i = 0;
+                                       // FIXME: I cannot find i++ part, but without that it won't work as expected.
+                                       for (; i < int.MaxValue; i++) {
+                                               if (IsStartElement (this.itemName, this.itemNamespace)) {
+                                                       context.IncrementItemCount (1);
+                                                       object value = ReadCollectionItem (collectionContract, itemType, itemName, itemNs);
+                                                       if (isArray) {
+                                                               MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod (itemType);
+                                                               growingCollection = ensureArraySizeMethod.Invoke (null, new object [] {growingCollection, i});
+                                                               ((Array) growingCollection).SetValue (value, i);
+                                                       } else {
+                                                               StoreCollectionValue (objectLocal, itemType, value, collectionContract);
+                                                       }
+                                               }
+                                               else if (IsEndElement ())
+                                                       break;
+                                               else
+                                                       HandleUnexpectedItemInCollection (ref i);
+                                       }
+
+                                       if (isArray) {
+                                               MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod (itemType);
+                                               objectLocal = trimArraySizeMethod.Invoke (null, new object [] {growingCollection, i});
+                                               context.AddNewObjectWithId (objectId, objectLocal);
+                                       }
+                               } else {
+                                       context.IncrementItemCount (size);
+                                       if (isArray) {
+                                               objectLocal = Array.CreateInstance (itemType, size);
+                                               context.AddNewObject (objectLocal);
+                                       }
+                                       // FIXME: I cannot find j++ part, but without that it won't work as expected.
+                                       for (int j = 0; j < size; j++) {
+                                               if (IsStartElement (this.itemName, this.itemNamespace)) {
+                                                       var itemValue = ReadCollectionItem (collectionContract, itemType, itemName, itemNs);
+                                                       if (isArray)
+                                                               ((Array) objectLocal).SetValue (itemValue, j);
+                                                       else
+                                                               StoreCollectionValue (objectLocal, itemType, itemValue, collectionContract);
+                                               }
+                                               else
+                                                       HandleUnexpectedItemInCollection (ref j);
+                                       }
+                                       context.CheckEndOfArray (xmlReader, size, this.itemName, this.itemNamespace);
+                               }
+                       }
+                       if (canReadPrimitiveArray)
+                               context.AddNewObjectWithId (objectId, objectLocal);
+               }
+
+               void ReadGetOnlyCollection (CollectionDataContract collectionContract)
+               {
+                       Type type = collectionContract.UnderlyingType;
+                       Type itemType = collectionContract.ItemType;
+                       bool isArray = (collectionContract.Kind == CollectionKind.Array);
+                       string itemName = collectionContract.ItemName;
+                       string itemNs = collectionContract.StableName.Namespace;
+
+                       objectLocal = context.GetCollectionMember ();
+
+                       //check that items are actually going to be deserialized into the collection
+                       if (IsStartElement (this.itemName, this.itemNamespace)) {
+                               if (objectLocal == null)
+                                       XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException (type);
+                               else {
+                                       int size = 0;
+                                       if (isArray)
+                                               size = ((Array) objectLocal).Length;
+                                       context.AddNewObject (objectLocal);
+                                       for (int i = 0; i < int.MaxValue;) {
+                                               if (IsStartElement (this.itemName, this.itemNamespace)) {
+                                                       context.IncrementItemCount (1);
+                                                       var value = ReadCollectionItem (collectionContract, itemType, itemName, itemNs);
+                                                       if (isArray) {
+                                                               if (size == i)
+                                                                       XmlObjectSerializerReadContext.ThrowArrayExceededSizeException (size, type);
+                                                               else
+                                                                       ((Array) objectLocal).SetValue (value, i);
+                                                       } else {
+                                                               StoreCollectionValue (objectLocal, itemType, value, collectionContract);
+                                                       }
+                                               }
+                                               else if (IsEndElement())
+                                                       break;
+                                               else
+                                                       HandleUnexpectedItemInCollection (ref i);
+                                       }
+                                       context.CheckEndOfArray (xmlReader, size, this.itemName, this.itemNamespace);
+                               }
+                       }
+               }
+
+               bool TryReadPrimitiveArray (Type type, Type itemType, int size, out bool readResult)
+               {
+                       readResult = false;
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract (itemType);
+                       if (primitiveContract == null)
+                               return false;
+
+                       string readArrayMethod = null;
+                       switch (Type.GetTypeCode (itemType))
+                       {
+                       case TypeCode.Boolean:
+                               readArrayMethod = "TryReadBooleanArray";
+                       break;
+                       case TypeCode.DateTime:
+                               readArrayMethod = "TryReadDateTimeArray";
+                       break;
+                       case TypeCode.Decimal:
+                               readArrayMethod = "TryReadDecimalArray";
+                       break;
+                       case TypeCode.Int32:
+                               readArrayMethod = "TryReadInt32Array";
+                       break;
+                       case TypeCode.Int64:
+                               readArrayMethod = "TryReadInt64Array";
+                       break;
+                       case TypeCode.Single:
+                               readArrayMethod = "TryReadSingleArray";
+                       break;
+                       case TypeCode.Double:
+                               readArrayMethod = "TryReadDoubleArray";
+                               break;
+                       default:
+                               break;
+                       }
+                       if (readArrayMethod != null) {
+                               var mi = typeof (XmlReaderDelegator).GetMethod (readArrayMethod, Globals.ScanAllMembers);
+                               var args = new object [] {context, itemName, itemNamespace, size, objectLocal};
+                               readResult = (bool) mi.Invoke (xmlReader, args);
+                               objectLocal = args.Last ();
+                               return true;
+                       }
+                       return false;
+               }
+
+               object ReadCollectionItem (CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs)
+               {
+                       if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) {
+                               context.ResetAttributes ();
+                               return CodeInterpreter.ConvertValue (collectionContract.ItemContract.ReadXmlValue (xmlReader, context), Globals.TypeOfObject, itemType);
+                       }
+                       else
+                               return ReadValue (itemType, itemName, itemNs);
+               }
+
+               void StoreCollectionValue (object collection, Type valueType, object value, CollectionDataContract collectionContract)
+               {
+                       if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) {
+                               ClassDataContract keyValuePairContract = DataContract.GetDataContract (valueType) as ClassDataContract;
+                               if (keyValuePairContract == null)
+                                       Fx.Assert ("Failed to create contract for KeyValuePair type");
+                               DataMember keyMember = keyValuePairContract.Members [0];
+                               DataMember valueMember = keyValuePairContract.Members [1];
+                               object pkey = CodeInterpreter.GetMember (keyMember.MemberInfo, value);
+                               object pvalue = CodeInterpreter.GetMember (valueMember.MemberInfo, value);
+                               
+                               collectionContract.AddMethod.Invoke (collection, new object [] {pkey, pvalue});
+                       }
+                       else
+                               collectionContract.AddMethod.Invoke (collection, new object [] {value});
+               }
+
+               void HandleUnexpectedItemInCollection (ref int iterator)
+               {
+                       if (IsStartElement ()) {
+                               context.SkipUnknownElement (xmlReader);
+                               iterator--;
+                       }
+                       else 
+                               throw XmlObjectSerializerReadContext.CreateUnexpectedStateException (XmlNodeType.Element, xmlReader);
+               }
+
+               bool IsStartElement(XmlDictionaryString name, XmlDictionaryString ns)
+               {
+                       return xmlReader.IsStartElement (name, ns);
+               }
+
+               bool IsStartElement()
+               {
+                       return xmlReader.IsStartElement ();
+               }
+
+               bool IsEndElement ()
+               {
+                       return xmlReader.NodeType == XmlNodeType.EndElement;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlFormatWriterGenerator_static.cs b/mcs/class/System.Runtime.Serialization/ReferenceSources/XmlFormatWriterGenerator_static.cs
new file mode 100644 (file)
index 0000000..4399a0c
--- /dev/null
@@ -0,0 +1,617 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Xml;
+
+namespace System.Runtime.Serialization
+{
+       internal partial class XmlFormatWriterGenerator
+       {
+               partial class CriticalHelper
+               {
+                       internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
+                       {
+                               return (XmlWriterDelegator xw, object obj, XmlObjectSerializerWriteContext ctx, ClassDataContract ctr) => new XmlFormatWriterInterpreter (classContract).WriteToXml (xw, obj, ctx, ctr);
+                       }
+
+                       internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
+                       {
+                               return (XmlWriterDelegator xw, object obj, XmlObjectSerializerWriteContext ctx, CollectionDataContract ctr) => new XmlFormatWriterInterpreter (collectionContract).WriteCollectionToXml (xw, obj, ctx, ctr);
+                       }
+               }
+       }
+
+       class XmlFormatWriterInterpreter
+       {
+               public XmlFormatWriterInterpreter (ClassDataContract classContract)
+               {
+                       this.classContract = classContract;
+               }
+
+               public XmlFormatWriterInterpreter (CollectionDataContract collectionContract)
+               {
+                       this.collectionContract = collectionContract;
+               }
+
+               ClassDataContract classContract;
+
+               CollectionDataContract collectionContract;
+
+               XmlWriterDelegator writer = null;
+               object obj = null;
+               XmlObjectSerializerWriteContext ctx = null;
+               DataContract dataContract = null;
+               object objLocal = null;
+
+               ClassDataContract classDataContract {
+                       get { return (ClassDataContract) dataContract; }
+               }
+               CollectionDataContract collectionDataContract {
+                       get {return (CollectionDataContract) dataContract; }
+               }
+
+               XmlDictionaryString [] contractNamespaces = null;
+               XmlDictionaryString [] memberNames = null;
+               XmlDictionaryString [] childElementNamespaces = null;
+               int typeIndex = 1;
+               int childElementIndex = 0;
+
+               public void WriteToXml (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract)
+               {
+                       this.writer = xmlWriter;
+                       this.obj = obj;
+                       this.ctx = context;
+                       this.dataContract = dataContract;
+
+                       InitArgs (classContract.UnderlyingType);
+
+                       // DemandSerializationFormatterPermission (classContract) - irrelevant
+                       // DemandMemberAccessPermission (memberAccessFlag) - irrelevant
+
+                       if (classContract.IsReadOnlyContract)
+                       {
+                               DataContract.ThrowInvalidDataContractException (classContract.SerializationExceptionMessage, null);
+                       }
+
+                       WriteClass (classContract);
+               }
+
+               public void WriteCollectionToXml (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract collectionContract)
+               {
+                       this.writer = xmlWriter;
+                       this.obj = obj;
+                       this.ctx = context;
+                       this.dataContract = collectionContract;
+
+                       InitArgs (collectionContract.UnderlyingType);                   
+
+                       // DemandMemberAccessPermission(memberAccessFlag);
+                       if (collectionContract.IsReadOnlyContract)
+                       {
+                               DataContract.ThrowInvalidDataContractException (collectionContract.SerializationExceptionMessage, null);
+                       }
+
+                       WriteCollection (collectionContract);
+               }
+
+               void InitArgs (Type objType)
+               {
+                       if (objType == Globals.TypeOfDateTimeOffsetAdapter) {
+                               objLocal = DateTimeOffsetAdapter.GetDateTimeOffsetAdapter ((DateTimeOffset) obj);
+                       }
+                       else
+                               objLocal = CodeInterpreter.ConvertValue (obj, typeof (object), objType);
+               }
+
+               void InvokeOnSerializing (ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext ctx)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnSerializing (classContract.BaseContract, objSerialized, ctx);
+                       if (classContract.OnSerializing != null) {
+                               classContract.OnSerializing.Invoke (objSerialized, new object [] {ctx.GetStreamingContext ()});
+                       }
+               }
+
+               void InvokeOnSerialized (ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext ctx)
+               {
+                       if (classContract.BaseContract != null)
+                               InvokeOnSerialized (classContract.BaseContract, objSerialized, ctx);
+                       if (classContract.OnSerialized != null) {
+                               classContract.OnSerialized.Invoke (objSerialized, new object [] {ctx.GetStreamingContext ()});
+                       }
+               }
+
+               void WriteClass (ClassDataContract classContract)
+               {
+                       InvokeOnSerializing (classContract, objLocal, ctx);
+
+                       if (classContract.IsISerializable)
+                               ctx.WriteISerializable (writer, (ISerializable) objLocal);
+                       else
+                       {
+                               if (classContract.ContractNamespaces.Length > 1)
+                                       contractNamespaces = classDataContract.ContractNamespaces;
+                               memberNames = classDataContract.MemberNames;
+
+                               for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++)
+                               {
+                                       if (classContract.ChildElementNamespaces[i] != null)
+                                       {
+                                               childElementNamespaces = classDataContract.ChildElementNamespaces;
+                                       }
+                               }
+
+                               if (classContract.HasExtensionData)
+                               {
+                                       ExtensionDataObject extensionData = ((IExtensibleDataObject) objLocal).ExtensionData;
+                                       ctx.WriteExtensionData (writer, extensionData, -1);
+
+                                       WriteMembers (classContract, extensionData, classContract);
+                               }
+                               else
+                                       WriteMembers (classContract, null, classContract);
+                       }
+                       InvokeOnSerialized (classContract, objLocal, ctx);
+               }
+
+               void WriteCollection(CollectionDataContract collectionContract)
+               {
+                       XmlDictionaryString itemNamespace = dataContract.Namespace;
+
+                       XmlDictionaryString itemName = collectionDataContract.CollectionItemName;
+
+                       if (collectionContract.ChildElementNamespace != null)
+                               writer.WriteNamespaceDecl (collectionDataContract.ChildElementNamespace);
+
+                       if (collectionContract.Kind == CollectionKind.Array)
+                       {
+                               Type itemType = collectionContract.ItemType;
+                               int i;
+
+                               // This check does not exist in the original dynamic code,
+                               // but there is no other way to check type mismatch.
+                               // CollectionSerialization.ArrayContract() shows that it is required.
+                               if (objLocal.GetType ().GetElementType () != itemType)
+                                       throw new InvalidCastException (string.Format ("Cannot cast array of {0} to array of {1}", objLocal.GetType ().GetElementType (), itemType));
+
+                               ctx.IncrementArrayCount (writer, (Array) objLocal);
+
+                               if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName, itemNamespace))
+                               {
+                                       var arr = (Array) objLocal;
+                                       var idx = new int [1];
+                                       for (i = 0; i < arr.Length; i++) {
+                                               if (!TryWritePrimitive(itemType, null, null, i, itemNamespace, itemName, 0)) {
+                                                       WriteStartElement (itemType, collectionContract.Namespace, itemNamespace, itemName, 0);
+                                                       idx [0] = i;
+                                                       var mbrVal = arr.GetValue (idx);
+                                                       WriteValue (itemType, mbrVal, false);
+                                                       WriteEndElement ();
+                                               }
+                                       }
+                               }
+                       }
+                       else
+                       {
+                               // This check does not exist in the original dynamic code,
+                               // but there is no other way to check type mismatch.
+                               // CollectionSerialization.ArrayContract() shows that it is required.
+                               if (!collectionContract.UnderlyingType.IsAssignableFrom (objLocal.GetType ()))
+                                       throw new InvalidCastException (string.Format ("Cannot cast {0} to {1}", objLocal.GetType (), collectionContract.UnderlyingType));
+                               
+                               MethodInfo incrementCollectionCountMethod = null;
+                               switch (collectionContract.Kind)
+                               {
+                               case CollectionKind.Collection:
+                               case CollectionKind.List:
+                               case CollectionKind.Dictionary:
+                                       incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
+                                       break;
+                               case CollectionKind.GenericCollection:
+                               case CollectionKind.GenericList:
+                                       incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
+                                       break;
+                               case CollectionKind.GenericDictionary:
+                                       incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
+                                       break;
+                               }
+                               if (incrementCollectionCountMethod != null)
+                                       incrementCollectionCountMethod.Invoke (ctx, new object [] {writer, objLocal});
+
+                               bool isDictionary = false, isGenericDictionary = false;
+                               Type enumeratorType = null;
+                               Type [] keyValueTypes = null;
+                               if (collectionContract.Kind == CollectionKind.GenericDictionary)
+                               {
+                                       isGenericDictionary = true;
+                                       keyValueTypes = collectionContract.ItemType.GetGenericArguments ();
+                                       enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType (keyValueTypes);
+                               }
+                               else if (collectionContract.Kind == CollectionKind.Dictionary)
+                               {
+                                       isDictionary = true;
+                                       keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
+                                       enumeratorType = Globals.TypeOfDictionaryEnumerator;
+                               }
+                               else
+                               {
+                                       enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
+                               }
+                               MethodInfo moveNextMethod = enumeratorType.GetMethod (Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
+                               MethodInfo getCurrentMethod = enumeratorType.GetMethod (Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
+                               if (moveNextMethod == null || getCurrentMethod == null)
+                               {
+                                       if (enumeratorType.IsInterface)
+                                       {
+                                               if (moveNextMethod == null)
+                                                       moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod;
+                                               if (getCurrentMethod == null)
+                                                       getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
+                                       }
+                                       else
+                                       {
+                                               Type ienumeratorInterface = Globals.TypeOfIEnumerator;
+                                               CollectionKind kind = collectionContract.Kind;
+                                               if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
+                                               {
+                                                       Type[] interfaceTypes = enumeratorType.GetInterfaces();
+                                                       foreach (Type interfaceType in interfaceTypes)
+                                                       {
+                                                               if (interfaceType.IsGenericType
+                                                                       && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
+                                                                       && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
+                                                               {
+                                                                       ienumeratorInterface = interfaceType;
+                                                                       break;
+                                                               }
+                                                       }
+                                               }
+                                               if (moveNextMethod == null)
+                                                       moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
+                                               if (getCurrentMethod == null)
+                                                       getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
+                                       }
+                               }
+                               Type elementType = getCurrentMethod.ReturnType;
+                               object currentValue = null; // of elementType
+
+                               var enumerator = (IEnumerator) collectionContract.GetEnumeratorMethod.Invoke (objLocal, new object [0]);
+                               if (isDictionary)
+                               {
+                                       enumerator = new CollectionDataContract.DictionaryEnumerator ((IDictionaryEnumerator) enumerator);
+                               }
+                               else if (isGenericDictionary)
+                               {
+                                       Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
+                                       ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null);
+                                       enumerator = (IEnumerator) Activator.CreateInstance (enumeratorType, new object [] {enumerator});
+                               }
+
+                               var emptyArray = new object [0];
+                               while (enumerator != null && enumerator.MoveNext ()) {
+                                       currentValue = getCurrentMethod.Invoke (enumerator, emptyArray);
+
+                                       if (incrementCollectionCountMethod == null)
+                                               XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke (ctx, new object [] {1});
+
+                                       if (!TryWritePrimitive (elementType, () => currentValue, null, null, itemNamespace, itemName, 0))
+                                       {
+                                               WriteStartElement (elementType, collectionContract.Namespace, itemNamespace, itemName, 0);
+                                               if (isGenericDictionary || isDictionary)
+                                                       collectionDataContract.ItemContract.WriteXmlValue (writer, currentValue, ctx);
+                                               else
+                                                       WriteValue (elementType, currentValue, false);
+                                               WriteEndElement();
+                                       }
+                               }
+                       }
+               }
+
+               int WriteMembers (ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
+               {
+                       int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers (classContract.BaseContract, extensionData, derivedMostClassContract);
+
+                       XmlDictionaryString ns = 
+                               (contractNamespaces == null) ? dataContract.Namespace :
+                               contractNamespaces [typeIndex - 1];
+
+                       ctx.IncrementItemCount (classContract.Members.Count);
+
+                       for (int i = 0; i < classContract.Members.Count; i++, memberCount++) {
+
+                               DataMember member = classContract.Members[i];
+                               Type memberType = member.MemberType;
+                               object memberValue = null;
+                               if (member.IsGetOnlyCollection)
+                                       ctx.StoreIsGetOnlyCollection ();
+                               bool doWrite = true, hasMemberValue = false;
+                               if (!member.EmitDefaultValue)
+                               {
+                                       hasMemberValue = true;
+                                       memberValue = LoadMemberValue (member);
+                                       doWrite = !IsDefaultValue (memberType, memberValue);
+                               }
+
+                               if (doWrite) {
+
+                                       bool writeXsiType = CheckIfMemberHasConflict (member, classContract, derivedMostClassContract);
+                                       if (writeXsiType || !TryWritePrimitive (memberType, hasMemberValue ? () => memberValue : (Func<object>) null, member.MemberInfo, null /*arrayItemIndex*/, ns, null /*nameLocal*/, i + childElementIndex)) {
+                                               WriteStartElement (memberType, classContract.Namespace, ns, null /*nameLocal*/, i + childElementIndex);
+                                               if (classContract.ChildElementNamespaces [i + childElementIndex] != null)
+                                                       writer.WriteNamespaceDecl (childElementNamespaces [i + childElementIndex]);
+                                               if (memberValue == null)
+                                                       memberValue = LoadMemberValue (member);
+                                               WriteValue (memberType, memberValue, writeXsiType);
+                                               WriteEndElement ();
+                                       }
+
+                                       if (classContract.HasExtensionData)
+                                               ctx.WriteExtensionData (writer, extensionData, memberCount);
+                               } else if (!member.EmitDefaultValue) {
+                                       if (member.IsRequired)
+                                               XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted (member.Name, classContract.UnderlyingType);
+                               }
+                       }
+
+                       typeIndex++;
+                       childElementIndex += classContract.Members.Count;
+                       return memberCount;
+               }
+
+
+               internal bool IsDefaultValue (Type type, object value)
+               {
+                       return GetDefaultValue (type).Equals (value);
+               }
+
+               internal object GetDefaultValue(Type type)
+               {
+                       if (type.IsValueType)
+                       {
+                               switch (Type.GetTypeCode(type))
+                               {
+                               case TypeCode.Boolean:
+                                       return false;
+                               case TypeCode.Char:
+                               case TypeCode.SByte:
+                               case TypeCode.Byte:
+                               case TypeCode.Int16:
+                               case TypeCode.UInt16:
+                               case TypeCode.Int32:
+                               case TypeCode.UInt32:
+                                       return 0;
+                               case TypeCode.Int64:
+                               case TypeCode.UInt64:
+                                       return 0L;
+                               case TypeCode.Single:
+                                       return 0.0F;
+                               case TypeCode.Double:
+                                       return 0.0;
+                               case TypeCode.Decimal:
+                                       return default (decimal);
+                               case TypeCode.DateTime:
+                                       return default (DateTime);
+                               }
+                       }
+                       return null;
+               }
+
+               bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
+               {
+                       // Check for conflict with base type members
+                       if (CheckIfConflictingMembersHaveDifferentTypes(member))
+                               return true;
+
+                       // Check for conflict with derived type members
+                       string name = member.Name;
+                       string ns = classContract.StableName.Namespace;
+                       ClassDataContract currentContract = derivedMostClassContract;
+                       while (currentContract != null && currentContract != classContract)
+                       {
+                               if (ns == currentContract.StableName.Namespace)
+                               {
+                                       List<DataMember> members = currentContract.Members;
+                                       for (int j = 0; j < members.Count; j++)
+                                       {
+                                               if (name == members[j].Name)
+                                                       return CheckIfConflictingMembersHaveDifferentTypes(members[j]);
+                                       }
+                               }
+                               currentContract = currentContract.BaseContract;
+                       }
+
+                       return false;
+               }
+
+               bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member)
+               {
+                       while (member.ConflictingMember != null)
+                       {
+                               if (member.MemberType != member.ConflictingMember.MemberType)
+                                       return true;
+                               member = member.ConflictingMember;
+                       }
+                       return false;
+               }
+
+               bool NeedsPrefix(Type type, XmlDictionaryString ns)
+               {
+                       return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
+               }
+
+               void WriteStartElement (Type type, XmlDictionaryString ns, XmlDictionaryString namespaceLocal, XmlDictionaryString nameLocal, int nameIndex)
+               {
+                       bool needsPrefix = NeedsPrefix(type, ns);
+                       nameLocal = nameLocal ?? memberNames [nameIndex];
+                       if (needsPrefix)
+                               writer.WriteStartElement (Globals.ElementPrefix, nameLocal, namespaceLocal);
+                       else
+                               writer.WriteStartElement (nameLocal, namespaceLocal);
+               }
+
+               void WriteEndElement ()
+               {
+                       writer.WriteEndElement ();
+               }
+
+               void WriteValue (Type memberType, object memberValue, bool writeXsiType)
+               {
+                       Pointer memberValueRefPointer = null;
+                       if (memberType.IsPointer)
+                               memberValueRefPointer = (Pointer) XmlFormatGeneratorStatics.BoxPointer.Invoke (null, new object [] {memberValue, memberType});
+                       bool isNullableOfT = (memberType.IsGenericType &&
+                               memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
+                       if (memberType.IsValueType && !isNullableOfT)
+                       {
+                               PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                               if (primitiveContract != null && !writeXsiType)
+                                       primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
+                               else
+                                       InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, () => memberValue, memberType, writeXsiType);
+                       }
+                       else
+                       {
+                               bool isNull;
+                               if (isNullableOfT)
+                                       memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull); //Leaves !HasValue on stack
+                               else
+                                       isNull = memberValue == null;
+                               if (isNull)
+                                       XmlFormatGeneratorStatics.WriteNullMethod.Invoke (ctx, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
+                               else {
+                                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                                       if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) {
+                                               if (isNullableOfT)
+                                                       primitiveContract.XmlFormatContentWriterMethod.Invoke (writer, new object [] {memberValue});
+                                               else                                                    
+                                                       primitiveContract.XmlFormatContentWriterMethod.Invoke (ctx, new object [] {writer, memberValue});
+                                       } else {
+                                               bool isNull2 = false;
+                                               if (memberType == Globals.TypeOfObject || //boxed Nullable<T>
+                                                       memberType == Globals.TypeOfValueType ||
+                                                       ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) {
+                                                       var unwrappedMemberValue = CodeInterpreter.ConvertValue (memberValue, memberType.GetType (), Globals.TypeOfObject);
+                                                       memberValue = unwrappedMemberValue;
+                                                       isNull2 = memberValue == null;
+                                               }
+                                               if (isNull2) {
+                                                       XmlFormatGeneratorStatics.WriteNullMethod.Invoke (ctx, new object [] {writer, memberType, DataContract.IsTypeSerializable(memberType)});
+                                               } else {
+                                                       InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
+                                                               () => memberValue, memberType, writeXsiType);
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               void InternalSerialize (MethodInfo methodInfo, Func<object> memberValue, Type memberType, bool writeXsiType)
+               {
+                       var v = memberValue ();
+                       var typeHandleValue = Type.GetTypeHandle (v);
+                       var isDeclaredType = typeHandleValue.Equals (CodeInterpreter.ConvertValue (v, memberType, Globals.TypeOfObject));
+                       methodInfo.Invoke (ctx, new object [] {writer, memberValue != null ? v : null, isDeclaredType, writeXsiType, DataContract.GetId (memberType.TypeHandle), memberType.TypeHandle});
+               }
+
+               object UnwrapNullableObject(Func<object> memberValue, ref Type memberType, out bool isNull)// Leaves !HasValue on stack
+               {
+                       object v = memberValue ();
+                       isNull = false;
+                       while (memberType.IsGenericType && memberType.GetGenericTypeDefinition () == Globals.TypeOfNullable) {
+                               Type innerType = memberType.GetGenericArguments () [0];
+                               if ((bool) XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v}))
+                                       v = XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod (innerType).Invoke (null, new object [] {v});
+                               else {
+                                       isNull = true;
+                                       v = XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod (memberType).Invoke (null, new object [0]);
+                               }
+                               memberType = innerType;
+                       }
+                       
+                       return v;
+               }
+
+               bool TryWritePrimitive(Type type, Func<object> value, MemberInfo memberInfo, int? arrayItemIndex, XmlDictionaryString ns, XmlDictionaryString name, int nameIndex)
+               {
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+                       if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
+                               return false;
+
+                       object callee = null;
+                       var args = new List<object> ();
+
+                       // load xmlwriter
+                       if (type.IsValueType)
+                               callee = writer;
+                       else {
+                               callee = ctx;
+                               args.Add (writer);
+                       }
+                       // load primitive value 
+                       if (value != null)
+                               args.Add (value ());
+                       else if (memberInfo != null)
+                               args.Add (CodeInterpreter.GetMember (memberInfo, objLocal));
+                       else
+                               args.Add (((Array) objLocal).GetValue (new int [] {(int) arrayItemIndex}));
+                       // load name
+                       if (name != null)
+                               args.Add (name);
+                       else
+                               args.Add (memberNames [nameIndex]);
+                       // load namespace
+                       args.Add (ns);
+                       // call method to write primitive
+                       primitiveContract.XmlFormatWriterMethod.Invoke (callee, args.ToArray ());
+                       return true;
+               }
+
+               bool TryWritePrimitiveArray (Type type, Type itemType, Func<object> value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+               {
+                       PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                       if (primitiveContract == null)
+                               return false;
+
+                       string writeArrayMethod = null;
+                       switch (Type.GetTypeCode(itemType))
+                       {
+                       case TypeCode.Boolean:
+                               writeArrayMethod = "WriteBooleanArray";
+                               break;
+                       case TypeCode.DateTime:
+                               writeArrayMethod = "WriteDateTimeArray";
+                               break;
+                       case TypeCode.Decimal:
+                               writeArrayMethod = "WriteDecimalArray";
+                               break;
+                       case TypeCode.Int32:
+                               writeArrayMethod = "WriteInt32Array";
+                               break;
+                       case TypeCode.Int64:
+                               writeArrayMethod = "WriteInt64Array";
+                               break;
+                       case TypeCode.Single:
+                               writeArrayMethod = "WriteSingleArray";
+                               break;
+                       case TypeCode.Double:
+                               writeArrayMethod = "WriteDoubleArray";
+                               break;
+                       default:
+                               break;
+                       }
+                       if (writeArrayMethod != null)
+                       {
+                               typeof (XmlWriterDelegator).GetMethod (writeArrayMethod, Globals.ScanAllMembers, null, new Type[] { type, typeof (XmlDictionaryString), typeof (XmlDictionaryString) }, null).Invoke (writer, new object [] {value (), itemName, itemNamespace});
+                               return true;
+                       }
+                       return false;
+               }
+
+               object LoadMemberValue (DataMember member)
+               {
+                       return CodeInterpreter.GetMember (member.MemberInfo, objLocal);
+               }
+       }
+}
index 580a0bb94822a89956f89accac7352ed969b4394..8c375632f505f92d178b2c160fd44212e6f58d80 100644 (file)
@@ -2,66 +2,18 @@
 ../../build/common/Locale.cs
 ../../build/common/MonoTODOAttribute.cs
 Assembly/AssemblyInfo.cs
-System.Runtime.Serialization.Configuration/DataContractSerializerSection.cs
-System.Runtime.Serialization.Configuration/DeclaredTypeElement.cs
-System.Runtime.Serialization.Configuration/DeclaredTypeElementCollection.cs
-System.Runtime.Serialization.Configuration/ParameterElement.cs
-System.Runtime.Serialization.Configuration/ParameterElementCollection.cs
-System.Runtime.Serialization.Configuration/SerializationSectionGroup.cs
-System.Runtime.Serialization.Configuration/TypeElement.cs
-System.Runtime.Serialization.Configuration/TypeElementCollection.cs
-../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/CollectionDataContractAttribute.cs
-../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ContractNamespaceAttribute.cs
-../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractAttribute.cs
-System.Runtime.Serialization/DataContractResolver.cs
-System.Runtime.Serialization/DataContractSerializer.cs
-System.Runtime.Serialization/DataMemberAttribute.cs
-System.Runtime.Serialization/EnumMemberAttribute.cs
-System.Runtime.Serialization/ExportOptions.cs
-System.Runtime.Serialization/ExtensionDataObject.cs
-System.Runtime.Serialization/IDataContractSurrogate.cs
-System.Runtime.Serialization/IExtensibleDataObject.cs
-System.Runtime.Serialization/IgnoreDataMemberAttribute.cs
-System.Runtime.Serialization/ImportOptions.cs
-System.Runtime.Serialization/InvalidDataContractException.cs
-System.Runtime.Serialization/KnownTypeAttribute.cs
-System.Runtime.Serialization/KnownTypeCollection.cs
-System.Runtime.Serialization/NetDataContractSerializer.cs
-System.Runtime.Serialization/SerializationMap.cs
-System.Runtime.Serialization/SerializationMap.XsdExporter.cs
-System.Runtime.Serialization/XmlFormatterDeserializer.cs
-System.Runtime.Serialization/XmlFormatterSerializer.cs
-System.Runtime.Serialization/XmlObjectSerializer.cs
-System.Runtime.Serialization/XmlSerializableServices.cs
-System.Runtime.Serialization/XsdDataContractExporter.cs
-System.Runtime.Serialization/XsdDataContractImporter.cs
-System.Xml/IFragmentCapableXmlDictionaryWriter.cs
-System.Xml/IStreamProvider.cs
-System.Xml/IXmlBinaryReaderInitializer.cs
-System.Xml/IXmlBinaryWriterInitializer.cs
-System.Xml/IXmlDictionary.cs
-System.Xml/IXmlMtomReaderInitializer.cs
-System.Xml/IXmlMtomWriterInitializer.cs
-System.Xml/IXmlUTF8ReaderInitializer.cs
-System.Xml/IXmlUTF8WriterInitializer.cs
-System.Xml/OnXmlDictionaryReaderClose.cs
-System.Xml/UniqueId.cs
-System.Xml/XmlBinaryDictionaryReader.cs
-System.Xml/XmlBinaryDictionaryWriter.cs
-System.Xml/XmlBinaryDictionaryWriterAutoGen.cs
-System.Xml/XmlBinaryFormat.cs
-System.Xml/XmlBinaryReaderSession.cs
-System.Xml/XmlBinaryWriterSession.cs
-System.Xml/XmlC14NWriter.cs
-System.Xml/XmlCanonicalWriter.cs
-System.Xml/XmlDictionary.cs
-System.Xml/XmlDictionaryReader.cs
-System.Xml/XmlDictionaryReaderAutoGen.cs
-System.Xml/XmlDictionaryReaderQuotas.cs
-System.Xml/XmlDictionaryString.cs
-System.Xml/XmlDictionaryWriter.cs
-System.Xml/XmlDictionaryWriterAutoGen.cs
-System.Xml/XmlMtomDictionaryReader.cs
-System.Xml/XmlMtomDictionaryWriter.cs
-System.Xml/XmlSimpleDictionaryReader.cs
-System.Xml/XmlSimpleDictionaryWriter.cs
+
+ReferenceSources/DiagnosticUtility.cs
+ReferenceSources/FxTrace.cs
+ReferenceSources/SR.cs
+ReferenceSources/SR_missing.cs
+ReferenceSources/XmlExceptionHelper.cs
+
+ReferenceSources/BitFlagsGenerator.cs
+ReferenceSources/CodeInterpreter.cs
+ReferenceSources/JsonFormatReaderGenerator_static.cs
+ReferenceSources/JsonFormatWriterGenerator_static.cs
+ReferenceSources/XmlDataContract_static.cs
+ReferenceSources/XmlFormatReaderGenerator_static.cs
+ReferenceSources/XmlFormatWriterGenerator_static.cs
+
index 0fc956d862074bef6efc18df22ce0de563bbe21e..03264c43f51f21f3d7535cad350a672f1393881a 100755 (executable)
@@ -137,9 +137,7 @@ namespace MonoTests.System.Runtime.Serialization
                        MemoryStream sw = new MemoryStream ();
                        ser.WriteObject (sw, 1);
                        string expected = "<int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">1</int>";
-                       byte[] buf = sw.ToArray ();
-                       // Skip the utf8 bom
-                       Assert.AreEqual (expected, Encoding.UTF8.GetString (buf, 3, buf.Length - 3));
+                       Assert.AreEqual (expected, Encoding.UTF8.GetString (sw.ToArray ()));
                }
 
                [Test]
@@ -1641,7 +1639,7 @@ namespace MonoTests.System.Runtime.Serialization
                                        + "<SecondId>ID-GOES-HERE</SecondId>"
                                        + "</MyData>";
                        var serializer = new DataContractSerializer (typeof (MyData));
-                       using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (whatItGets)))
+                       using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (whatItGets.Replace ("ID-GOES-HERE", Guid.NewGuid ().ToString ()))))
                        {
                                var data = serializer.ReadObject (stream);
                        }
index 690ebfe36eaacd57b29ffada790d6a6995c7aadd..9687913986155d8efee563ec507ea14329075e61 100644 (file)
@@ -244,7 +244,7 @@ namespace MonoTests.System.Runtime.Serialization
                        Assert.That (ret, Is.Not.Null, "#2");
                        
                        Assert.That (ret.ArrayRank, Is.EqualTo (0), "#3");
-                       Assert.That (ret.BaseType, Is.EqualTo ("TestWCF.Model.MyCollectionOfdouble"), "#4");
+                       Assert.That (ret.BaseType, Is.EqualTo ("TestWCF.Model1.MyCollectionOfdouble"), "#4");
                        Assert.That (ret.TypeArguments.Count, Is.EqualTo (0), "#5");
                }
 
index d57dbb698d0f77fa0cf3a27c6b932573c684404f..31ca0721bbc91266891823ce72affb817a446d64 100644 (file)
@@ -47,7 +47,6 @@ namespace MonoTests.System.Xml
                {
                        MemoryStream ms = new MemoryStream ();
                        var w = XmlDictionaryWriter.CreateMtomWriter (ms, Encoding.UTF8, 10000, "sTaRt", "myboundary", "urn:foo", false, false);
-                       w.WriteStartDocument ();
                        w.WriteStartElement ("root");
                        w.WriteRaw ("RAW");
                        w.WriteStartElement ("foo");
@@ -79,11 +78,11 @@ Content-ID: <urn:foo>
 Content-Transfer-Encoding: 8bit
 Content-Type: application/xop+xml;charset=utf-8;type=""sTaRt""
 
-<root>RAW<foo>bcdMjxG<arr>true</arr><arr>false</arr><arr>true</arr>AQIDBAU=999&#xD;
-&#xD;
+<root>RAW<foo>bcdMjxG<arr>true</arr><arr>false</arr><arr>true</arr>AQIDBAU=999&#xD;XXX
+&#xD;XXX
 666</foo></root>
 --myboundary--
-<root/><root/><root/>".Replace ("\n", "\r\n");
+<root/><root/><root/>".Replace ("\n", "\r\n").Replace ("XXX\r\n", "\n");
        }
 
        class MyStreamProvider : IStreamProvider
index 3946206a0bf0d9fcce0ceb38e65f0eff62039ec5..c0c73b07ad060fd22023aa3448912020fa0071df 100644 (file)
@@ -1,63 +1,5 @@
-Assembly/AssemblyInfo.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/DataContractJsonSerializer.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/DataContractJsonSerializerSettings.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/IXmlJsonReaderInitializer.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/IXmlJsonWriterInitializer.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/JsonReader.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/JsonReaderWriterFactory.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/JsonSerializationReader.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/JsonSerializationWriter.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/JsonWriter.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/TypeMap.cs
-../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/CollectionDataContractAttribute.cs
-../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/ContractNamespaceAttribute.cs
-../../../external/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/DataContractAttribute.cs
-System.Runtime.Serialization/DataContractResolver.cs
-System.Runtime.Serialization/DataContractSerializer.cs
-System.Runtime.Serialization/DataContractSerializerSettings.cs
-System.Runtime.Serialization/DataMemberAttribute.cs
-System.Runtime.Serialization/DateTimeFormat.cs
-System.Runtime.Serialization/EmitTypeInformation.cs
-System.Runtime.Serialization/EnumMemberAttribute.cs
-System.Runtime.Serialization/ExportOptions.cs
-System.Runtime.Serialization/ExtensionDataObject.cs
-System.Runtime.Serialization/IDataContractSurrogate.cs
-System.Runtime.Serialization/IExtensibleDataObject.cs
-System.Runtime.Serialization/IgnoreDataMemberAttribute.cs
-System.Runtime.Serialization/InvalidDataContractException.cs
-System.Runtime.Serialization/KnownTypeAttribute.cs
-System.Runtime.Serialization/KnownTypeCollection.cs
-System.Runtime.Serialization/NetDataContractSerializer.cs
-System.Runtime.Serialization/SerializationMap.cs
-System.Runtime.Serialization/XmlFormatterDeserializer.cs
-System.Runtime.Serialization/XmlFormatterSerializer.cs
-System.Runtime.Serialization/XmlObjectSerializer.cs
-System.Xml/IStreamProvider.cs
-System.Xml/IXmlBinaryReaderInitializer.cs
-System.Xml/IXmlBinaryWriterInitializer.cs
-System.Xml/IXmlDictionary.cs
-System.Xml/IXmlMtomReaderInitializer.cs
-System.Xml/IXmlMtomWriterInitializer.cs
-System.Xml/IXmlUTF8ReaderInitializer.cs
-System.Xml/IXmlUTF8WriterInitializer.cs
-System.Xml/OnXmlDictionaryReaderClose.cs
-System.Xml/UniqueId.cs
-System.Xml/XmlBinaryDictionaryReader.cs
-System.Xml/XmlBinaryDictionaryWriter.cs
-System.Xml/XmlBinaryDictionaryWriterAutoGen.cs
-System.Xml/XmlBinaryFormat.cs
-System.Xml/XmlBinaryReaderSession.cs
-System.Xml/XmlBinaryWriterSession.cs
-System.Xml/XmlC14NWriter.cs
-System.Xml/XmlCanonicalWriter.cs
-System.Xml/XmlDictionary.cs
-System.Xml/XmlDictionaryReader.cs
-System.Xml/XmlDictionaryReaderAutoGen.cs
-System.Xml/XmlDictionaryReaderQuotas.cs
-System.Xml/XmlDictionaryString.cs
-System.Xml/XmlDictionaryWriter.cs
-System.Xml/XmlDictionaryWriterAutoGen.cs
-System.Xml/XmlSimpleDictionaryReader.cs
-System.Xml/XmlSimpleDictionaryWriter.cs
-System.Xml/OnXmlDictionaryReaderClose.cs
+#include System.Runtime.Serialization.dll.sources
+#include ReferenceSource.common.sources
+
+ReferenceSources/SchemaExporter_mobile.cs
+ReferenceSources/SimplifiedCodeTypeReference.cs
index be9e8242268f4e377083e0fac77b3e4da22d1ccc..a26b31febb036df6edf76204afba107eee1426f4 100644 (file)
@@ -1,5 +1,3 @@
-#include net_4_0_System.Runtime.Serialization.dll.sources
-System.Runtime.Serialization/DateTimeFormat.cs
-System.Runtime.Serialization/EmitTypeInformation.cs
-../System.ServiceModel.Web/System.Runtime.Serialization.Json/DataContractJsonSerializerSettings.cs
-System.Runtime.Serialization/DataContractSerializerSettings.cs
+#include System.Runtime.Serialization.dll.sources
+#include ReferenceSource.common.sources
+#include ReferenceSource.desktop.sources
index 3a40bb20ec96f0275abd84725b371f4876db7b2f..8a59e57f34149998efcb05a3a7fc41ee232e7905 100644 (file)
@@ -79,7 +79,7 @@ namespace MonoTests.System.ServiceModel.Discovery
 
                [Test]
                // looks like EndpointAddress is *ignored*
-               [Category ("NotOnMac")]
+               [Category ("NotWorking")]
                public void AnnonceOnlineOfflineAddressSchemeMismatch ()
                {
                        var ac = new AnnouncementClient (new UdpAnnouncementEndpoint () { Address = new EndpointAddress ("http://localhost:37564")});
index a246259b5d54227cf0f9336ce23c8a88651bcbbd..24b5d2fc2e9b93f44c0ac70a9941155b47d5602d 100644 (file)
@@ -11,4 +11,8 @@ LIB_MCS_FLAGS = /unsafe
 
 TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
+EXTRA_DISTFILES = 
+
+NO_TEST = yes
+
 include ../../build/library.make
index 380b054468a5dcfc7f6ec2811ab4457ce43cf9a8..b438b10968481216020eb087dce8d5b0e6b6a0f6 100644 (file)
@@ -178,12 +178,12 @@ namespace System.ServiceModel.Channels
                                using (XmlWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (new StreamWriter (stream, source.WriteEncoding))))
                                        message.WriteMessage (w);
 #else
-                               using (XmlWriter w = XmlDictionaryWriter.CreateTextWriter (stream, source.WriteEncoding))
+                               using (XmlWriter w = XmlDictionaryWriter.CreateTextWriter (stream, source.WriteEncoding, false))
                                        message.WriteMessage (w);
 #endif
                                break;
                        case WebContentFormat.Json:
-                               using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (stream, source.WriteEncoding))
+                               using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (stream, source.WriteEncoding, false))
                                        message.WriteMessage (w);
                                break;
                        case WebContentFormat.Raw:
index c9a78ea3420d19f36f5ac6a3db101f796fbb70c3..00e44579760024f920006cb20a04bcc9355d57d3 100644 (file)
@@ -80,7 +80,7 @@ namespace System.ServiceModel.Syndication
                        Add (new SyndicationElementExtension (xmlReader));
                }
 
-               new void Add (SyndicationElementExtension item)
+               internal new void Add (SyndicationElementExtension item)
                {
                        base.Add (item);
                }
index bc268c4c669fc2c7e28eccf0d42f4853d34badb6..b380fd834ad074115d7a09271b23ccbb492db52c 100644 (file)
@@ -95,7 +95,7 @@ namespace System.ServiceModel.Syndication
                                if (!(r is XmlDictionaryReader))
                                        r = XmlDictionaryReader.CreateDictionaryReader (r);
                                var ms = new MemoryStream ();
-                               var xw = XmlDictionaryWriter.CreateBinaryWriter (ms);
+                               var xw = XmlDictionaryWriter.CreateBinaryWriter (ms, null, null, false);
                                xw.WriteStartElement ("content", Namespaces.Atom10);
                                xw.WriteAttributeString ("type", "text/xml");
                                while (!r.EOF)
index 8a11d70baf12597633b386afe2b730be9546d3ed..21eef3451a0525b3894e0f86a7b46ec9adf1c068 100644 (file)
@@ -1083,7 +1083,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (SerializationException))]
-               [Category ("NotDotNet")] // 0.0 is an invalid Colors value.
+               [Ignore ("NotDotNet")] // 0.0 is an invalid Colors value.
                public void DeserializeEnumInvalid3 ()
                {
                        //"0.0" instead of "0"
@@ -1104,7 +1104,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (SerializationException))]
-               [Category ("NotDotNet")] // 4 is an invalid Colors value.
+               [Ignore ("NotDotNet")] // 4 is an invalid Colors value.
                [Category ("NotWorking")]
                public void DeserializeEnumWithDCInvalid ()
                {
@@ -1360,8 +1360,8 @@ namespace MonoTests.System.Runtime.Serialization.Json
                        var ms = new MemoryStream ();
                        DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
                        Query query = new Query () {
-                               StartDate = new DateTime (2010, 3, 4, 5, 6, 7),
-                               EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
+                               StartDate = DateTime.SpecifyKind (new DateTime (2010, 3, 4, 5, 6, 7), DateTimeKind.Utc),
+                               EndDate = DateTime.SpecifyKind (new DateTime (2010, 4, 5, 6, 7, 8), DateTimeKind.Utc)
                                };
                        serializer.WriteObject (ms, query);
                        Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
@@ -1386,14 +1386,14 @@ namespace MonoTests.System.Runtime.Serialization.Json
                [Test]
                public void BugXamarin163 ()
                {
-                       string json = @"{""should_have_value"":""\/Date(1277355600000-0500)\/""}";
+                       string json = @"{""should_have_value"":""\/Date(1277355600000)\/""}";
 
                        byte[] bytes = global::System.Text.Encoding.UTF8.GetBytes(json);
                        Stream inputStream = new MemoryStream(bytes);
                        
                        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
                        DateTest t = serializer.ReadObject(inputStream) as DateTest;
-                       Assert.AreEqual (634129344000000000, t.ShouldHaveValue.Value.Ticks, "#1");
+                       Assert.AreEqual (634129524000000000, t.ShouldHaveValue.Value.Ticks, "#1");
                }
 
                [Test]
@@ -2069,6 +2069,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
                void Init ()
                {
                        C = true;
+                       ServerTimeUTC = DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);
                }
 
                [OnDeserializing]
index c19cedaab1e2f2116df80fe25d9b3fd94b875bc8..c95c3b62352418dc98e81ac95c74f6155a0d514e 100644 (file)
@@ -509,7 +509,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
                // Read() valid and invalid contents
 
                [Test]
-               [ExpectedException (typeof (XmlException))]
+               [Ignore ("It should throw XmlException for parser error, but .NET fails to report that")]
                public void ReadTwoTopLevelContents ()
                {
                        ReadToEnd (CreateReader ("{}{}"));
@@ -537,7 +537,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
                }
 
                [Test]
-               [ExpectedException (typeof (XmlException))]
+               [Ignore ("It should throw XmlException for parser error, but .NET fails to report that")]
                public void ReadExtraCloseCurly2 ()
                {
                        ReadToEnd (CreateReader ("{}}"));
@@ -566,7 +566,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // hmm, why does it pass?
+               [Ignore ("NotDotNet")] // hmm, why does it pass?
                public void ReadExtraCloseBrace2 ()
                {
                        ReadToEnd (CreateReader ("[]]"));
@@ -655,7 +655,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidNumber3 ()
                {
                        ReadToEnd (CreateReader ("01"));
@@ -670,7 +670,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidNumber5 ()
                {
                        ReadToEnd (CreateReader ("10."));
@@ -685,7 +685,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidNumber8 ()
                {
                        ReadToEnd (CreateReader ("-e5"));
@@ -693,7 +693,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidNumber9 ()
                {
                        ReadToEnd (CreateReader ("-e5.5"));
@@ -714,7 +714,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidObjectContent2 ()
                {
                        ReadToEnd (CreateReader ("{\"A\": 123 456}"));
@@ -729,7 +729,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidObjectContent4 ()
                {
                        ReadToEnd (CreateReader ("{\"A\":123, \"B\":456,}"));
@@ -744,7 +744,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidArrayContent2 ()
                {
                        ReadToEnd (CreateReader ("[123 456]"));
@@ -759,7 +759,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
 
                [Test]
                [ExpectedException (typeof (XmlException))]
-               [Category ("NotDotNet")] // likely .NET bug
+               [Ignore ("NotDotNet")] // likely .NET bug
                public void ReadInvalidArrayContent4 ()
                {
                        ReadToEnd (CreateReader ("[123,456,]"));
@@ -876,7 +876,7 @@ namespace MonoTests.System.Runtime.Serialization.Json
                                DataContractJsonSerializer jsonSerializer = new
                                        DataContractJsonSerializer(typeof(IEnumerable<string>));
                                var result = jsonSerializer.ReadObject(stream);
-                               Assert.AreEqual (typeof (List<string>), result.GetType ());
+                               Assert.AreEqual (typeof (string []), result.GetType ());
                        }
                }
        }
index 4ea004a34e86c7b60d01da5951b7069d8ff636d5..b6e42b90bb0dafaee233cf63ea37187a3bcd2a46 100644 (file)
@@ -28,6 +28,7 @@
 using System;
 using System.IO;
 using System.Text;
+using System.Runtime.Serialization;
 using System.Runtime.Serialization.Json;
 using System.Xml;
 using NUnit.Framework;
@@ -51,6 +52,39 @@ namespace MonoTests.System.Runtime.Serialization.Json
                        w = JsonReaderWriterFactory.CreateJsonWriter (ms);
                }
 
+               /*
+               [Test]
+               public void Dummy_BitFlagsGenerator ()
+               {
+                       var b = new BitFlagsGenerator (2);
+                       Assert.IsFalse (b.Load (0), "#a1");
+                       b.Store (0, false);
+                       Assert.IsFalse (b.Load (0), "#a2");
+                       b.Store (0, true);
+                       Assert.IsTrue (b.Load (0), "#a3");
+                       Assert.IsFalse (b.Load (1), "#a4");
+                       b.Store (0, false);
+                       Assert.IsFalse (b.Load (0), "#a5");
+                       Assert.IsFalse (b.Load (1), "#a6");
+
+                       Assert.IsFalse (b.Load (1), "#b1");
+                       b.Store (1, false);
+                       Assert.IsFalse (b.Load (1), "#b2");
+                       b.Store (1, true);
+                       Assert.IsTrue (b.Load (1), "#b3");
+                       b.Store (1, false);
+                       Assert.IsFalse (b.Load (1), "#b4");
+
+                       var bytes = new byte [2];
+                       Assert.IsFalse (BitFlagsGenerator.IsBitSet (bytes, 0), "#c1");
+                       BitFlagsGenerator.SetBit (bytes, 0);
+                       Assert.IsTrue (BitFlagsGenerator.IsBitSet (bytes, 0), "#c2");
+                       Assert.IsFalse (BitFlagsGenerator.IsBitSet (bytes, 1), "#c3");
+                       BitFlagsGenerator.SetBit (bytes, 0);
+                       Assert.IsTrue (BitFlagsGenerator.IsBitSet (bytes, 0), "#c4");
+               }
+               */
+
                [Test]
                [ExpectedException (typeof (ArgumentNullException))]
                public void ConstructorNullStream ()
index f3b3bc0933df511651dba3baca09ac1ab5f3821f..0140f3c1b5856f231c99771f92b7e29602f8cc33 100644 (file)
@@ -1,3 +1,6 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
 Assembly/AssemblyInfo.cs
 Assembly/TypeForwarders.cs
 System.ServiceModel.Channels/WebBodyFormatMessageProperty.cs
index ab76a512211bf8114ce564a3ad2d958743a6a9ec..fc379b2e588c954c49948dd5a3c7285d66a6a69f 100644 (file)
@@ -120,7 +120,7 @@ namespace System.ServiceModel.Channels
                {
                        VerifyMessageVersion (message);
 
-                       using (var xw = XmlDictionaryWriter.CreateBinaryWriter (stream, Constants.SoapDictionary, session ? CurrentWriterSession : null))
+                       using (var xw = XmlDictionaryWriter.CreateBinaryWriter (stream, Constants.SoapDictionary, session ? CurrentWriterSession : null, false))
                                message.WriteMessage (xw);
                }
 
index ec14a780bb07007b121c0f48379eca8420092253..f67ce5dd8ad5a357f0d1408aec19137c4e16ac62 100644 (file)
@@ -258,9 +258,16 @@ namespace System.ServiceModel.Channels
                                WriteBodyContents (body);
                        }
 
+                       var nt = new NameTable ();
+                       var nsmgr = new XmlNamespaceManager (nt);
+                       nsmgr.AddNamespace ("s", Version.Envelope.Namespace);
+                       nsmgr.AddNamespace ("a", Version.Addressing.Namespace);
+                       var pc = new XmlParserContext (nt, nsmgr, null, XmlSpace.None);
+                       
                        var rs = new XmlReaderSettings ();
                        rs.ConformanceLevel = ConformanceLevel.Auto;
-                       return XmlDictionaryReader.CreateDictionaryReader (XmlReader.Create (new StringReader (sw.ToString ()), rs));
+                       
+                       return XmlDictionaryReader.CreateDictionaryReader (XmlReader.Create (new StringReader (sw.ToString ()), rs, pc));
                }
 
                protected abstract void OnWriteBodyContents (
index dccf9bedfba17297d994ab083bd32a61ce5b8d21..130f13fbebe8a4faf15b9706e1d98796fb3ec03c 100644 (file)
@@ -99,17 +99,6 @@ namespace System.ServiceModel.Description
 
                #region internals required for moonlight compatibility
 
-#if NET_2_1  // it uses S.R.Serialization internals which is InternalVisible to this assembly only in 2.1. So, DON'T use this member in full 2.0 profile.
-               XmlName msg_name;
-               internal XmlName MessageName {
-                       get {
-                               if (msg_name == null)
-                                       msg_name = new XmlName (KnownTypeCollection.GetStaticQName (MessageType).Name);
-                               return msg_name;
-                       }
-               }
-#endif
-
                internal bool IsTypedMessage {
                        get { return MessageType == null; }
                }
index eaaa7b4eb2731dcfca00578a2d9e0a0c2ebfeebf..be5e051ff47524fa6ac28485f5baaa1836fa7e1a 100644 (file)
@@ -96,8 +96,9 @@ namespace System.ServiceModel.Description
                                        MetadataSection.CreateFromServiceDescription (sd));
 
                        foreach (XmlSchema xs in GeneratedXmlSchemas.Schemas ())
-                               metadata.MetadataSections.Add (
-                                       MetadataSection.CreateFromSchema (xs));
+                               if (xs.TargetNamespace != XmlSchema.Namespace)
+                                       metadata.MetadataSections.Add (
+                                               MetadataSection.CreateFromSchema (xs));
                                
                        return metadata;
                }
@@ -459,7 +460,6 @@ namespace System.ServiceModel.Description
                        get {
                                if (xsd_exporter == null)
                                        xsd_exporter = new XsdDataContractExporter ();
-
                                return xsd_exporter;
                        }
                }
@@ -651,6 +651,9 @@ namespace System.ServiceModel.Description
                                        return;
                        }
 
+                       if (ns == string.Empty)
+                               return;
+
                        XmlSchemaImport imp = new XmlSchemaImport ();
                        imp.Namespace = ns;
                        schema.Includes.Add (imp);
index 5986f5e3869d6ef7628bd7916876039a2d63ea7c..355a3941c49773033d6a5496df503c5a8a417a99 100644 (file)
@@ -62,14 +62,14 @@ using System.Runtime.InteropServices;
 #endif
 
 #if NET_2_1
-       [assembly: InternalsVisibleTo ("System.Runtime.Serialization, PublicKey=00240000048000009400000006020000002400005253413100040000010001008D56C76F9E8649383049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B37AB")]
        [assembly: InternalsVisibleTo ("System.ServiceModel.Web, PublicKey=00240000048000009400000006020000002400005253413100040000010001008D56C76F9E8649383049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B37AB")]
        // System.Xml.Serialization (from Microsoft Silverlight 2.0 SDK) requires access to System.Xml internals
        [assembly: InternalsVisibleTo ("System.Xml.Serialization, PublicKey=" + AssemblyRef.FrameworkPublicKeyFull)]
 #else
        [assembly: AllowPartiallyTrustedCallers]
 #endif
-       [assembly: InternalsVisibleTo ("System.Xml.Linq, PublicKey=" + AssemblyRef.FrameworkPublicKeyFull)]
+       [assembly: InternalsVisibleTo ("System.Runtime.Serialization, PublicKey=" + AssemblyRef.FrameworkPublicKeyFull, AllInternalsVisible = false)]
+       [assembly: InternalsVisibleTo ("System.Xml.Linq, PublicKey=" + AssemblyRef.FrameworkPublicKeyFull, AllInternalsVisible = false)]
 
 [assembly: AssemblyFileVersion (Consts.FxFileVersion)]
 [assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]